<template>
  <!-- 
    整页表单的分片表单
    v 1.0
    2021-05-12
    Lufthafen
  -->
  <a-form-model
    :label-col="labelCol"
    :model="form"
    :rules="rules"
    :wrapper-col="wrapperCol"
    ref="form"
  >
    <a-spin :spinning="loading">
      <a-icon slot="indicator" spin type="loading" />
      <!-- 表单控件 -->
      <!-- ... -->
      <a-row :gutter="16" type="flex">
        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="立项文件" prop="houseInfo.anEntryDocument">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.anEntryDocument"
              :showUploadList=" { showRemoveIcon: true, showDownloadIcon: true }"
              @change="(data) => onFileChange(data, 'anEntryDocument')"
              @download="onFileDownload"
            >
              <a-button icon="upload" type="dashed">上传立项文件</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>

        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="规划许可" prop="houseInfo.planningPermission">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.planningPermission"
              :showUploadList=" { showRemoveIcon: true, showDownloadIcon: true }"
              @change="(data) => onFileChange(data, 'planningPermission')"
              @download="onFileDownload"
            >
              <a-button icon="upload" type="dashed">上传规划许可</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>

        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="竣工验收备案" prop="houseInfo.completionRecord">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.completionRecord"
              :showUploadList=" { showRemoveIcon: true, showDownloadIcon: true }"
              @change="(data) => onFileChange(data, 'completionRecord')"
              @download="onFileDownload"
            >
              <a-button icon="upload" type="dashed">上传竣工验收备案</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>

        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="监理文件" prop="houseInfo.monitorDocument">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.monitorDocument"
              :showUploadList=" { showRemoveIcon: true, showDownloadIcon: true }"
              @change="(data) => onFileChange(data, 'monitorDocument')"
              @download="onFileDownload"
            >
              <a-button icon="upload" type="dashed">上传监理文件</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>

        <a-col :span="24">
          <a-form-model-item
            class="ant-row-flex"
            label="鉴定报告"
            prop="houseInfo.identificationReport"
          >
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.identificationReport"
              :showUploadList=" { showRemoveIcon: true, showDownloadIcon: true }"
              @change="(data) => onFileChange(data, 'identificationReport')"
              @download="onFileDownload"
            >
              <a-button icon="upload" type="dashed">上传鉴定报告</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>

        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="其他附件" prop="houseInfo.otherDocument">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.otherDocument"
              :showUploadList=" { showRemoveIcon: true, showDownloadIcon: true }"
              @change="(data) => onFileChange(data, 'otherDocument')"
              @download="onFileDownload"
            >
              <a-button icon="upload" type="dashed">上传其他附件</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-spin>
  </a-form-model>
</template>
<script>
import { GetFileName, PreviewFile, BlobToBase64 } from '@/util/file';
/* 表单内容默认值 */
const defaultForm = {
  /* ... */
  houseInfo: {
    anEntryDocument: [],
    planningPermission: [],
    completionRecord: [],
    monitorDocument: [],
    identificationReport: [],
    otherDocument: [],
  },
};

export default {
  props: ['param'],

  data() {
    return {
      labelCol: { flex: '150px' },
      wrapperCol: { flex: '1' },

      /** 表单数据 */
      form: {
        ...defaultForm,
      },
      /** 验证格式 */
      rules: {
        /* ... */
      },

      /** 加载异步数据状态 */
      loading: false,

      /** 其他成员属性 */
      /* ... */
    };
  },

  async created() {
    this.onFillData();
  },

  methods: {
    /**
     * 必要的方法
     * 在打开编辑页时允许填充数据
     */
    async onFillData() {
      this.loading = true;
      {
        // await this.onLoadCodes();
        /** 将默认数据覆盖到form */
        const record = this.param && this.param.record;
        const form = this.$_.cloneDeep(defaultForm);

        if (record) {
          this.$_.giveDeep(form, record);

          for (var key in form.houseInfo) {
            const fileValue = [];
            const fileList =
              !form.houseInfo[key] || form.houseInfo[key].length == 0 ? [] : form.houseInfo[key].split(',');
            for (let i = 0; i < fileList.length; i++) {
              try {
                const file = await PreviewFile(fileList[i]);
                const base64 = await BlobToBase64(file);
                fileValue.push({
                  uid: fileList[i],
                  response: fileList[i], // 用于和新上传的文件一同回传
                  name: file.name,
                  url: base64,
                  status: 'done',
                });
              } catch {
                const { data: file } = await this.$api.sysFileInfoDetail({ id: fileList[i] });
                fileValue.push({
                  uid: fileList[i],
                  response: '文件已丢失',
                  name: file.fileOriginName,
                  status: 'error',
                });
              }
            }
            form.houseInfo[key] = fileValue;
          }
        }
        this.form = form;
      }
      this.loading = false;
    },
    /**
     * 必要方法
     * 验证表单并获取表单数据
     */
    onGetData() {
      return new Promise((reslove, reject) => {
        this.$refs.form.validate((valid, err) => {
          if (valid) {
            const record = this.$_.cloneDeep(this.form);

            /** 验证通过后可以对数据进行转换得到想要提交的格式 */
            for (var key in defaultForm.houseInfo) {
              record.houseInfo[key] = record.houseInfo[key].map((p) => p.response).join(',');
            }
            /* ... */

            reslove(record);
          } else {
            reject(err);
          }
        });
      });
    },

    /**
     * 必要的方法
     * 在外部窗口关闭或重置时对表单验证进行初始化
     */
    onResetFields() {
      setTimeout(() => {
        this.$refs.form.resetFields();

        /** 在这里可以初始化当前组件中其他属性 */
        /* ... */
      }, 300);
    },

    /** 当前组件的其他方法 */
    /* ... */

    /* 上传下载文件相关 Begin */
    async onFileUpload({ file, onProgress, onSuccess, onError }) {
      onProgress();
      const fd = new FormData();
      fd.append('file', file);
      try {
        const { data: fileId } = await this.$api.sysFileInfoUpload(fd);
        onSuccess(fileId);
      } catch {
        onError();
      }
    },
    onFileChange({ fileList }, key) {
      this.form.houseInfo[key] = fileList;
    },
    onFileDownload(file) {
      this.$api.sysFileInfoDownload({ id: file.response }).then((res) => {
        const url = window.URL.createObjectURL(res.data);
        const fileName = GetFileName(res.headers['content-disposition']);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
      });
    },
    /* 上传图片相关 End */
  },
};
</script>