<template>
  <el-form ref="form" :rules="rules" :model="form" label-width="80px" label-position="top" size="small">
    <el-row :gutter="40">
      <el-col :span="12">
        <el-form-item label="企业证件类型" prop="companyCertType">
          <el-select v-model="form.companyCertType" placeholder="请选择证件类型" clearable>
            <el-option v-for="item of dict.companyCertType" :key="item.key" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="40">
      <el-col :span="12">
        <el-form-item label="企业证件照片" prop="licenseImages">
          <div class="device-wrap">
            <uploader
              ref="fileUpload"
              v-model="form.licenseImages"
              :data="upload.data"
              :action="upload.action"
              :before-upload="onUploadBefore"
              :limit="5"
              :security="true"
              placeholder="上传照片"
              list-type="picture-card"
              accept="image/png, image/jpeg, image/jpg, application/pdf"
              @on-error="onUploadError"
              @on-success="onUploadSuccess"
              @on-remove="onUploadRemove"
            />
            <i v-if="device.showTakePhoto" class="icon-device-video" @click="showDialog = true" />
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="40">
      <el-col :span="12">
        <el-form-item label="企业证件号码" prop="companyCertNumber">
          <el-input v-model="form.companyCertNumber" placeholder="请输入企业证件号码" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="企业证件地址" prop="companyCertAddress">
          <el-input v-model="form.companyCertAddress" placeholder="请输入企业证件地址" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="企业通讯地址" prop="companyContactAddress">
          <el-input v-model="form.companyContactAddress" placeholder="请输入企业通讯地址" clearable />
        </el-form-item>
      </el-col>
    </el-row>
    <device-dialog :show.sync="showDialog" :security="true" :data="form.licenseImages" :limit="5" @getPhoto="getPhoto" />
  </el-form>
</template>
<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { cuscImageUpload } from '@/api/realname-enterprise'
import Uploader from '@/components/Uploader'
import deviceDialog from '@/components/Device/dialog'
export default {
  name: 'CertForm',
  components: {
    Uploader,
    deviceDialog
  },
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    const checkLicenseImages = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请上传企业证件照片'))
      } else {
        callback()
      }
    }
    return {
      showDialog: false,
      upload: {
        data: {
          rootPath: '',
          path: ''
        },
        headers: {
          'Authorization': `bearer ${getToken()}`
        },
        action: cuscImageUpload
      },
      form: {
        companyCertType: '0',
        licenseImages: [],
        companyCertNumber: '',
        companyCertAddress: '',
        companyContactAddress: ''
      },
      rules: {
        licenseImages: [
          { required: true, validator: checkLicenseImages, trigger: 'blur, change' }
        ],
        companyCertNumber: [
          { required: true, message: '请输入企业证件号码', trigger: 'blur' }
        ],
        companyCertAddress: [
          { required: true, message: '请输入企业证件地址', trigger: 'blur' }
        ],
        companyContactAddress: [
          { required: true, message: '请输入企业通讯地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['dict', 'device'])
  },
  watch: {
    data() {
      this.updateInternalData()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.updateInternalData()
    },

    updateInternalData() {
      if (typeof this.data === 'object' && this.data !== null) {
        this.form = {
          companyCertType: this.data.companyCertType || '0',
          licenseImages: this.data.licenseImages || [],
          companyCertNumber: this.data.companyCertNumber || '',
          companyCertAddress: this.data.companyCertAddress || '',
          companyContactAddress: this.data.companyContactAddress || ''
        }
      } else {
        this.form = {
          companyCertType: '0',
          licenseImages: [],
          companyCertNumber: '',
          companyCertAddress: '',
          companyContactAddress: ''
        }
      }
    },

    /**
    * 获取图片
    * @time 2022-05-11 23:32:36
    */
    getPhoto(data) {
      this.form.licenseImages = data
    },

    /**
    * 获取当前模块数据
    * @time 2022-04-23 15:50:05
    */
    async validate(isErrorAnchor = false) {
      try {
        await this.$refs.form.validate()
        return true
      } catch (e) {
        if (isErrorAnchor) {
          this.$refs.form.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
        }
        let temp = {
          anchor: () => {
            this.$refs.form.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
            temp = null
          }
        }
        throw temp
      }
    },

    /**
    * 获取表单数据
    * @time 2022-04-23 18:02:02
    */
    getFormData() {
      return this.form
    },

    /**
    * 获取待缓存数据
    * @time 2022-04-24 19:43:57
    */
    getPendingCacheData() {
      return this.getFormData()
    },

    /**
    * 凭证上传校验
    * @time 2022-04-11 09:16:44
    */
    onUploadBefore(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isPDF = file.type === 'application/pdf'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG && !isPNG && !isPDF) {
        this.$message.error('证件照片格式不对!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('证件照片大小不能超过5MB!')
        return false
      }
    },

    /**
    * 凭证上传成功
    * @time 2022-04-09 17:22:21
    */
    onUploadSuccess() {
      this.$nextTick(() => {
        this.$refs.form.validateField('licenseImages')
      })
    },

    /**
    * 凭证上传失败
    * @time 2022-04-09 17:22:21
    */
    onUploadError() {
      this.$message.error('文件上传失败')
      this.$refs.fileUpload.$refs.fileUpload.clearFiles()
      this.onUploadRemove()
    },

    /**
    * 移除上传凭证
    * @time 2022-04-09 17:22:21
    */
    onUploadRemove() {
      this.$nextTick(() => {
        this.$refs.form.validateField('licenseImages')
      })
    }
  }
}
</script>
