<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="12">
          <a-form-model-item class="ant-row-flex" label="面砖总面积" prop="areaCount">
            <a-row type="flex">
              <a-col flex="1">
                <a-input-number
                  :min="0"
                  class="w-100-p"
                  placeholder="请输入面砖总面积"
                  v-model="form.areaCount"
                />
              </a-col>
              <a-col>
                <span class="yo-addon">m²</span>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="粘贴基层做法" prop="treatmentProposal">
            <a-checkbox-group v-model="form.treatmentProposal">
              <a-checkbox
                :key="item.code"
                :value="item.code"
                v-for="item in codes.stickup"
              >{{ item.value }}</a-checkbox>
            </a-checkbox-group>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="外立面照片" prop="facadePhoto">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.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 = {
  /* ... */
  facadePhoto: [],
};

export default {
  components: {
    PhotoSwipe,
  },

  props: ['param'],

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

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

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

      /** 其他成员属性 */
      /* ... */
      codes: {
        stickup: [],
      },
    };
  },

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

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

      // 从数据中的文件id转换成uploader所需的格式
      if (record) {
        const fileList = record.facadePhoto.split(',');
        for (let i = 0; i < fileList.length; i++) {
          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',
          });
        }
      }

      this.form = this.$_.cloneDeep({
        ...defaultForm,
        ...record,
        /** 在此处添加其他默认数据转换 */
        /* ... */
        facadePhoto,
      });
    },

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

            /** 验证通过后可以对数据进行转换得到想要提交的格式 */
            /* ... */

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

    /**
     * 必要的方法
     * 在外部窗口进行保存时调用表单验证
     */
    onValidate(callback) {
      this.$refs.form.validate(callback);
    },

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

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

    /**
     * 必要方法
     * 加载当前表单中所需要的异步数据
     */
    async onInit() {
      this.loading = true;
      /** 可以在这里await获取一些异步数据 */
      /* ... */
      await this.onLoadCodes();
      this.loading = false;
    },

    /** 当前组件的其他方法 */
    /* ... */
    onLoadCodes() {
      return this.$api
        .sysDictTypeDropDowns({
          code: ['dic_house_facebrick_stickup'],
        })
        .then(({ data: { dic_house_facebrick_stickup } }) => {
          this.codes = {
            stickup: dic_house_facebrick_stickup,
          };
        });
    },

    /* 上传图片相关 Begin */
    onFileChange({ fileList }) {
      this.form.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.facadePhoto.length; i++) {
        const _file = this.form.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.facadePhoto.indexOf(file),
      });
    },
    /* 上传图片相关 End */
  },
};
</script>