<template>
  <div v-loading="listLoading">
    <div style="padding:20px">
      <el-form ref="form" :model="form" label-width="210px">
        <!-- 动态生成表单项 -->
        <el-row v-for="(item, index) in uploadConfig" :key="index">
          <el-col :span="12">
            <el-form-item v-if="dialogType !== 'savePhoto'" :label="`已上传${item.label}`">
              <div>
                <img :src="config.fileUrl + form[item.prop]" width="100" height="100">
              </div>
            </el-form-item>
            <el-form-item :label="item.label" :prop="item.prop">
              <el-upload
                ref="photoUpload"
                :file-list="form[item.prop]"
                :multiple="false"
                :limit="1"
                :class="{hide: item.hideUpload}"
                :auto-upload="false"
                :on-remove="(file, fileList) => handleRemove(file, fileList, item.prop)"
                :on-change="(file, fileList) => handleChange(file, fileList, item.prop)"
                action="#"
                accept=".jpg,.jpeg,.png"
                list-type="picture-card">
                <i class="el-icon-plus"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="ui-height"/>
    <div class="ui-foot">
      <el-button type="success" @click="confirm">保 存</el-button>
      <el-button plain type="info" @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import {requestFN} from '@/utils/request'
import SelectTree from '@/components/SelectTree'
import {upload} from "../../../../../utils/upload";

export default {
  components: {Pagination, SelectTree},
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 10
      },
      config: config,
      areaList: [], // 省市县列表
      placeList: [],
      listLoading: true,
      varList: [],
      total: 0,
      title: '',
      isShow: false,
      addDialogVisible: false,
      dialogType: 'savePhoto',
      addForm: {
        LICENCE_NO: '', // 车牌号
        MOTORCADE_ID: '', // 所属车队ID
        CORPINFO_ID: '',
        LICENCE_TYPE: '',
        VEHICLE_TYPE: '',
        CONTACT: '',
        PHONE: '',
        EMISSION_STANDARDS: '',
      },
      form: {
        CORPINFO_ID: JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID,
        MOTORCADE_ID: this.$parent.MOTORCADE_ID,
        REQUISITION_FILE: '',
        COMMITMENT_FILE: '',
        LICENSE_FILE: '',
        TRANSPORT_PERMIT_FILE: '',
        HAZARDOUS_CHEMICALS_FILE: ''
      },
      uploadConfig: [
        {label: '智能口门管理系统账号申请单', prop: 'REQUISITION_FILE', hideUpload: false},
        {label: '智能口门管理系统使用承诺书', prop: 'COMMITMENT_FILE', hideUpload: false},
        {label: '营业执照', prop: 'LICENSE_FILE', hideUpload: false},
        {label: '道路运输经营许可证', prop: 'TRANSPORT_PERMIT_FILE', hideUpload: false},
        {label: '危险化学品经营许可证', prop: 'HAZARDOUS_CHEMICALS_FILE', hideUpload: false}
      ]
    }
  },
  async created() {
    this.getList()
    this.getUploadedFiles()
  },
  methods: {
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    // 重置
    reset() {
      this.form = {
        USER_NAME: '',
        PHONE: '',
        ID_CARD: '',
        CORPINFO_NAME: '',
        DEPARTMENT_NAME: '',
        VISIT_START_TIME: '',
        VISIT_END_TIME: '',
        DOOR_NAME: ''
      }
      this.getList()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
          '/mkmj/management/carInfoList?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page, this.form
      ).then((data) => {
        console.log(data)
        this.listLoading = false
        this.varList = data.carInfoList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 通用文件移除处理
    handleRemove(file, fileList, prop) {
      this.form[prop] = fileList;
      const configItem = this.uploadConfig.find(item => item.prop === prop);
      if (configItem) {
        configItem.hideUpload = fileList.length >= 1;
      }
    },
    // 通用文件上传处理
    handleChange(file, fileList, prop) {
      const types = ['image/jpeg', 'image/jpg', 'image/png'];
      const isImage = types.includes(file.raw.type);
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!');
        fileList.pop();
        this.form[prop] = [];
        return;
      }
      this.form[prop] = [];
      this.form[prop].push(file);
      const configItem = this.uploadConfig.find(item => item.prop === prop);
      if (configItem) {
        configItem.hideUpload = fileList.length >= 1;
      }
    },
    getUploadedFiles() {
      try {
        const response = requestFN('/mkmj/management/getUploadedFiles', {
          MOTORCADE_ID: this.form.MOTORCADE_ID
        });

        // 检查响应是否成功
        if (response && response.result === "success" && response.corpFilingApplicationEntity) {
          const uploadedFiles = response.corpFilingApplicationEntity;

          // 遍历 uploadConfig 配置
          this.uploadConfig.forEach(item => {
            if (uploadedFiles[item.prop]) {
              // 将已上传的文件信息填充到 form 对象中
              this.form[item.prop] = [{
                url: this.config.fileUrl + uploadedFiles[item.prop], // 拼接完整的文件 URL
                name: uploadedFiles[item.prop] // 文件名
              }];
            }
          });
        }
      } catch (error) {
        console.error('获取已上传文件失败', error);
      }
    },
    confirm() {
      this.listLoading = true;
      console.log(this.form);
      const formData = new FormData();
      formData.append('CORPINFO_ID', this.form.CORPINFO_ID);
      formData.append("MOTORCADE_ID",this.form.MOTORCADE_ID);
      formData.append('REQUISITION_FILE', this.form.REQUISITION_FILE[0].raw);
      formData.append('COMMITMENT_FILE', this.form.COMMITMENT_FILE[0].raw);
      formData.append('LICENSE_FILE', this.form.LICENSE_FILE[0].raw);
      formData.append('TRANSPORT_PERMIT_FILE', this.form.TRANSPORT_PERMIT_FILE[0].raw);
      formData.append('HAZARDOUS_CHEMICALS_FILE', this.form.HAZARDOUS_CHEMICALS_FILE[0].raw);

      console.log(formData); // 打印 FormData 对象

      upload(
        '/mkmj/management/fleetFilingApply',
        formData
      ).then(response => {
        console.log('上传成功', response);
        this.listLoading = false;
        this.goBack()
      }).catch(error => {
        console.error('上传失败', error);
        this.listLoading = false;
      });
    },
    goBack() {
      this.$parent.activeName = 'List'
    }
  }
}
</script>