<template>
  <div class="open-info-details">
    <base-info
      ref="baseInfoRef"
      :details-info="baseDetailsInfo"
      :disabled="disabled"
      @changeCustomerStatus="changeCustomerStatus"
      @getLegalRepresentative="getLegalRepresentative"
      @getCompanyInfo="getCompanyInfo"
    />
    <template v-if="customerType === 0">
      <!-- 法定代表人 -->
      <cy-info-title style="margin-top: 20px">法定代表人信息</cy-info-title>
      <qichacha-info
        ref="legalpersonRef"
        :qichacha-options="legalpersonOptions"
        :details-info="detailsInfo.bocomLegalPersonInfo"
        front-file-type="bocomLegalRepresentativeIdCardFront"
        reverse-file-type="bocomLegalRepresentativeIdCardBack"
        type="legalperson"
        name="法定代表人姓名"
        :disabled="disabled"
      />
      <template v-if="shareholderOrActualCControllerStatus">
        <!-- 控股股东信息 -->
        <div v-for="(item, index) in detailsInfo.bocomShareholderActualControllers" :key="`${index}-0`">
          <cy-info-title style="margin-top: 20px">
            控股股东信息
            <div v-if="!disabled" slot="right">
              <el-button type="text" @click="synchronousClick('控股股东信息', index)">同步信息</el-button>
            </div>
          </cy-info-title>
          <qichacha-info
            :ref="`shareholderRef${index}`"
            :qichacha-options="shareholderOptions"
            :details-info="item"
            front-file-type="bocomShareholderIdCardFront"
            reverse-file-type="bocomShareholderIdCardBack"
            type="shareholder"
            name="控股股东姓名"
            :disabled="disabled"
          />
        </div>
      </template>
      <template v-if="!shareholderOrActualCControllerStatus">
        <!-- 实控人信息 -->
        <div v-for="(item, index) in detailsInfo.bocomShareholderActualControllers" :key="`${index}-1`">
          <cy-info-title style="margin-top: 20px">
            实控人信息
            <div v-if="!disabled" slot="right">
              <el-button type="text" @click="synchronousClick('实控人信息', index)">同步信息</el-button>
            </div>
          </cy-info-title>
          <qichacha-info
            :ref="`actualCControllerRef${index}`"
            :qichacha-options="shareholderOptions"
            :details-info="item"
            front-file-type="bocomShareholderIdCardFront"
            reverse-file-type="bocomShareholderIdCardBack"
            type="actualCController"
            name="实控人姓名"
            :disabled="disabled"
          />
        </div>
      </template>
    </template>
    <template v-if="customerType === 0 || customerType === 1">
      <!-- 受益人信息 || 负责人信息-->
      <div v-for="(item, index) in customerType === 0 ? detailsInfo.bocomBeneficiaryInfos : detailsInfo.bocomShareholderActualControllers" :key="`${index}-2`">
        <cy-info-title style="margin-top: 20px">
          {{ customerType === 0 ? '受益人信息' : '负责人信息' }}
          <div v-if="!disabled && customerType === 0" slot="right">
            <el-button
              type="text"
              @click="synchronousClick(customerType === 0 ? '受益人信息' : '负责人信息', index)"
            >
              同步信息
            </el-button>
            <el-button type="text" @click="beneficiaryClick('add')">新增</el-button>
            <el-button
              v-if="detailsInfo.bocomBeneficiaryInfos.length > 1"
              type="text"
              @click="beneficiaryClick('delete', index)"
            >
              <span style="color: #ff0404"> 删除</span>
            </el-button>
          </div>
        </cy-info-title>
        <qichacha-info
          :ref="`beneficiaryRef${index}`"
          :qichacha-options="beneficiaryOptions"
          :details-info="item"
          :front-file-type="customerType === 0 ? 'bocomBeneficiaryFront' : 'bocomShareholderIdCardFront'"
          :reverse-file-type="customerType === 0 ? 'bocomBeneficiaryBack' : 'bocomShareholderIdCardBack'"
          :type="customerType === 0 ? 'beneficiary' : 'commander'"
          :name=" customerType === 0 ? '受益人姓名' : '负责人姓名'"
          :disabled="disabled"
        />
      </div>

      <!-- 授权代理人信息 -->
      <cy-info-title style="margin-top: 20px">
        授权代理人信息
        <div v-if="!disabled" slot="right">
          <el-button type="text" @click="synchronousClick('授权代理人信息', '')">同步信息</el-button>
        </div>
      </cy-info-title>
      <authorized-agent-info ref="authorizedAgentRef" :details-info="detailsInfo.bocomAuthorizedAgent" :disabled="disabled" />
    </template>

    <div v-if="!disabled" class="submit-btn">
      <el-button
        @click="
          () => {
            $router.go(-1);
          }
        "
      >取消</el-button>
      <el-button type="primary" @click="submitClick('temp')">暂存</el-button>
      <el-button type="primary" @click="submitClick('submit')">提交</el-button>
    </div>
    <cy-dialog ref="dialogRef" title="同步信息" width="700px" top="30vh">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="同步角色" prop="synchronousRole">
          <el-select
            v-model="ruleForm.synchronousRole"
            placeholder="请选择同步角色"
          >
            <el-option
              v-for="item in getSynchronousList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="submit-btn">
        <el-button @click="synchronousDialogClick('cancel')">取消</el-button>
        <el-button type="primary" @click="synchronousDialogClick('submit')">提交</el-button>
      </div>

    </cy-dialog>
  </div>
</template>

<script>
import { getDetails, submitData } from '@/api/accountCenter/openInfoManage'
export default {
  components: {
    BaseInfo: () => import('./components/BaseInfo.vue'),
    QichachaInfo: () => import('./components/QichachaInfo.vue'),
    AuthorizedAgentInfo: () => import('./components/AuthorizedAgentInfo.vue')
  },
  data() {
    return {
      disabled: false,
      customerType: '',
      detailsInfo: {
        bocomLegalPersonInfo: {
          name: ''
        },
        bocomShareholderActualControllers: [],
        // 受益人信息
        bocomBeneficiaryInfos: [],
        // 授权人信息
        bocomAuthorizedAgent: {
          authorizedAgent: 0
        }
      },
      // 基础详情
      baseDetailsInfo: {},
      // 深拷贝详情
      deepDetailsInfo: {},
      legalpersonOptions: {
        name: 'name', // 姓名
        nationality: 'nationality', // 国籍
        idCardFrontList: 'frontFile', // 身份证正面
        idCardReverseList: 'backFile', // 身份证反面
        frontId: 'front', // 正面id
        backId: 'back', // 反面id
        idType: 'certificateType', // 证件种类
        idNumber: 'certificateCode', // 证件号
        periodValidityStart: 'periodOfValidityFrom', // 证件有效期开始
        periodValidityEnd: 'periodOfValidity', // 证件有效期结束
        periodValidityDate: 'periodValidityDate', // 证件有效期数组
        phone: 'phoneNumber', // 手机号
        personType: 'personType'
      },
      shareholderOptions: {
        name: 'name', // 姓名
        idCardFrontList: 'frontFile', // 身份证正面
        idCardReverseList: 'backFile', // 身份证反面
        frontId: 'front', // 正面id
        backId: 'back', // 反面id
        idType: 'certificateType', // 证件种类
        idNumber: 'certificateCode', // 证件号
        periodValidityStart: 'periodOfValidityFrom', // 证件有效期开始
        periodValidityEnd: 'periodOfValidity', // 证件有效期结束
        periodValidityDate: 'periodValidityDate', // 证件有效期数组
        personType: 'personType'
      },
      // 控股股东或实控人状态
      shareholderOrActualCControllerStatus: true,
      beneficiaryOptions: {
        name: 'name', // 姓名
        nationality: 'country', // 国籍
        idCardFrontList: 'frontFile', // 身份证正面
        idCardReverseList: 'backFile', // 身份证反面
        frontId: 'front', // 正面id
        backId: 'back', // 反面id
        idType: 'certificateType', // 证件种类
        idNumber: 'certificateCode', // 证件号
        periodValidityStart: 'periodOfValidityFrom', // 证件有效期开始
        periodValidityEnd: 'periodOfValidity', // 证件有效期结束
        periodValidityDate: 'periodValidityDate', // 证件有效期数组
        address: 'address',
        phone: 'phoneNumber', // 手机号
        personType: 'personType'
      },

      // 同步信息
      ruleForm: {
        synchronousRole: ''
      },
      rules: {
        synchronousRole: [{ required: true, message: `请选择同步角色`, trigger: 'change' }]
      },
      // 同步角色列表
      synchronousList: [],
      // 同步类型
      synchronousType: '',
      // 同步索引
      synchronousIndex: ''
    }
  },
  computed: {
    getSynchronousList() {
      let list = []
      if (this.customerType === 0) {
        if (this.shareholderOrActualCControllerStatus) {
          list = ['法定代表人信息', '控股股东信息', '受益人信息']
        } else {
          list = ['法定代表人信息', '实控人信息', '受益人信息']
        }
      } else if (this.customerType === 1) {
        list = ['负责人信息']
      } else {
        list = []
      }
      return list.filter(item => item !== this.synchronousType)
    }
  },
  created() {
    const { type } = this.$route.query
    const { id } = this.$route.params
    if (type === 'edit') {
      this.getDetailsList(id)
    } else if (type === 'see') {
      this.disabled = true
      this.getDetailsList(id)
    }
    this.deepDetailsInfo = JSON.parse(JSON.stringify(this.detailsInfo))
  },
  methods: {
    getDetailsList(id) {
      getDetails({ id }).then(({ data }) => {
        this.detailsInfo = {
          ...data,
          bocomLegalPersonInfo: data.bocomLegalPersonInfo ? data.bocomLegalPersonInfo : this.detailsInfo.bocomLegalPersonInfo
        }
        this.baseDetailsInfo = {
          ...data
        }
        delete this.baseDetailsInfo.bocomLegalPersonInfo
        delete this.baseDetailsInfo.bocomShareholderActualControllers
        delete this.baseDetailsInfo.bocomBeneficiaryInfos
        delete this.baseDetailsInfo.bocomAuthorizedAgent
        this.customerType = data.customerType
      })
    },
    // 客户状态变化
    changeCustomerStatus(val) {
      this.customerType = val
      this.detailsInfo = JSON.parse(JSON.stringify(this.deepDetailsInfo))
    },
    // 获取法定代表人
    getLegalRepresentative(name) {
      this.detailsInfo.bocomLegalPersonInfo.name = name
      if (this.customerType === 1) {
        this.detailsInfo.bocomShareholderActualControllers = [{ name: name, type: 2, personType: 2, country: 'registerCountry_CHN' }]
      }
    },

    // 获取控股股东名称 - 受益人信息名称
    getCompanyInfo(val) {
      if (this.customerType === 0) {
        const { beneficialOwnerList, partnerList } = val
        const beneficialOwnerListData = beneficialOwnerList.length ? beneficialOwnerList : [this.detailsInfo.bocomLegalPersonInfo.name]
        const partnerListData = partnerList.length ? partnerList : [{ name: this.detailsInfo.bocomLegalPersonInfo.name, type: 1 }]
        if (partnerListData[0].type === 1) {
          this.shareholderOrActualCControllerStatus = true
        } else {
          this.shareholderOrActualCControllerStatus = false
        }
        this.detailsInfo.bocomShareholderActualControllers = partnerListData.map(item => ({ name: item.name, personType: item.type }))
        this.detailsInfo.bocomBeneficiaryInfos = beneficialOwnerListData.map(item => ({ name: item, country: 'registerCountry_CHN' }))
      }
    },
    // 提交
    async submitClick(type) {
      const baseInfo = await this.$refs.baseInfoRef.getParams(type)
      if (baseInfo === false) return
      let bocomLegalPersonInfo = null
      // 控股股东信息
      const bocomShareholderActualControllers = this.detailsInfo.bocomShareholderActualControllers
      const bocomShareholderActualControllersList = []
      // 受益人信息
      const bocomBeneficiaryInfosList = []
      let bocomAuthorizedAgent = null

      if (this.customerType === 0 || this.customerType === 1) {
        // 法定代表人
        if (this.customerType === 0) {
          bocomLegalPersonInfo = await this.$refs.legalpersonRef.getParams(type)
          if (bocomLegalPersonInfo === false) return
        }

        if (bocomShareholderActualControllers.length) {
          for (let i = 0; i < bocomShareholderActualControllers.length; i++) {
            let refName = ''
            if (this.customerType === 0 && this.shareholderOrActualCControllerStatus) {
              refName = `shareholderRef${i}`
            } else if (this.customerType === 0 && !this.shareholderOrActualCControllerStatus) {
              refName = `actualCControllerRef${i}`
            }
            if (this.customerType === 1) {
              refName = `beneficiaryRef${i}`
            }
            const shareholderObj = await this.$refs[refName][0].getParams(type)
            if (shareholderObj === false) return
            bocomShareholderActualControllersList.push({
              // ...bocomShareholderActualControllers[i],
              ...shareholderObj
            })
          }
        }
        if (this.customerType === 0) {
          // 受益人信息
          const bocomBeneficiaryInfos = this.detailsInfo.bocomBeneficiaryInfos
          if (this.customerType === 0) {
            if (bocomBeneficiaryInfos.length) {
              for (let i = 0; i < bocomBeneficiaryInfos.length; i++) {
                const shareholderObj = await this.$refs[`beneficiaryRef${i}`][0].getParams(type)
                if (shareholderObj === false) return
                bocomBeneficiaryInfosList.push({
                  // ...bocomBeneficiaryInfos[i],
                  ...shareholderObj
                })
              }
            }
          }
        }
        // 授权代理人
        bocomAuthorizedAgent = await this.$refs.authorizedAgentRef.getParams(type)
        if (bocomAuthorizedAgent === false) return
      }

      const params = {
        Loading: true,
        visible: type !== 'temp',
        ...baseInfo,
        bocomLegalPersonInfo,
        bocomShareholderActualControllers: bocomShareholderActualControllersList,
        bocomBeneficiaryInfos: bocomBeneficiaryInfosList,
        bocomAuthorizedAgent,
        id: this.$route.query.type === 'add' ? null : this.$route.params.id
      }
      submitData(params).then((data) => {
        this.$message.success(`${type === 'temp' ? '暂存成功' : '提交成功'}`)
        this.$router.go(-1)
      })
    },
    // 同步信息
    synchronousClick(type, index) {
      this.synchronousType = type
      this.synchronousIndex = index
      if (type === '授权代理人信息') {
        this.authorizedAgentSynchronous()
      } else {
        this.$refs.dialogRef.show = true
        this.ruleForm.synchronousRole = ''
      }
    },
    getSynchronousParams() {
      const list = [{
        name: '法定代表人信息',
        ref: 'legalpersonRef',
        detailsObj: 'bocomLegalPersonInfo',
        personType: null
      }, {
        name: '控股股东信息',
        ref: 'shareholderRef',
        detailsObj: 'bocomShareholderActualControllers',
        personType: 0
      }, {
        name: '授权代理人信息',
        ref: 'authorizedAgentRef',
        detailsObj: 'bocomAuthorizedAgent',
        personType: null
      }, {
        name: '实控人信息',
        ref: 'actualCControllerRef',
        detailsObj: 'bocomShareholderActualControllers',
        personType: 1
      }, {
        name: '受益人信息',
        ref: 'beneficiaryRef',
        detailsObj: 'bocomBeneficiaryInfos',
        personType: null
      }, {
        name: '负责人信息',
        ref: 'beneficiaryRef',
        detailsObj: 'bocomShareholderActualControllers',
        personType: 2
      }]
      // 同步的对象
      const synchronousListObj = list.find(item => item.name === this.ruleForm.synchronousRole)
      // 被同步的对象
      const passiveListObj = list.find(item => item.name === this.synchronousType)
      // 同步的RuleForm
      let synchronousRuleFormObj = {}
      let synchronousFilesObj = {}

      if (this.synchronousIndex !== '') {
        // 被同步的name
        let name = ''
        // 授权代理人信息不进行nam对比
        if (passiveListObj.name !== '授权代理人信息') {
          name = this.detailsInfo[passiveListObj.detailsObj][this.synchronousIndex].name
        }

        if (this.ruleForm.synchronousRole === '法定代表人信息') {
          synchronousRuleFormObj = this.$refs[synchronousListObj.ref].ruleForm
          synchronousFilesObj = this.$refs[synchronousListObj.ref].getFile()
        } else {
          // 是数组的情况
          this.detailsInfo[synchronousListObj.detailsObj].forEach((item, index) => {
            if (passiveListObj.name === '授权代理人信息') {
              synchronousRuleFormObj = this.$refs[`${synchronousListObj.ref}${index}`][0].ruleForm
              synchronousFilesObj = this.$refs[`${synchronousListObj.ref}${index}`][0].getFile()
            } else {
              if (this.$refs[`${synchronousListObj.ref}${index}`][0].ruleForm.name === name) {
                synchronousRuleFormObj = this.$refs[`${synchronousListObj.ref}${index}`][0].ruleForm
                synchronousFilesObj = this.$refs[`${synchronousListObj.ref}${index}`][0].getFile()
              }
            }
          })
        }

        if (passiveListObj.name !== '授权代理人信息' && synchronousRuleFormObj?.name !== name) {
          this.$message.warning(`${this.synchronousType}姓名与${synchronousListObj.name}姓名不一致无法同步`)
          return
        }
      } else {
        synchronousRuleFormObj = this.$refs[`${synchronousListObj.ref}`].ruleForm
        synchronousFilesObj = this.$refs[`${synchronousListObj.ref}`].getFile()
      }

      const { idType, idNumber, periodValidityDate, contactAddress, name, phone } = synchronousRuleFormObj
      const obj = {
        name,
        certificateType: idType,
        certificateCode: idNumber,
        periodOfValidityFrom: periodValidityDate && periodValidityDate.length ? periodValidityDate[0] : '',
        periodOfValidity: periodValidityDate && periodValidityDate.length ? periodValidityDate[1] : '',
        frontFile: synchronousFilesObj.idCardFrontList[0],
        backFile: synchronousFilesObj.idCardReverseList[0],
        personType: passiveListObj.personType,
        address: contactAddress,
        phoneNumber: phone
      }
      if (passiveListObj.name === '授权代理人信息') {
        this.$set(this.detailsInfo, passiveListObj.detailsObj, {
          ...this.detailsInfo[passiveListObj.detailsObj],
          ...obj
        })
      } else {
        this.$set(this.detailsInfo[passiveListObj.detailsObj], this.synchronousIndex, {
          ...this.detailsInfo[passiveListObj.detailsObj][this.synchronousIndex],
          ...obj
        })
        this.$refs.dialogRef.show = false
      }
      this.$message.success('同步成功')
    },
    synchronousDialogClick(type) {
      if (type === 'cancel') {
        this.$refs.dialogRef.show = false
      } else if (type === 'submit') {
        this.$refs.ruleFormRef.validate((valid) => {
          if (valid) {
            this.getSynchronousParams()
          } else {
            return false
          }
        })
      } else if (type === 'temp') {
        this.getSynchronousParams()
      }
    },
    authorizedAgentSynchronous() {
      this.$confirm(`此操作将会同步${this.customerType === 0 ? '法人信息' : '负责人信息'}。请确认是否继续？`, '同步信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ruleForm.synchronousRole = this.customerType === 0 ? '法定代表人信息' : '负责人信息'
        if (this.customerType === 1) {
          this.synchronousIndex = 0
        }
        this.synchronousDialogClick('temp')
      })
    },
    // 受益人新增删除
    async beneficiaryClick(type, index) {
      if (type === 'add') {
        const obj = {
          name: '',
          country: 'registerCountry_CHN'
        }
        this.$set(this.detailsInfo, 'bocomBeneficiaryInfos', [...this.detailsInfo.bocomBeneficiaryInfos, JSON.parse(JSON.stringify(obj))])
      } else if (type === 'delete') {
        for (let i = 0; i < this.detailsInfo.bocomBeneficiaryInfos.length; i++) {
          const beneficiaryObj = await this.$refs[`beneficiaryRef${i}`][0].getParams('temp')
          const beneficiaryFilesObj = this.$refs[`beneficiaryRef${i}`][0].getFile()
          const obj = {
            ...beneficiaryObj,
            frontFile: beneficiaryFilesObj.idCardFrontList[0],
            backFile: beneficiaryFilesObj.idCardReverseList[0]
          }
          this.detailsInfo.bocomBeneficiaryInfos[i] = JSON.parse(JSON.stringify(obj))
        }
        setTimeout(() => {
          this.detailsInfo.bocomBeneficiaryInfos.splice(index, 1)
        }, 200)
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
