<template>
  <div class="person-info">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <cy-info-title>{{ personType === 'legal' ? '法人信息' : '实际控制人信息' }}</cy-info-title>
      <el-form-item label="身份证正面" class="form-required">
        <cy-upload
          ref="idcardStorage_front"
          :upload-params="getFrontUplpadParams"
          :disabled="disabled"
          :is-call-back="true"
          :upload-from-orange-status="true"
          :limit="1"
          :file-type="'jpeg,png,jpg'"
          :file-data="ruleForm.frontFile || []"
          placeholder="请上传身份证正面"
          @call-back="frontCardCallBack"
        />
      </el-form-item>
      <el-form-item label="身份证反面" class="form-required">
        <cy-upload
          ref="idcardStorage_back"
          :upload-params="getBackUplpadParams"
          :disabled="disabled"
          :is-call-back="true"
          :limit="1"
          :file-type="'jpeg,png,jpg'"
          :upload-from-orange-status="true"
          :file-data="ruleForm.backFile || []"
          placeholder="请上传身份证反面"
          @call-back="backCardCallBack"
        />
      </el-form-item>
      <el-form-item :label="personType === 'legal' ? '法人姓名': ' 实控人姓名'" prop="legalName">
        <el-input v-model="ruleForm.legalName" disabled placeholder="请输入姓名" readonly></el-input>
      </el-form-item>
      <el-form-item label="出生日期" prop="bornDate">
        <el-date-picker
          v-model="ruleForm.bornDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出生日期"
          disabled
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="ruleForm.phoneNumber"
          :disabled="disabled || verifyStatus"
          placeholder="请输入手机号码"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="$route.query.type !== 'see'" label="验证码" class="form-required">
        <el-input
          v-model="ruleForm.code"
          placeholder="请输入验证码"
          type="text"
          tabindex="1"
          auto-complete="on"
        >
          <template #append>
            <div style="display: flex;">
              <verification-code
                :code="ruleForm.phoneNumber"
                module="other"
                type="phone"
                placeholder="手机号码"
                @startCall="verifyCodeStartCall"
                @endCall="verifyCodeEndCall"
              />
              <el-button v-if="showVerifyBtn" @click="handleVerifyPhone">验证</el-button>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="联系地址" prop="contactAddress">
        <el-input
          v-model="ruleForm.contactAddress"
          placeholder="请输入联系地址"
          disabled
        ></el-input>
      </el-form-item>

      <el-form-item label="现住地址" class="two-form-item" prop="cascaderAddress">
        <div class="address">
          <div v-if="!disabled">
            <el-cascader
              v-model="ruleForm.cascaderAddress"
              style="width: 100%;"
              placeholder="请选择省市区"
              :options="regionList"
              :key="personType"
              :props="{ value: 'id', label: 'name' }"
              @change="getBusinessAddress"
            />
          </div>
          <div>
            <el-input
              v-model="ruleForm.inputAddress"
              style="width: 100%;"
              :disabled="disabled"
              placeholder="请输入详细地址（具体到楼栋号）"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="征信" class="form-required" style="width: 100%;">
        <cy-upload
          ref="creditFileRef"
          :upload-params="getCreditUploadParams"
          :disabled="disabled"
          :file-type="'pdf'"
          :file-data="ruleForm.creditFile || []"
          :upload-from-orange-status="true"
          placeholder="请上传征信文件"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { cloneDeep } from '@/utils'
import { verifyCode, idCardOCR } from '@/api/common'

export default {
  components: {
    verificationCode: () => import('@/components/VerificationCode/index.vue')
  },
  props: {
    personType: {
      type: String,
      default: 'legal'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    detailsInfo: {
      type: Object,
      default: () => {}
    },
    regionList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      ruleForm: {
        frontFile: [],
        backFile: [],
        legalName: '',
        bornDate: '',
        phoneNumber: '',
        personCard: '',
        email: '',
        code: '',
        cascaderAddress: [],
        contactAddress: '',
        creditFile: []
      },
      selectLabels: [],
      rules: {
        legalName: [{ required: true, message: '请输入法人姓名', trigger: 'blur' }],
        bornDate: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        contactAddress: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
        cascaderAddress: [{ required: true, message: '请选择现居地址', trigger: 'blur' }],
        cascaderControlAddress: [{ required: true, message: '请选择现居地址', trigger: 'blur' }]
      },
      showVerifyBtn: false,
      verifyStatus: false
    }
  },
  computed: {
    getFrontUplpadParams() {
      if (this.personType === 'legal') {
        return { fileType: 'companyZrFrFrontCard' }
      }
      return { fileType: 'companyZrRcFrontCard' }
    },
    getBackUplpadParams() {
      if (this.personType === 'legal') {
        return { fileType: 'companyZrFrBackCard' }
      }
      return { fileType: 'companyZrRcBackCard' }
    },
    getCreditUploadParams() {
      if (this.personType === 'legal') {
        return { fileType: 'companyZrFrCredit' }
      }
      return { fileType: 'companyZrRcCredit' }
    }
  },
  watch: {
    detailsInfo: {
      handler(val) {
        if (val && Object.keys(val).length) {
          const newVal = cloneDeep(val)
          const {
            legalPerson,
            legalPersonAddress,
            legalPersonBirthday,
            legalPersonCard,
            legalPersonProvince,
            legalPersonCity,
            legalPersonCounty,
            legalPersonEmail,
            legalPersonLiveAddress,
            legalPersonPhone,
            frCardBack,
            frCardFront,
            frCredit,
            realControlPerson,
            realControlPersonAddress,
            realControlPersonBirthday,
            realControlPersonCard,
            realControlPersonProvince,
            realControlPersonCity,
            realControlPersonCounty,
            realControlPersonEmail,
            realControlPersonLiveAddress,
            realControlPersonPhone,
            rcCardBack,
            rcCardFront,
            rcCredit
          } = newVal

          if (this.personType === 'legal') {
            this.ruleForm = {
              legalName: legalPerson,
              bornDate: legalPersonBirthday,
              phoneNumber: legalPersonPhone,
              personCard: legalPersonCard,
              email: legalPersonEmail,
              cascaderAddress: [legalPersonProvince, legalPersonCity, legalPersonCounty],
              contactAddress: legalPersonAddress,
              inputAddress: legalPersonLiveAddress,
              frontFile: frCardFront,
              backFile: frCardBack,
              creditFile: frCredit
            }
          } else {
            this.ruleForm = {
              legalName: realControlPerson,
              bornDate: realControlPersonBirthday,
              phoneNumber: realControlPersonPhone,
              personCard: realControlPersonCard,
              email: realControlPersonEmail,
              cascaderAddress: [realControlPersonProvince, realControlPersonCity, realControlPersonCounty],
              contactAddress: realControlPersonAddress,
              inputAddress: realControlPersonLiveAddress,
              frontFile: rcCardFront,
              backFile: rcCardBack,
              creditFile: rcCredit
            }
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    getParams(type) {
      const reqParams = cloneDeep(this.ruleForm)
      return new Promise((resolve) => {
        const fileFrontList = this.$refs['idcardStorage_front'].getFileLists
        const fileBackList = this.$refs['idcardStorage_back'].getFileLists
        const creditList = this.$refs.creditFileRef.getFileLists
        if (fileFrontList && fileFrontList.length) {
          reqParams.cardFrontId = fileFrontList[0].id
        }
        if (fileBackList && fileBackList.length) {
          reqParams.cardBackId = fileBackList[0].id
        }
        if (creditList && creditList.length) {
          reqParams.creditId = creditList[0].id
        }
        if (type === 'temp') {
          resolve(reqParams)
        } else {
          if (fileFrontList && fileFrontList.length === 0) {
            this.$message.warning('请上传身份证正面')
            return
          }

          if (fileBackList && fileBackList.length === 0) {
            this.$message.warning('请上传身份证反面')
            return
          }

          if (creditList && creditList.length === 0) {
            this.$message.warning('请上传征信文件')
            return
          }

          if (!this.ruleForm.code) {
            this.$message.warning('请输入验证码')
            return
          }

          this.$refs.ruleFormRef.validate((valid) => {
            if (valid) {
              resolve(reqParams)
            }
          })
        }
      })
    },
    getBusinessAddress(value) {
      // const address = this.ruleForm.cascaderAddress.length ? this.ruleForm.cascaderAddress.join('') : '' // 此方式是当级联value为name时候直接回显
      const findLabels = (options, ids) => {
        const labels = []
        let currentOptions = options
        for (const id of ids) {
          const node = currentOptions.find((item) => item.id === id)
          if (node) {
            labels.push(node.name)
            currentOptions = node.children || []
          } else {
            break
          }
        }
        return labels
      }
      const labelArr = findLabels(this.regionList, value)
      const address = labelArr.length ? labelArr.join('') : ''
      // let tempAdress = ''
      // if (this.ruleForm.inputAddress) {
      //   tempAdress = this.ruleForm.inputAddress
      // } else {
      //   tempAdress = address
      // }
      this.$set(this.ruleForm, 'inputAddress', address)
    },
    validatePhoneNumber(val) {
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(val)) {
        this.$message.warning('请输入合法的手机号码')
        return false
      }
      return true
    },
    // 身份证正面上传成功回调
    async frontCardCallBack() {
      const fileFrontList = this.$refs['idcardStorage_front'].getFileLists

      const fileBackList = this.$refs['idcardStorage_back'].getFileLists

      if (fileFrontList.length && fileBackList.length) {
        this.ocrIdCard(fileFrontList[0].id, fileBackList[0].id)
      }
    },
    // 身份证反面上传成功的回调
    backCardCallBack() {
      const fileFrontList = this.$refs['idcardStorage_front'].getFileLists

      const fileBackList = this.$refs['idcardStorage_back'].getFileLists

      if (fileFrontList.length && fileBackList.length) {
        this.ocrIdCard(fileFrontList[0].id, fileBackList[0].id)
      }
    },
    // OCR身份证
    async ocrIdCard(frontId, backId) {
      if (frontId !== '' && backId !== '') {
        const res = await idCardOCR({
          front: frontId,
          back: backId
        })

        console.log('idCardOCR------', res)

        if (res.success) {
          this.ruleForm.legalName = res.data.name
          this.ruleForm.bornDate = res.data.birth
          this.ruleForm.contactAddress = res.data.address
          this.ruleForm.personCard = res.data.idcard
        }
      }
    },
    async handleVerifyPhone() {
      const params = {
        phoneNumber: this.ruleForm.phoneNumber,
        code: this.ruleForm.code
      }

      try {
        const res = await verifyCode(params)

        if (res.success) {
          this.verifyStatus = true
        }
      } catch (error) {
        console.log('error----', error)
        this.verifyStatus = false
      }
    },
    verifyCodeStartCall(status) {
      this.showVerifyBtn = status
    },
    verifyCodeEndCall(status) {
      this.showVerifyBtn = status
    }
  }
}
</script>

<style lang="scss" scoped>
.address {
  display: flex;
  width: 100%;
  div {
    width: calc(50% - 10px);
  }
  div:nth-child(2) {
    margin-left: 18px;
  }
}
</style>
