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

    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      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>
        <div v-if="!disabled" class="synchronization">
          <el-button type="text" @click="synchronizationClick">一键同步</el-button>
        </div>
        <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 class="slot-name-desc">*</span>
          <span>企业征信查询授权书</span>
        </template>
        <cy-comm-table
          name="enterprise"
          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">
        <div class="address">
          <div v-if="!disabled">
            <el-cascader
              v-model="ruleForm.cascaderAddress"
              style="width: 100%;"
              placeholder="请选择省市区"
              :options="constant.regionList"
              :props="{ value: 'name', label: 'name' }"
              @change="getBusinessAddress"
            />
          </div>
          <div v-if="!disabled">
            <el-input
              v-model="ruleForm.inputAddress"
              style="width: 100%;"
              placeholder="请输入详细地址"
              @blur="getBusinessAddress"
            />
          </div>
          <div :style="{ width: disabled ? '100%' : 'calc(33.5% - 20px)'}">
            <el-input v-model="ruleForm.businessAddress" disabled placeholder="请输入经营地址" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="地点定位图" class="form-required" prop="locationMap">
        <cy-upload
          ref="locationMap"
          :upload-params="{
            fileType: 'enterprise_location_map'
          }"
          :file-data="locationMap"
          :disabled="disabled"
          :upload-from-orange-status="true"
          placeholder="请上传地点定位图"
        />
      </el-form-item>
      <el-form-item label="租房合同" class="form-required">
        <cy-upload
          ref="rentalContract"
          :upload-params="{
            fileType: 'enterprise_rental_contract'
          }"
          :disabled="disabled"
          :file-data="rentalContract"
          :upload-from-orange-status="true"
          placeholder="请上传租房合同"
        />
      </el-form-item>
      <el-form-item label="房租缴纳流水" class="form-required">
        <cy-upload
          ref="waterElectricityFees"
          :upload-params="{
            fileType: 'enterprise_water_electricity_fees'
          }"
          :disabled="disabled"
          :file-data="waterElectricityFees"
          :upload-from-orange-status="true"
          placeholder="请上传房租缴纳流水"
        />
      </el-form-item>
      <el-form-item label="办公环境图" class="form-required">
        <cy-upload
          ref="officeEnvironment"
          :upload-params="{
            fileType: 'enterprise_office_environment'
          }"
          :disabled="disabled"
          :file-data="officeEnvironment"
          :upload-from-orange-status="true"
          placeholder="请上传办公环境图"
        />
      </el-form-item>
      <template v-if="!hasGuaranteeEnterprise">
        <cy-info-title type="center">公司相关信息</cy-info-title>
        <el-form-item label="营业执照" class="form-required" prop="businessLicense">
          <cy-upload
            ref="businessLicense"
            :upload-params="{
              fileType: 'enterprise_business_license'
            }"
            :disabled="disabled"
            :file-data="businessLicense"
            :isCallBack="true"
            :limit="1"
            @call-back="businessLicenseCallBack"
            :upload-from-orange-status="true"
            placeholder="请上传营业执照"
          />
        </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="form-required" prop="basicAccountInformation">
          <cy-upload
            ref="basicAccountInformation"
            :upload-params="{
              fileType: 'enterprise_basic_account_information'
            }"
            :disabled="disabled"
            :file-data="basicAccountInformation"
            :upload-from-orange-status="true"
            placeholder="请上传基本户信息"
          />
        </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="form-required" prop="articlesAssociation">
          <cy-upload
            ref="articlesAssociation"
            :upload-params="{
              fileType: 'enterprise_articles_association'
            }"
            :disabled="disabled"
            :file-data="articlesAssociation"
            :upload-from-orange-status="true"
            placeholder="请上传公司章程和修正案"
          />
        </el-form-item>
        <el-form-item label="结案证明或判决书" prop="judgment">
          <cy-upload
            ref="judgment"
            :upload-params="{
              fileType: 'enterprise_judgment'
            }"
            :disabled="disabled"
            :file-data="judgment"
            :upload-from-orange-status="true"
            file-type="bmp,png,jpg,jpeg"
            placeholder="请上传结案证明或判决书"
          />
        </el-form-item>
      </template>

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

<script>
import { salesContractManagementGetAuthStatus, salesContractManagementSignType } from '@/api/myTrade/salesContractManagement/salesContractManagement'
import creditInvestigation from '../mixins/creditInvestigation'
import { mapGetters } from 'vuex'
import { ocrIdentifyCard, ocrBusinessLicense } from '@/api/sushang/supplierCredit'

export default {
  mixins: [creditInvestigation],
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    addInfo: {
      type: Object,
      default: () => {}
    },
    hasGuaranteeEnterprise: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableKey: 0,
      ruleForm: {
        businessAddress: '',
        id: '',
        cascaderAddress: [],
        inputAddress: '',
        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',
          ruleRequired: true
        },
        {
          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 && row.frontFile.length) ? row.frontFile : []}
              oncall-back={ (fileList, fileName) => {
                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.frontFile && row.frontFile.length) ? 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: 'shortAuthUrl',
          width: 300,
          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: 'certificateShortSignUrl',
          width: 300,
          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: '认证状态',
          headerAlign: 'center',
          renderHeader: (h, row) => {
            return <div>
              <div>认证状态</div>
              { !this.disabled && <div style='color:#FE7D0B'>(认证后请点击刷新)</div> }
            </div>
          },
          showTooltip: true,
          prop: 'authStatus',
          render: (h, row) => {
            return <div class='sgin-box'>
              <span
                style={{ color: row.authStatus === '未认证' ? '#FF0000' : '' }}>
                { row.authStatus }
              </span>
              { !this.disabled ? <i
                disabled={this.disabled}
                class='iconfont icon-a-Group8131'
                onClick={() => { this.refreshAuthStatus(row) }}
              ></i> : '' }
            </div>
          }
        },
        {
          label: '签署状态',
          headerAlign: 'center',
          renderHeader: (h, row) => {
            return <div>
              <div>签署状态</div>
              {!this.disabled && <div style='color:#FE7D0B'>(签署后请点击刷新)</div>}
            </div>
          },
          showTooltip: true,
          prop: 'certificateSignStatus',
          render: (h, row) => {
            return <div class='sgin-box'>
              <span
                style={{ color: row.authStatus === '未签署' ? '#FF0000' : '' }}>
                { row.certificateSignStatus }
              </span>
              { !this.disabled ? <i
                class='iconfont icon-a-Group8131'
                onClick={() => { this.refreshSignStatus(row) }}
              ></i> : ''
              }
            </div>
          }
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['constant'])
  },
  watch: {
    addInfo: {
      handler(newV) {
        if (newV === undefined || !newV?.id) return
        if (newV && Object.keys(newV)) {
          const { businessAddress, locationMap, rentalContract, waterElectricityFees, officeEnvironment, businessLicense, basicAccountInformation, articlesAssociation, judgment, creditInvestigationInfoList, corporateName, certificateShortSignUrl, certificateSignStatus, shortAuthUrl, authStatus, id, cComprehensiveRiskInvestigationId, fddCustomerId, certificateContractId, certificateTransactionId, businessScope, registeredAddress, bankAccount, bank } = JSON.parse(JSON.stringify(newV))
          this.ruleForm = {
            businessAddress,
            id,
            cComprehensiveRiskInvestigationId,
            cascaderAddress: [],
            inputAddress: '',
            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 = JSON.parse(JSON.stringify(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 ? '已认证' : '未认证',
              fddCustomerId,
              certificateContractId,
              certificateTransactionId
            }
          ]
        }
      },
      immediate: true,
      deep: true
    }
  },

  created() {
    this.$store.dispatch('getConstant', ['regionList'])
  },
  methods: {
    refreshAuthStatus(row) {
      const { fddCustomerId } = row
      salesContractManagementGetAuthStatus({ customerId: fddCustomerId }).then(({ data }) => {
        this.$message.success('刷新成功')
        const { authStatus } = data
        this.enterpriseTableData[0].authStatus = authStatus ? '已认证' : '未认证'
      })
    },
    refreshSignStatus(row) {
      const { fddCustomerId, certificateContractId, certificateTransactionId } = row
      const params = {
        customerId: fddCustomerId,
        contractId: certificateContractId,
        transactionId: certificateTransactionId
      }
      salesContractManagementSignType(params).then(({ data }) => {
        this.$message.success('刷新成功')
        this.enterpriseTableData[0].certificateSignStatus = data ? '已签署' : '未签署'
      })
    },
    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 creditInvestigationInfoList = this.tableData.map((item, index) => {
        const {
          type,
          name,
          socialCreditCode,
          phoneNumber,
          domicileAddress,
          permanentAddress,
          validFrom,
          validTo,
          email
        } = item
        // const fileLists = this.$refs.commTable.$refs[`idcardStorage${index}`].getFileLists
        const fileFrontList = this.$refs.commTable.$refs[`idcardStorage_front_${index}`].getFileLists
        const fileBackList = this.$refs.commTable.$refs[`idcardStorage_back_${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)
        }
      })

      var 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: [],
        basicAccountInformationIds: [],
        articlesAssociationIds: [],
        judgmentIds: [],
        creditInvestigationInfoList
      }
      delete params.cascaderAddress
      delete params.inputAddress

      if (!this.hasGuaranteeEnterprise) {
        const businessLicense = this.$refs.businessLicense.getFileLists
        const basicAccountInformation = this.$refs.basicAccountInformation.getFileLists
        const articlesAssociation = this.$refs.articlesAssociation.getFileLists
        const judgment = this.$refs.judgment.getFileLists
        params = {
          ...params,
          businessLicenseIds: businessLicense.map(item => item.id),
          basicAccountInformationIds: basicAccountInformation.map(item => item.id),
          articlesAssociationIds: articlesAssociation.map(item => item.id),
          judgmentIds: judgment.map(item => item.id)
        }
      }

      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 (!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)
        }
      })
    },
    getBusinessAddress() {
      const address = this.ruleForm.cascaderAddress.length ? this.ruleForm.cascaderAddress.join('') : ''
      this.ruleForm.businessAddress = address + this.ruleForm.inputAddress
    },
    // 身份证正面上传成功回调
    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) {
        row.frontFile = fileFrontList
        row.backFile = fileBackList
        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) {
        row.frontFile = fileFrontList
        row.backFile = fileBackList
        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
        })

        console.log(res)
        if (res.success) {
          this.ruleForm.businessScope = res.data.businessScope
          this.ruleForm.registeredAddress = res.data.address
        }
      }
    },
    // 校验个人征信表格
    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>
.add-info {
  .synchronization {
    position: absolute;
    right: 20px;
    top: 14px;
    z-index: 10;
  }
}
</style>
<style lang="scss">
.add-info {
  .copy, .sgin-box {
    display: flex;
    align-items: center;
  }
  .sgin-box {
    justify-content: center;
  }
  .icon-a-Group779, .icon-a-Group8131 {
    margin-left: 10px;
    font-size: 30px;
  }
  .address {
    display: flex;
    & > div {
      width: calc(33.5% - 20px);
      margin-right: 20px;
      &:first-child {
        width: calc(33.5% - 20px);
        margin-right: 20px;
      }
      &:last-child {
        // width: 66.66%;
        margin-right: 0px;
      }
    }
  }
}
</style>
