<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.facadePhoto">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.houseInfo.facadePhoto"
              :preview-file="onPreviewFile"
              @change="onFileChange"
              @preview="onFilePreview"
              list-type="picture-card"
            >
              <div>
                <a-icon type="plus" />
                <div class="ant-upload-text">外立面照片</div>
              </div>
            </a-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-spin>
    <PhotoSwipe ref="photo-swipe" />
  </a-form-model>
</template>
<script>
import { PreviewFile, BlobToBase64 } from '@/util/file';

import PhotoSwipe from '@/components/photoSwipe';

/* 表单内容默认值 */
const defaultForm = {
  /* ... */
  houseInfo: {
    facadePhoto: [],
  },
};

export default {
  components: {
    PhotoSwipe,
  },

  props: ['param'],

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

      /** 表单数据 */
      form: {
        ...defaultForm,
      },
      /** 验证格式 */
      rules: {
        /* ... */
        // 'houseInfo.facadePhoto': [{ required: true, message: '请上传外立面照片' }],
      },

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

      /** 其他成员属性 */
      /* ... */
      previewVisible: false,
      previewImage: '',
    };
  },

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

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

        // 从数据中的文件id转换成uploader所需的格式
        if (record) {
          const fileList = !!record.houseInfo.facadePhoto ? record.houseInfo.facadePhoto.split(',') : [];
          for (let i = 0; i < fileList.length; i++) {
            try {
              const file = await PreviewFile(fileList[i]);
              const base64 = await BlobToBase64(file);
              facadePhoto.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] });
              facadePhoto.push({
                uid: fileList[i],
                response: '文件已丢失',
                name: file.fileOriginName,
                status: 'error',
              });
            }
          }
        }
        defaultForm.houseInfo.facadePhoto = facadePhoto;
        this.form = this.$_.cloneDeep({
          ...defaultForm,
        });
      }
      this.loading = false;
    },

    /**
     * 必要方法
     * 验证表单并获取表单数据
     */
    onGetData() {
      return new Promise((reslove, reject) => {
        this.$refs.form.validate((valid, err) => {
          if (valid) {
            const record = this.$_.cloneDeep(this.form);

            /** 验证通过后可以对数据进行转换得到想要提交的格式 */
            /* ... */
            record.houseInfo.facadePhoto = record.houseInfo.facadePhoto.map((p) => p.response).join(',');

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

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

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

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

    /* 上传图片相关 Begin */
    onFileChange({ fileList }) {
      this.form.houseInfo.facadePhoto = fileList;
    },
    onPreviewFile(file) {
      return new Promise((resolve) => {
        const base64 = BlobToBase64(file);
        resolve(base64);
      });
    },
    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();
      }
    },
    onFilePreview(file) {
      const items = [];
      for (let i = 0; i < this.form.houseInfo.facadePhoto.length; i++) {
        const _file = this.form.houseInfo.facadePhoto[i];
        const img = new Image();
        const src = _file.url || _file.thumbUrl;
        img.src = src;
        items.push({
          src,
          w: img.naturalWidth,
          h: img.naturalHeight,
        });
      }
      this.$refs['photo-swipe'].initPhotoSwipe(items, {
        index: this.form.houseInfo.facadePhoto.indexOf(file),
      });
    },
    /* 上传图片相关 End */
  },
};
</script>