<template>
  <a-modal title='证件资料' :visible='visible' :width='860' @cancel='cancel' @ok='onSubmit'>
    <p-form-model ref='formTarget' :label-col='{ span: 8 }' :model='form' :rules="{
                        certificateNumber:[{required: true, message: '请输入证件号码', trigger: 'change'}],
                        certificateName:[{required: true, message: '请选择证件名称', trigger: 'change'}],
                    }" :wrapper-col='{ span: 16 }' class='plg-grid-from'>
      <a-row>
        <a-col :span='8'>
          <p-form-model-item label='证件号码' prop='certificateNumber'>
            <p-input v-model='form.certificateNumber' :disabled='type==="view"' placeholder='请输入证件号码' />
          </p-form-model-item>
        </a-col>
        <a-col :span='8'>
          <p-form-model-item label='证件名称' prop='certificateName'>
            <p-search-modal ref='certificateRef' :disabled='type==="view"' v-model='form.certificateName' v-bind='$data.$formItems.certificateAttr' @change="(event, value) => onFormChange('certificate',event, value)" />
          </p-form-model-item>
        </a-col>
        <a-col :span='8'>
          <p-form-model-item label='证件编码'>
            <p-input v-model='form.certificateCode' disabled />
          </p-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='8'>
          <p-form-model-item label='证件起始日期' prop='startDate'>
            <p-date-picker v-model='form.startDate' :showToday='false' :disabled='type==="view"' :disabled-date='disabledStartDate' placeholder='请选择证件起始日期' style='width: 100%;' valueFormat='YYYY-MM-DD' />
          </p-form-model-item>
        </a-col>
        <a-col :span='8'>
          <p-form-model-item label='证件截止日期' prop='expireDate'>
            <p-date-picker v-model='form.expireDate' :showToday='false' :disabled='type==="view"' :disabled-date='disabledEndDate' placeholder='请选择证件截止日期' style='width: 100%;' valueFormat='YYYY-MM-DD' />
          </p-form-model-item>
        </a-col>
      </a-row>
    </p-form-model>
    <certificateUpload ref='fileRef' :rootType='rootType' :type='type' :editData='editData' />
  </a-modal>
</template>

<script>
import certificateUpload from './components/certificateUpload'
import * as $formItems from './js/form'
import { add, update } from './api'

export default {
  components: { certificateUpload },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    rootType: '',
    consignorid: '',
    parentid: '',
    mode: '', // 证件类型 1：货主2：供应商3：客户4：供应商5：物流商6：商品7：设备 8受托人

    type: '', // 控制组件状态
    editData: { // 组件回显数据
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      $formItems,
      form: {}
    }
  },
  mounted() {
    if (this.type !== 'add') {
      this.form = { ...this.editData }
    }
  },
  methods: {
    cancel() {
      this.$emit('update:visible', false)
    },
    ok() {
      this.$emit('ok', {})
    },
    onSubmit() {
      this.$refs.formTarget.validate(flag => {
        if (!flag) return
        if (this.type === 'add') return this.onAdd()
        if (this.type === 'edit') return this.onUpdate()
      })
    },
    async onAdd() {
      let closeLoading
      try {
        this.spinning = true
        closeLoading = this.$message.loading('正在保存证件数据...', 0)
        // 新增报错需要单独捕获,以免被try处理
        const { parentcode, parentid, parentname, consignorcode, consignorid, consignorname } = this.editData
        const type = this.mode
        const certificateRes = await add({ ...this.form, type, parentcode, parentid, parentname, consignorcode, consignorid, consignorname }).catch(err => (console.error('新增证件失败:', err), true))
        closeLoading()
        if (certificateRes.success) {
          closeLoading = this.$message.loading('正在上传文件...', 0)
          await this.$refs.fileRef.uploadAllFile(certificateRes.data)
          closeLoading()
        } else {
          this.$message.error(certificateRes.message)
        }
        this.spinning = false
        if (certificateRes.success) {
          this.$message.success(certificateRes.message)
          this.ok()
          this.cancel()
        }
      } catch (e) {
        this.spinning = false
        closeLoading?.()
        this.$message.error(e)
      }
    },
    onUpdate() {
      this.spinning = true
      update(this.form).then(res => {
        if (res.success) {
          this.$message.success(res.messagesage)
          this.ok()
          this.cancel()
        } else {
          this.$message.warn(res.message)
        }
      }).finally(() => {
        this.spinning = false
      })
    },
    onFormChange(name, { selectData }, value) {
      if (!selectData) return
      selectData = Array.isArray(selectData) ? selectData[0] : selectData
      if (name === 'certificate') {
        if (!value) {
          Object.assign(this.form, { certificateName: '', certificateCode: '', certificateId: '' })
          return
        }
        const { certificateName, certificateCode, id } = selectData
        this.$set(this.form, 'certificateName', certificateName)
        this.$set(this.form, 'certificateCode', certificateCode)
        this.$set(this.form, 'certificateId', id)
        return
      }
    },
    // 日期选择限制
    disabledStartDate(startValue) {
      if (!startValue || !this.form.expireDate) return false
      const endValue = this.$moment(this.form.expireDate)
      return startValue.valueOf() > endValue.valueOf()
    },
    disabledEndDate(endValue) {
      const current = this.$moment()
      if (!endValue || !this.form.startDate) {
        return current.valueOf() > endValue.valueOf()
      }
      const startValue = this.$moment(this.form.startDate)
      return startValue.valueOf() > endValue.valueOf() || current.valueOf() > endValue.valueOf()
    }
  }
}
</script>

<style scoped>

</style>
