<template>
  <div class="guarantee-add-info">

    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <cy-info-title type="center">征信信息</cy-info-title>
      <el-form-item style="width: 100%">
        <template slot="label">
          <span>个人征信</span>
          <span class="slot-name-desc">烦请本人线上查询个人征信，并填写我司邮箱作为央行等银行发送征信报告的指定邮箱operation@changan-inkasso.com</span>
        </template>
        <cy-comm-table
          ref="commTable"
          style="margin-top: 10px; width: 100%"
          :columns="columns"
          :data="tableData"
          :count="0"
        />
      </el-form-item>
      <el-form-item style="width: 100%">
        <template slot="label">
          <span>企业征信查询授权书</span>
          <span class="slot-name-desc">必须已认证已签署才可提交</span>
        </template>
        <cy-comm-table
          style="margin-top: 10px; width: 100%"
          :columns="enterpriseColumns"
          :data="enterpriseTableData"
          :count="0"
        />
      </el-form-item>
      <cy-info-title type="center">企业经营地址</cy-info-title>
      <el-form-item label="经营地址" style="width: 100%;" prop="businessAddress">
        <el-input v-model="ruleForm.businessAddress" placeholder="请输入经营地址" disabled />
      </el-form-item>
      <el-form-item label="地点定位图" class="one-form-item form-required" prop="locationMap">
        <cy-upload
          ref="locationMap"
          :upload-params="{
            fileType: 'enterprise_location_map'
          }"
          :file-data="locationMap"
          :upload-from-orange-status="true"
          placeholder="请上传地点定位图"
          disabled
        />
      </el-form-item>
      <el-form-item label="租房合同" class="one-form-item form-required" prop="rentalContract">
        <cy-upload
          ref="rentalContract"
          :upload-params="{
            fileType: 'enterprise_rental_contract'
          }"
          :file-data="rentalContract"
          :upload-from-orange-status="true"
          placeholder="请上传租房合同"
          disabled
        />
      </el-form-item>
      <el-form-item label="房租缴纳流水" class="one-form-item form-required" prop="waterElectricityFees">
        <cy-upload
          ref="waterElectricityFees"
          :upload-params="{
            fileType: 'enterprise_water_electricity_fees'
          }"
          :file-data="waterElectricityFees"
          :upload-from-orange-status="true"
          placeholder="请上传房租缴纳流水"
          disabled
        />
      </el-form-item>
      <el-form-item label="办公环境图" class="one-form-item form-required" prop="officeEnvironment">
        <cy-upload
          ref="officeEnvironment"
          :upload-params="{
            fileType: 'enterprise_office_environment'
          }"
          :file-data="officeEnvironment"
          :upload-from-orange-status="true"
          placeholder="请上传办公环境图"
          disabled
        />
      </el-form-item>
      <cy-info-title type="center">公司相关信息</cy-info-title>
      <el-form-item label="营业执照" class="one-form-item form-required" prop="businessLicense">
        <cy-upload
          ref="businessLicense"
          :upload-params="{
            fileType: 'enterprise_business_license'
          }"
          :file-data="businessLicense"
          :is-call-cack="true"
          :limit="1"
          :upload-from-orange-status="true"
          placeholder="请上传营业执照"
          disabled
          @call-back="businessLicenseCallBack"
        />
      </el-form-item>
      <el-form-item label="经营范围" prop="businessScope">
        <el-input
          v-model="ruleForm.businessScope"
          :disabled="disabled"
          placeholder="请输入经营范围"
        />
      </el-form-item>
      <el-form-item label="注册地址" prop="registeredAddress">
        <el-input
          v-model="ruleForm.registeredAddress"
          :disabled="disabled"
          placeholder="请输入注册地址"
        />
      </el-form-item>
      <el-form-item label="基本户信息" class="one-form-item form-required" prop="basicAccountInformation">
        <cy-upload
          ref="basicAccountInformation"
          :upload-params="{
            fileType: 'enterprise_basic_account_information'
          }"
          :file-data="basicAccountInformation"
          :upload-from-orange-status="true"
          placeholder="请上传基本户信息"
          disabled
        />
      </el-form-item>
      <el-form-item label="基本存款账号" prop="bankAccount">
        <el-input
          v-model="ruleForm.bankAccount"
          :disabled="disabled"
          placeholder="请输入基本存款账号"
        />
      </el-form-item>
      <el-form-item label="基本账户开户行名称" prop="bank">
        <el-input
          v-model="ruleForm.bank"
          :disabled="disabled"
          placeholder="请输入基本账户开户行名称"
        />
      </el-form-item>
      <el-form-item label="公司章程和修正案 " class="one-form-item form-required" prop="articlesAssociation">
        <cy-upload
          ref="articlesAssociation"
          :upload-params="{
            fileType: 'enterprise_articles_association'
          }"
          :file-data="articlesAssociation"
          :upload-from-orange-status="true"
          placeholder="请上传公司章程和修正案"
          disabled
        />
      </el-form-item>
      <el-form-item label="结案证明或判决书" class="one-form-item" prop="judgment">
        <cy-upload
          ref="judgment"
          :upload-params="{
            fileType: 'enterprise_judgment'
          }"
          :file-data="judgment"
          :upload-from-orange-status="true"
          placeholder="请上传结案证明或判决书"
          disabled
        />
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import { ocrIdentifyCard, ocrBusinessLicense } from '@/api/capitalFinancialManage'

export default {
  props: {
    addInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      ruleForm: {
        businessAddress: '',
        businessScope: '',
        registeredAddress: '',
        bankAccount: '',
        bank: ''
      },
      locationMap: [],
      rentalContract: [],
      waterElectricityFees: [],
      officeEnvironment: [],
      businessLicense: [],
      basicAccountInformation: [],
      articlesAssociation: [],
      judgment: [],
      rules: {
        businessAddress: [{ required: true, message: '请输入经营地址', trigger: 'blur' }],
        businessScope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
        registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
        bankAccount: [{ required: true, message: '请输入基本存款账号', trigger: 'blur' }],
        bank: [{ required: true, message: '请输入基本账户开户行名称', trigger: 'blur' }]
      },
      tableData: [],
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '身份类型',
          width: 100,
          prop: 'typeStr'
        },
        {
          label: '姓名',
          prop: 'name'
        },
        {
          label: '身份证正面',
          width: 180,
          ruleRequired: true,
          render: (h, row, index) => {
            return <cy-upload
              ref={`idcardStorage_front_${index}`}
              uploadParams={{ fileType: 'enterprise_idcard_front' }}
              disabled={this.disabled}
              isCallBack={true}
              limit={1}
              fileData={row.frontFile || []}
              oncall-back={ (fileList, fileName, row, index) => {
                this.frontCardCallBack(fileList, fileName, row, index)
              } }
              defaultDesc='请上传身份证正面'
            />
          }
        },
        {
          label: '身份证反面',
          width: 180,
          ruleRequired: true,
          render: (h, row, index) => {
            return <cy-upload
              ref={`idcardStorage_back_${index}`}
              uploadParams={{ fileType: 'enterprise_idcard_back' }}
              disabled={this.disabled}
              isCallBack={true}
              limit={1}
              fileData={row.backFile || []}
              oncall-back={ (fileList, fileName) => {
                this.backCardCallBack(fileList, fileName, row, index)
              } }
              defaultDesc='请上传身份证反面'
            />
          }
        },
        {
          label: '姓名',
          width: 100,
          prop: 'name',
          ruleRequired: true,
          render: (h, row) => {
            return row.typeStr === '实控人' ? <el-input v-model={row.name} disabled={this.disabled} placeholder='请输入姓名'></el-input> : <span>{row.name}</span>
          }
        },
        {
          label: '身份证号',
          prop: 'socialCreditCode',
          ruleRequired: true,
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.socialCreditCode} placeholder='请输入身份证号'></el-input>
          }
        },
        {
          label: '手机号码',
          render: (h, row) => {
            return <el-input
              disabled={this.disabled}
              v-model={row.phoneNumber}
              placeholder='请输入手机号码'
            ></el-input>
          }
        },
        {
          label: '户籍地址',
          ruleRequired: true,
          render: (h, row) => {
            return <el-input
              disabled={this.disabled}
              v-model={row.domicileAddress}
              placeholder='请输入户籍地址'
            ></el-input>
          }
        },
        {
          label: '常住地址',
          ruleRequired: true,
          render: (h, row) => {
            return <el-input
              disabled={this.disabled}
              v-model={row.permanentAddress}
              placeholder='请输入常住地址'
            ></el-input>
          }
        },
        {
          label: '证件有效开始日期',
          ruleRequired: true,
          render: (h, row) => {
            return <el-date-picker
              disabled={this.disabled}
              v-model={row.validFrom}
              type='date'
              value-format='yyyy-MM-dd'
              placeholder='请选择证件有效开始日期'>
            </el-date-picker>
          }
        },
        {
          label: '证件有效截止期',
          ruleRequired: true,
          render: (h, row) => {
            return <el-date-picker
              disabled={this.disabled}
              v-model={row.validTo}
              type='date'
              value-format='yyyy-MM-dd'
              placeholder='请选择证件有效截止期'>
            </el-date-picker>
          }
        },
        {
          label: '邮箱',
          render: (h, row) => {
            return <el-input disabled={this.disabled} v-model={row.email} placeholder='请输入邮箱地址'></el-input>
          }
        }
      ],
      enterpriseTableData: [],
      enterpriseColumns: [
        {
          label: '公司名称',
          prop: 'corporateName',
          showTooltip: true
        },
        {
          label: '签署链接',
          showTooltip: true,
          prop: 'certificateShortSignUrl',
          render(h, row) {
            return <div class='copy'>
              <span> { row.certificateShortSignUrl }</span>
              <i
                class='iconfont icon-a-Group779'
                v-clipboard:copy={row.certificateShortSignUrl}
              ></i>
            </div>
          }
        },
        {
          label: '认证链接',
          showTooltip: true,
          prop: 'shortAuthUrl',
          render(h, row) {
            return <div class='copy'>
              <span> { row.shortAuthUrl }</span>
              <i class='iconfont icon-a-Group779' v-clipboard:copy={row.shortAuthUrl}></i>
            </div>
          }
        },
        {
          label: '认证状态',
          showTooltip: true,
          prop: 'authStatus'
        },
        {
          label: '签署状态',
          showTooltip: true,
          prop: 'certificateSignStatus'
        },
        {
          label: '授权书',
          render: (h, row, index) => {
            return <cy-upload
              fileData={row.fileStorageDO}
              defaultDesc={`请上传授权书`}
              disabled
            />
          }
        }
      ]
    }
  },
  watch: {
    addInfo: {
      handler(newV) {
        if (newV && Object.keys(newV)) {
          const { businessAddress, locationMap, rentalContract, waterElectricityFees, officeEnvironment, creditInvestigationInfoList, businessLicense, basicAccountInformation, articlesAssociation, judgment, corporateName, certificateShortSignUrl, certificateSignStatus, shortAuthUrl, authStatus, id, cComprehensiveRiskInvestigationId, fileStorageDO, businessScope, registeredAddress, bankAccount, bank } = newV
          this.ruleForm = {
            businessAddress,
            id,
            cComprehensiveRiskInvestigationId,
            businessScope,
            registeredAddress,
            bankAccount,
            bank
          }
          this.locationMap = locationMap
          this.rentalContract = rentalContract
          this.waterElectricityFees = waterElectricityFees
          this.officeEnvironment = officeEnvironment
          this.businessLicense = businessLicense
          this.basicAccountInformation = basicAccountInformation
          this.articlesAssociation = articlesAssociation
          this.judgment = judgment
          this.tableData = creditInvestigationInfoList

          // 转一下个人征信身份证正反面回显
          this.tableData.forEach((el) => {
            const frontArr = []
            const backArr = []
            frontArr.push(el.frontFile)
            backArr.push(el.backFile)
            el.frontFile = frontArr
            el.backFile = backArr
          })

          this.enterpriseTableData = [
            {
              corporateName,
              certificateShortSignUrl,
              certificateSignStatus: certificateSignStatus === 1 ? '已签署' : '未签署',
              shortAuthUrl,
              authStatus: authStatus ? '已认证' : '未认证',
              fileStorageDO: [fileStorageDO]
            }
          ]
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 身份证正面上传成功回调
    async frontCardCallBack(fileList, fileName, row, index) {
      const fileFrontList = this.$refs.commTable.$refs[`idcardStorage_front_${index}`].getFileLists

      const fileBackList = this.$refs.commTable.$refs[`idcardStorage_back_${index}`].getFileLists

      if (fileFrontList.length && fileBackList.length) {
        this.ocrIdCard(fileFrontList[0].id, fileBackList[0].id, row)
      }
    },
    // 身份证背面上传成功回调
    backCardCallBack(fileList, fileName, row, index) {
      const fileFrontList = this.$refs.commTable.$refs[`idcardStorage_front_${index}`].getFileLists

      const fileBackList = this.$refs.commTable.$refs[`idcardStorage_back_${index}`].getFileLists

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

        if (res.success) {
          tableRow.domicileAddress = res.data.address
          tableRow.permanentAddress = res.data.address
          tableRow.socialCreditCode = res.data.idcard
          tableRow.validFrom = res.data.validfrom
          tableRow.validTo = res.data.validto
        }
      }
    },
    // 营业执照的OCR
    async businessLicenseCallBack() {
      const fileList = this.$refs.businessLicense.getFileLists

      if (fileList.length) {
        const res = await ocrBusinessLicense({
          fileId: fileList[0].id
        })

        if (res.success) {
          this.ruleForm.businessScope = res.data.businessScope
          this.ruleForm.registeredAddress = res.data.address
        }
      }
    },
    getParams(type) {
      const locationMap = this.$refs.locationMap.getFileLists
      const rentalContract = this.$refs.rentalContract.getFileLists
      const waterElectricityFees = this.$refs.waterElectricityFees.getFileLists
      const officeEnvironment = this.$refs.officeEnvironment.getFileLists
      const businessLicense = this.$refs.businessLicense.getFileLists
      const basicAccountInformation = this.$refs.basicAccountInformation.getFileLists
      const articlesAssociation = this.$refs.articlesAssociation.getFileLists
      const judgment = this.$refs.judgment.getFileLists

      // 个人征信
      const creditInvestigationInfoList = this.tableData.map((item, index) => {
        const {
          type,
          name,
          socialCreditCode,
          phoneNumber,
          domicileAddress,
          permanentAddress,
          validFrom,
          validTo,
          email
        } = item
        const fileFrontList = this.$refs.commTable.$refs[`idcardStorage_front_${index}`].getFileLists
        const fileBackList = this.$refs.commTable.$refs[`idcardStorage_back_${index}`].getFileLists
        // const fileLists = this.$refs.commTable.$refs[`idcardStorage${index}`].getFileLists
        return {
          type,
          name,
          socialCreditCode,
          phoneNumber,
          domicileAddress,
          permanentAddress,
          validFrom,
          validTo,
          email,
          front: fileFrontList.length ? fileFrontList[0].id : '',
          back: fileBackList.length ? fileBackList[0].id : ''
          // fileList: fileLists.map(item => item.id)
        }
      })

      const params = {
        ...this.ruleForm,
        locationMapIds: locationMap.map(item => item.id),
        rentalContractIds: rentalContract.map(item => item.id),
        waterElectricityFeesIds: waterElectricityFees.map(item => item.id),
        officeEnvironmentIds: officeEnvironment.map(item => item.id),
        businessLicenseIds: businessLicense.map(item => item.id),
        basicAccountInformationIds: basicAccountInformation.map(item => item.id),
        articlesAssociationIds: articlesAssociation.map(item => item.id),
        judgmentIds: judgment.map(item => item.id),
        creditInvestigationInfoList
      }

      return new Promise((resolve, reject) => {
        if (type === 'submit') {
          if (!locationMap.length) {
            this.$message.warning('请上传地点定位图')
            return
          }
          if (!rentalContract.length) {
            this.$message.warning('请上传租房合同')
            return
          }
          if (!waterElectricityFees.length) {
            this.$message.warning('请上传房租缴纳流水')
            return
          }
          if (!officeEnvironment.length) {
            this.$message.warning('请上传办公环境图')
            return
          }
          if (!businessLicense.length) {
            this.$message.warning('请上传营业执照')
            return
          }
          if (!basicAccountInformation.length) {
            this.$message.warning('请上传基本户信息')
            return
          }
          if (!articlesAssociation.length) {
            this.$message.warning('请上传公司章程和修正案')
            return
          }
          if (!judgment.length) {
            this.$message.warning('请上传结案证明或判决书')
            return
          }

          // 个人征信校验
          if (!this.validateCreditInvestigationInfoList(creditInvestigationInfoList)) return
          // 校验手机号、邮箱 -- 只校验法人
          if (creditInvestigationInfoList.length) {
            if (creditInvestigationInfoList[0].phoneNumber === '') {
              this.$message.warning('请输入个人征信第一行法定代表人手机号')
              return
            }
            if (creditInvestigationInfoList[0].email === '') {
              this.$message.warning('请输入个人征信第一行法定代表人邮箱地址')
              return
            }
            if (creditInvestigationInfoList[0].email && creditInvestigationInfoList[0].email.indexOf('@') < 0) {
              this.$message.warning(`请输入个人征信第一行合法邮箱地址`)
              return
            }
          }

          this.$refs.ruleForm.validate(valid => {
            if (valid) {
              resolve(params)
            } else {
              reject()
              return false
            }
          })
        } else {
          resolve(params)
        }
      })
    },
    // 校验个人征信表格
    validateCreditInvestigationInfoList(dataArr) {
      let i = 0
      while (i < dataArr.length) {
        if (!dataArr[i].name) {
          this.$message.warning(`请输入个人征信第${i + 1}行姓名`)
          return false
        } else if (!dataArr[i].socialCreditCode) {
          this.$message.warning(`请输入个人征信第${i + 1}行身份证号`)
          return false
        } else if (!dataArr[i].domicileAddress) {
          this.$message.warning(`请输入个人征信第${i + 1}行户籍地址`)
          return false
        } else if (!dataArr[i].permanentAddress) {
          this.$message.warning(`请输入个人征信第${i + 1}行常住地址`)
          return false
        } else if (!dataArr[i].validFrom) {
          this.$message.warning(`请输入个人征信第${i + 1}行证件开始日期`)
          return false
        } else if (!dataArr[i].validTo) {
          this.$message.warning(`请输入个人征信第${i + 1}行证件结束日期`)
          return false
        } else if (!dataArr[i].front) {
          this.$message.warning(`请上传个人征信第${i + 1}行身份证正面`)
          return false
        } else if (!dataArr[i].back) {
          this.$message.warning(`请上传个人征信第${i + 1}行身份证反面`)
          return false
        } else if (!dataArr[i].email) {
          this.$message.warning(`请输入个人征信第${i + 1}行邮箱`)
          return false
        }
        i++
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.guarantee-add-info {
}
</style>
<style lang="scss">
.guarantee-add-info {
  .copy {
    display: flex;
    align-items: center;
  }
}
</style>
