<template>
  <div class="legalperson-info">
    <el-form
      ref="ruleFormRef"
      :key="ruleFormKey"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      class="rule-form-orange"
    >
      <el-form-item :label="name" prop="name">
        <el-input
          v-model="ruleForm.name"
          :placeholder="`请输入${name}`"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item v-if="type === 'beneficiary' || type === 'commander'" label="国籍" prop="nationality">
        <el-select v-model="ruleForm.nationality" placeholder="请选择证国籍" disabled>
          <el-option
            v-for="item in constant.registerCountry"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证正面" class="form-required">
        <cy-upload
          ref="idCardFront"
          :upload-params="{
            fileType: frontFileType
          }"
          :file-data="idCardFrontList"
          :disabled="disabled"
          :upload-from-orange-status="true"
          :limit="1"
          :file-type="'jpeg,jpg,png,bmp,gif'"
          :is-call-back="true"
          placeholder="请上传身份证正面(格式:jpeg、jpg、png、bmp、gif)"
          @call-back="callBack"
        />
      </el-form-item>
      <el-form-item label="身份证反面" class="form-required">
        <cy-upload
          ref="idCardReverse"
          :upload-params="{
            fileType: reverseFileType
          }"
          :file-data="idCardReverseList"
          :disabled="disabled"
          :upload-from-orange-status="true"
          :limit="1"
          :file-type="'jpeg,jpg,png,bmp,gif'"
          placeholder="请上传身份证反面(格式:jpeg、jpg、png、bmp、gif)"
          :is-call-back="true"
          @call-back="callBack"
        />
      </el-form-item>
      <el-form-item label="证件种类" prop="idType">
        <el-select v-model="ruleForm.idType" placeholder="请选择证件种类" :disabled="disabled">
          <el-option
            v-for="item in constant.idCard"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="ruleForm.idNumber"
          placeholder="请输入证件号码"
          :disabled="disabled"
          @blur="getIdType"
        />
      </el-form-item>
      <el-form-item label="证件有效期" prop="periodValidityDate">
        <el-date-picker
          v-model="ruleForm.periodValidityDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 100%;"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item v-if="type === 'legalperson' || type === 'commander'" label="手机号" prop="phone">
        <el-input
          v-model="ruleForm.phone"
          placeholder="请输入手机号"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item v-if="type === 'beneficiary' || type === 'commander'" label="地址" prop="address">
        <el-input
          v-model="ruleForm.address"
          placeholder="请输入地址"
          :disabled="disabled"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import qichachaInfo from '../../mixins/qichachaInfo'
import { validPhone } from '@/utils/validate'
export default {
  mixins: [qichachaInfo],
  props: {
    type: {
      type: String,
      default: '' // legalperson 法人信息 shareholder 控股股东信息  actualCController  实控人信息 beneficiary 受益人信息 commander 负责人
    },
    disabled: {
      type: Boolean,
      default: false
    },
    //
    name: {
      type: String,
      default: ''
    },
    // 身份证正面文件类型
    frontFileType: {
      type: String,
      default: ''
    },
    // 身份证反面文件类型
    reverseFileType: {
      type: String,
      default: ''
    },
    qichachaOptions: {
      type: Object,
      default: () => {}
    },
    detailsInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'))
      }
      if (!validPhone(value)) {
        return callback(new Error('请输入有效的手机号'))
      }
      callback()
    }
    return {
      ruleFormKey: 1,
      idCardFrontList: [],
      idCardReverseList: [],
      ruleForm: {
        name: '',
        nationality: 'registerCountry_CHN',
        idType: '',
        idNumber: '',
        periodValidityStart: '',
        periodValidityEnd: '',
        periodValidityDate: [],
        phone: '',
        address: ''
      },
      rules: {
        name: [
          { required: true, message: `请输入${this.name}`, trigger: 'blur' }
        ],
        periodValidityDate: [
          { required: true, message: `请选择证件有效期`, trigger: 'change' }
        ],
        idType: [
          { required: true, message: `请选择证件种类`, trigger: 'change' }
        ],
        idNumber: [
          { required: true, message: `请输入证件号码`, trigger: 'blur' }
        ],
        address: [
          { required: true, message: `请输入地址`, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: `请输入手机号`, trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['constant'])
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV && Object.keys(newV).length) {
          const deepData = JSON.parse(JSON.stringify(newV))
          for (const key in this.qichachaOptions) {
            this.ruleForm[key] = deepData[this.qichachaOptions[key]]
          }
          this.idCardFrontList = deepData.frontFile ? [deepData.frontFile] : []
          this.idCardReverseList = deepData.backFile ? [deepData.backFile] : []
          this.ruleForm.periodValidityDate = this.ruleForm.periodValidityStart ? [this.ruleForm.periodValidityStart, this.ruleForm.periodValidityEnd] : []
          this.ruleFormKey += 1
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['idCard', 'registerCountry'])
  },
  methods: {
    submitParams(type) {
      let front = null
      let back = null
      const idCardFront = this.$refs.idCardFront.getFileLists
      if (type === 'submit' && !idCardFront.length) {
        this.$message.error('请上传身份证正面照片')
        return false
      }
      const idCardReverse = this.$refs.idCardReverse.getFileLists
      if (type === 'submit' && !idCardReverse.length) {
        this.$message.error('请上传身份证反面照片')
        return false
      }
      front = idCardFront.length ? idCardFront[0].id : ''
      back = idCardReverse.length ? idCardReverse[0].id : ''
      const mapRuleForm = {}
      for (const key in this.qichachaOptions) {
        mapRuleForm[this.qichachaOptions[key]] = this.ruleForm[key] === undefined ? null : this.ruleForm[key]
        if (key === 'periodValidityDate' && this.ruleForm.periodValidityDate && this.ruleForm.periodValidityDate.length) {
          mapRuleForm.periodOfValidityFrom = this.ruleForm.periodValidityDate[0]
          mapRuleForm.periodOfValidity = this.ruleForm.periodValidityDate[1]
        }
      }
      const params = {
        ...mapRuleForm,
        front,
        back
      }
      delete params.periodValidityDate
      return params
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleFormRef.validate(valid => {
          if (valid) {
            resolve(this.submitParams('submit'))
          } else {
            return false
          }
        })
      })
    },

    // 获取数据
    getParams(type) {
      return new Promise((resolve, reject) => {
        if (type === 'temp') {
          resolve(this.submitParams(type))
        } else {
          this.validateForm().then((data) => {
            resolve(data)
          })
        }
      })
    },
    getFile() {
      const idCardFrontList = this.$refs.idCardFront.getFileLists
      const idCardReverseList = this.$refs.idCardReverse.getFileLists
      return { idCardFrontList, idCardReverseList }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
