<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="patrolInfo.settlementTilt">
            <a-textarea
              :auto-size="{ minRows: 3 }"
              placeholder="请输入沉降倾斜情况"
              v-model="form.patrolInfo.settlementTilt"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item
            class="ant-row-flex"
            label="沉降倾斜情况照片"
            prop="patrolInfo.settlementTiltFiles"
          >
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.patrolInfo.settlementTiltFiles"
              :preview-file="onPreviewFile"
              @change="(data) => onFileChange(data, 'settlementTiltFiles')"
              @preview="(data) => onFilePreview(data, 'settlementTiltFiles')"
              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-col :span="24">
          <a-form-model-item class="ant-row-flex" label="其他情况" prop="patrolInfo.otherInfo">
            <a-textarea
              :auto-size="{ minRows: 3 }"
              placeholder="请输入其他情况"
              v-model="form.patrolInfo.otherInfo"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item class="ant-row-flex" label="其他情况照片" prop="patrolInfo.otherInfoFiles">
            <a-upload
              :custom-request="onFileUpload"
              :file-list="form.patrolInfo.otherInfoFiles"
              :preview-file="onPreviewFile"
              @change="(data) => onFileChange(data, 'otherInfoFiles')"
              @preview="(data) => onFilePreview(data, 'otherInfoFiles')"
              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-col :span="24">
          <a-form-model-item class="ant-row-flex" label="主要安全隐患综述" prop="patrolInfo.mainSafety">
            <a-textarea
              :auto-size="{ minRows: 3 }"
              placeholder="请输入主要安全隐患综述"
              v-model="form.patrolInfo.mainSafety"
            />
          </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 = {
  patrolInfo: {
    settlementTilt: null,
    settlementTiltFiles: [],
    otherInfo: null,
    otherInfoFiles: [],
    mainSafety: null,
  },
};
export default {
  components: {
    PhotoSwipe,
  },
  props: ['param'],
  data() {
    return {
      labelCol: { flex: '150px' },
      wrapperCol: { flex: '1' },
      form: {
        ...defaultForm,
      },
      rules: {},
      /** 加载异步数据状态 */
      loading: false,

      /** 其他成员属性 */
      codes: {},
      fileFieldArr: ['settlementTiltFiles', 'otherInfoFiles'],
    };
  },

  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.patrolInfo) {
            if (key.indexOf('Files') > -1) {
              const fileValue = [];
              const fileList =
                !form.patrolInfo[key] || form.patrolInfo[key].length == 0 ? [] : form.patrolInfo[key].split(',');
              for (let i = 0; i < fileList.length; i++) {
                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',
                });
              }
              form.patrolInfo[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);

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

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

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

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

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

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