<!-- 新单跟进的修改提交还没写 -->
<template>
  <div>
    <div v-if="processedinsuredData.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <el-button
              type="warning"
              icon="DocumentAdd"
              @click="exportInfo"
              v-if="showContacts"
              :disabled="editStatus"
              >导入联系人</el-button
            >
            <!--  v-if="props.idsObj.appointmentBizId" -->
            <el-button
              v-if="props.showSubmitBtn"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus(!editStatus)"
              style="margin-left: 10px"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="insuredInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <div v-for="father in processedinsuredData">
          <el-row style="margin-bottom: 10px" v-if="father.showMoudle">
            <div class="formBox">
              <div class="fatherLable">{{ father.fatherTitle }}</div>
              <div class="fatherDes">{{ father.description }}</div>

              <el-row :gutter="20">
                <template v-for="child in father.data" :key="child.key">
                  <el-col :sm="child.sm" :lg="child.lg" class="formItem" v-if="child.show">
                    <div>
                      <!--  :rules="
                          child.required
                            ? [
                                {
                                  required: true,
                                  message: `${child.label}不能为空`,
                                  trigger: 'blur'
                                }
                              ]
                            : []
                        " -->
                      <el-form-item
                        :label-width="child.labelWidth"
                        :label="child.label"
                        :prop="child.key"
                        :key="child.key"
                        :label-position="child.labelPosition"
                        :rules="getRules(child)"
                      >
                        <el-input
                          v-if="child.domType === 'Input'"
                          :type="child.inputType"
                          v-model="form[child.key]"
                          :placeholder="child.placeholder"
                          maxlength="30"
                          :disabled="child.disabled"
                        />
                        <el-select
                          v-if="child.domType === 'Select'"
                          v-model="form[child.key]"
                          :placeholder="child.placeholder"
                          @change="handleSelectChange(father, child)"
                          :disabled="child.disabled"
                        >
                          <el-option
                            v-for="item in child.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                        <el-date-picker
                          v-model="form[child.key]"
                          style="width: 100%"
                          v-if="child.domType === 'DatePicker'"
                          type="date"
                          :placeholder="child.placeholder"
                          :disabled="child.disabled"
                          :disabled-date="time => disabledDate(time, child)"
                          @change="handleDateChange(child)"
                        />
                        <el-input
                          v-if="child.domType === 'arrowRight'"
                          v-model="form[child.key]"
                          :placeholder="child.placeholder"
                          @click="handleFoucs(child)"
                          :suffix-icon="ArrowRight"
                          readonly
                          :disabled="child.disabled"
                        >
                        </el-input>
                        <el-button v-if="child.domType === 'button'" :type="child.buttonType">{{
                          child.buttonTxt
                        }}</el-button>
                      </el-form-item>
                    </div>
                  </el-col>
                </template>
              </el-row>
            </div>
          </el-row>
        </div>
        <el-row v-if="props.showSubmitBtn">
          <el-col>
            <div class="tabButton">
              <!-- <el-button
                type="primary"
                icon="RefreshRight"
                @click="resetForm"
                size="large"
                :disabled="editStatus"
                >重置</el-button
              > -->
              <el-button
                type="primary"
                icon="Check"
                @click="submitForm"
                size="large"
                :disabled="editStatus"
                >保存</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-dialog title="联系人信息" v-model="openList" width="600px" append-to-body>
        <div>
          <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="85px">
            <el-form-item label="联系人姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" @input="customerList" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" circle @click="customerList" />
              <el-button type="info" icon="Refresh" circle @click="resetCustomerList" />
            </el-form-item>
          </el-form>
          <div class="customerBox">
            <div class="customerItem" v-for="item in tableData" :key="item.id">
              <div class="top">
                <div class="right">
                  <el-button type="primary" size="small" @click="handleExport(item)"
                    >导入联系人</el-button
                  >
                </div>
              </div>
              <div class="bottom">
                <div class="left">
                  <div class="infoItem">
                    <span>姓名：</span>
                    <span> {{ item.name || '暂无' }}</span>
                  </div>
                  <div class="infoItem">
                    <span>性别：</span>
                    <span>
                      <dict-tag :options="fetchDictData('sys_gender')" :value="item.gender"
                    /></span>
                  </div>
                  <div class="infoItem">
                    <span>年龄：</span>
                    <span> {{ item.age || '暂无' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <!-- <div v-else class="domEmpty" v-loading="loading"></div> -->
    <Phone
      @close="handleCloseDrawer"
      :showDrawer="showPhoneDrawer"
      :drawerInfo="drawerInfo"
      :phoneMenuList="phoneMenuList"
      :phoneQuickList="phoneQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Address
      @close="handleCloseDrawer"
      :showAddressDrawer="showAddressDrawer"
      :drawerInfo="drawerInfo"
      :addressMenuList="addressMenuList"
      :addressQuickList="addressQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Country
      :showCountryDrawer="showCountryDrawer"
      @close="handleCloseDrawer"
      @confirmCountry="confirmDrawer"
    />
  </div>
</template>
<script setup name="insuredInfo">
import { validateEnglish } from '@/utils/validate'
import { calculateExactAge } from '@/utils/date'
import dayjs from 'dayjs'
import { ArrowRight } from '@element-plus/icons-vue'
import policyDomData from '@/formJson/insured'
import Country from '@/views/components/country'
import Phone from '@/views/components/phone'
import Address from '@/views/components/address'
import { updatePolicyInsurant } from '@/api/sign/underwritingMain'
import { watch, nextTick } from 'vue'
import { getCustomerList } from '@/api/sign/fna'
import { editInsurantInfo } from '@/api/sign/appointment'
import useDictStore from '@/store/modules/dict'

const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  apiInsurantInfoDto: { type: Object, default: () => ({}) }, //父组件传递过来的预约信息的详情
  appointmentStatus: { type: Number }, //父组件传递过来的预约的状态
  customerInfo: { type: Object, default: () => ({}) }, //客户详情回显表单用
  currentPolicyholderInfo: { type: Object, default: () => ({}) }, //当前保单的投保人信息
  showSubmitBtn: { type: Boolean, default: false }, //父组件状态，新增、修改
  pageSource: { type: String, default: '' } //页面来源
})
const emit = defineEmits(['handleSuccessEdit', 'policyEditSuccess'])
const { proxy } = getCurrentInstance()
// const { csf_id_type, sys_gender } = proxy.useDict('csf_id_type', 'sys_gender')
const insuredInfoFormRef = ref(null)
const showPhoneDrawer = ref(false) //电话抽屉开关
const showAddressDrawer = ref(false) //地址抽屉开关
const showCountryDrawer = ref(false) //国家/地区抽屉开关
const drawerInfo = ref({}) // 用于存储所有arrowRight类型的输入框输入值
const saveKey = ref({}) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const tempSaveKey = ref({}) // 用于tab切换的时候保存一份临时的值，防止切换的时候数据丢失
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作
const showContacts = ref(true)

const tableLoading = ref(false)
const tableData = ref([])
const total = ref(0)
// 地址组件菜单数据
const addressMenuList = ref([
  {
    name: '国家/地区',
    icon: false,
    value: '',
    placeholder: '请输入国家/地区',
    key: 'region'
  },
  {
    name: '省市',
    icon: false,
    value: '',
    placeholder: '请输入省市',
    key: 'city'
  },
  {
    name: '街道',
    icon: false,
    value: '',
    placeholder: '请输入街道',
    key: 'street'
  },
  {
    name: '详细地址',
    icon: false,
    value: '',
    placeholder: '请输入详细地址',
    key: 'location'
  }
])
// 快捷地址的数据
const addressQuickList = ref([])
const phoneMenuList = ref([
  {
    name: '区号',
    icon: true,
    value: '',
    placeholder: '请输入区号',
    arrow: true,
    type: 'string'
  },
  {
    name: '电话号码',
    icon: false,
    value: '',
    placeholder: '请输入电话号码',
    type: 'number'
  }
])
const phoneQuickList = ref([])
const tempAddressQuickList = ref([])
const tempPhoneQuickList = ref([])
const personalObj = ref({}) //存储个人key
const companyObj = ref({}) //存储公司key
const commonObj = ref({}) //存储个人和公司的公共key
const deleteKeyList = ref([
  'objType',
  'mailingAddress',
  'residentialAddress',
  'residenceAddress',
  'companyAddress',
  'txAddress',
  'companyEnterAddress',
  'phoneString',
  'phoneCode'
]) // 存储需要删除的key
const data = reactive({
  form: {},
  tempPolicyForm: {}, //由于切换tab的时候，表单数据会重置，所以需要
  processedinsuredData: [], // 处理后的表单数据
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedinsuredData, queryParams, oldAppointmentData, tempPolicyForm } =
  toRefs(data)
// 获取表单项的校验规则
const getRules = child => {
  const rules = []

  // 必填校验
  if (child.required) {
    rules.push({
      required: true,
      message: `${child.label}不能为空`,
      trigger: 'blur'
    })
  }

  // 为英文姓名添加自定义校验
  if (child.key === 'nameEn') {
    rules.push({
      validator: validateEnglish,
      trigger: 'change'
    })
  }

  return rules
}

const handleDateChange = child => {
  let age = null
  if (child.key == 'birthday') {
    age = calculateExactAge(proxy.formatToDate(form.value.birthday))
    if (age >= 0) {
      form.value.age = age
    }
  }
}
const disabledDate = (time, child) => {
  return time.getTime() > Date.now()
  // if (child.key == 'birthday') {
  //   // 计算18年前的今天
  //   const eighteenYearsAgo = dayjs().subtract(18, 'year')
  //   // 禁用今天之后的日期和18年前的今天之后的日期
  //   return time.getTime() > Date.now() || time.getTime() > eighteenYearsAgo.valueOf()
  // } else {
  //   return time.getTime() > Date.now()
  // }
}
const exportInfo = () => {
  if (props.customerBizId && editStatus.value) {
    proxy.$modal.confirm(`请先点击编辑在导入客户信息`, { showCancel: '0', title: '填写提示' })
    return
  }
  openList.value = true
  customerList()
}
const customerList = () => {
  console.log('触发了')

  tableLoading.value = true
  getCustomerList(queryParams.value).then(res => {
    if (res.code == 200) {
      tableData.value = res.data.records
      total.value = res.data.total
      tableLoading.value = false
    }
  })
}
const resetCustomerList = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
  customerList()
}
// 从客户列表中导入客户信息到当前表单
const handleExport = row => {
  oldObjInfo.value = JSON.parse(JSON.stringify(form.value)) // 修改时存储原始数据，便于撤销操作
  processFormData({
    domdata: processedinsuredData.value,
    customerInfo: row,
    exportValue: true
  })
  openList.value = false
}

// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}
const mergeObjects = (obj1, obj2) => {
  const result = Object.assign({}, obj1)

  Object.keys(obj2).forEach(key => {
    if (result[key] === undefined || !result.hasOwnProperty(key)) {
      result[key] = obj2[key]
    }
  })

  return result
}
// 处理表单配置，添加字典数据
/**
 * domdata:表单的dom数据
 * customerInfo:根据客户信息回显表单
 * exportValue:是否从导入联系人列表中导入客户信息到当前表单
 */
const processFormData = async obj => {
  let tempPhoneList = []
  let tempAddressList = []
  form.value = {}
  saveKey.value = {}
  addressQuickList.value = []
  phoneQuickList.value = []
  // if (!obj.exportValue) {
  //   form.value = {}
  //   saveKey.value = {}
  //   addressQuickList.value = []
  //   phoneQuickList.value = []
  // }

  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(obj.domdata))

  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (section.key == 'customer') {
          personalObj.value[field.key] = field.key
          companyObj.value[field.key] = field.key
        }
        // 收集key,区分个人和企业
        if (section.key == 'person' && !field.commonKey) {
          personalObj.value[field.key] = field.key
        } else if (section.key == 'company' && !field.commonKey) {
          companyObj.value[field.key] = field.key
        } else if (field.commonKey) {
          commonObj.value[field.key] = field.key
        }
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
        if (obj.customerInfo) {
          for (const key1 in obj.customerInfo) {
            if (key1 == 'birthdate' && obj.customerInfo[key1]) {
              obj.customerInfo[key1] = proxy.formatToDateTime(obj.customerInfo[key1])
            }
            // 客户类型为公司时，隐藏非公司信息
            if (key1 == 'customerType' && obj.customerInfo[key1] == 'COMPANY') {
              showContacts.value = false
              if (section.key == 'company') {
                section.showMoudle = true
              } else if (section.key !== 'customer') {
                section.showMoudle = false
              }
            } else if (key1 == 'customerType' && obj.customerInfo[key1] !== 'COMPANY') {
              showContacts.value = true
              if (section.key == 'company') {
                section.showMoudle = false
              } else {
                section.showMoudle = true
              }
            }
            // 非公司信息时，给表单赋值客户信息
            if (section.showMoudle && field.customerKey && key1 == field.customerKey) {
              form.value[field.key] = obj.customerInfo[key1]
            }
          }
          if (
            (field.key == 'smokingVolume' && obj.customerInfo['smoke'] == '1') ||
            obj.customerInfo['smokingAllowed'] == '1'
          ) {
            field.show = true
          } else if (field.key == 'smokingVolume') {
            field.show = false
          }

          //要判断drawerType,因为抽屉要回显数据
          if (
            (section.key !== 'company' ||
              (props.idsObj.appointmentBizId && section.key == 'company')) &&
            field.drawerType
          ) {
            switch (field.drawerType) {
              //电话的code暂时没对上
              case 'phone':
                let phoneObj = {}
                for (const key1 in field) {
                  for (const key2 in obj.customerInfo) {
                    //这样写的作用：和dom数据的key和code做对应，方便抽屉回显
                    if (key1 !== 'drawerType' && field[key1] == key2) {
                      if (
                        (key1 == 'customerCode' || field.code == key2) &&
                        obj.customerInfo[key2]
                      ) {
                        phoneObj[field.code] = obj.customerInfo[key2].includes('+')
                          ? obj.customerInfo[key2]
                          : `+${obj.customerInfo[key2]}`
                      }
                      if (
                        (key1 == 'customerKey' || field.key == key2) &&
                        field[key1] == key2 &&
                        obj.customerInfo[key2]
                      ) {
                        phoneObj[field.key] = obj.customerInfo[key2]
                      }
                    }
                  }
                }

                if (phoneObj[field.key]) {
                  phoneObj.phoneString = form.value[field.key] = `${phoneObj[field.code]} ${
                    phoneObj[field.key]
                  }`
                  tempPhoneList.push(phoneObj)
                  phoneObj.objType = field.drawerType
                  phoneObj.key = field.key
                  phoneObj.phoneCode = field.code
                  phoneObj.fatherKey = section.key
                  saveKey.value[field.key] = phoneObj
                }

                break
              case 'address':
                let addressObj = null
                for (const key1 in field) {
                  if (obj.customerInfo.addressList && obj.customerInfo.addressList.length > 0) {
                    obj.customerInfo.addressList.forEach(item => {
                      if (field.customerKey == item.type) {
                        addressObj = item
                      }
                    })
                  }
                }

                if (addressObj) {
                  form.value[
                    field.key
                  ] = `${addressObj.region} ${addressObj.city} ${addressObj.street} ${addressObj.location}`
                  addressObj.addressString = `${addressObj.region} ${addressObj.city} ${addressObj.street} ${addressObj.location}`
                  addressObj.objType = field.drawerType
                  addressObj.fatherKey = section.key
                  saveKey.value[field.key] = addressObj
                  if (tempAddressList.length > 0) {
                    tempAddressList.forEach(item => {
                      if (item.addressString !== addressObj.addressString) {
                        tempAddressList.push(addressObj)
                      }
                    })
                  } else {
                    tempAddressList.push(addressObj)
                  }
                }

                break
              case 'country':
                form.value[field.key] = obj.customerInfo.countryName
                saveKey.value[field.key] = {
                  country: obj.customerInfo.country || '',
                  countryCode: obj.customerInfo.country || '',
                  countryName: obj.customerInfo.countryName || '',
                  name: obj.customerInfo.countryName || '',
                  objType: field.drawerType,
                  fatherKey: section.key
                }
                break
              default:
                break
            }
          }
        }

        //当tab切换走，在切换回来的时候，需要把之前保存的值赋值回来
        if (
          JSON.stringify(tempPolicyForm.value) !== '{}' &&
          !props.idsObj.appointmentBizId &&
          props.pageSource == 'fnaList'
        ) {
          // 客户类型为公司时，隐藏非公司信息
          if (
            tempPolicyForm.value['customerType'] &&
            tempPolicyForm.value['customerType'] == 'COMPANY'
          ) {
            showContacts.value = false
            if (section.key == 'company') {
              section.showMoudle = true
            } else if (section.key !== 'customer') {
              section.showMoudle = false
            }
          } else if (
            tempPolicyForm.value['customerType'] &&
            tempPolicyForm.value['customerType'] !== 'COMPANY'
          ) {
            showContacts.value = true
            if (section.key == 'company') {
              section.showMoudle = false
            } else {
              section.showMoudle = true
            }
          }
        }
        if (props.showSubmitBtn) {
          if (obj.source && obj.source == 'policyholderRel' && field.key !== 'age') {
            field.disabled = false
          } else {
            field.disabled = true
          }
        } else {
          if (field.key == 'age') {
            field.disabled = true
          } else {
            field.disabled = false
          }
        }
      }
    }
  }
  addressQuickList.value = tempAddressList
  tempPhoneList.forEach(item => {
    for (const key in saveKey.value) {
      if (item.key == key) {
        for (const key2 in saveKey.value[key]) {
          if (item.key == key2) {
            item.mobile = saveKey.value[key][key2]
          }
          if (item.phoneCode == key2) {
            item.code = saveKey.value[key][key2]
          }
        }
      }
    }
  })
  phoneQuickList.value = removeDuplicates(tempPhoneList, 'phoneString')
  addressQuickList.value = removeDuplicates(tempAddressList, 'addressString')

  //当tab切换走，在切换回来的时候，新增情况下需要把之前保存的值赋值回来
  if (
    JSON.stringify(tempPolicyForm.value) !== '{}' &&
    !props.idsObj.appointmentBizId &&
    props.pageSource == 'fnaList'
  ) {
    form.value = { ...tempPolicyForm.value }
    saveKey.value = { ...tempSaveKey.value }
    addressQuickList.value = JSON.parse(JSON.stringify(tempAddressQuickList.value))
    phoneQuickList.value = JSON.parse(JSON.stringify(tempPhoneQuickList.value))
  }
  // props.idsObj.appointmentBizId
  if (props.showSubmitBtn) {
    form.value = mergeObjects(form.value, obj.customerInfo)
    if (form.value.smokingAllowed) {
      form.value.smokingAllowed = Number(form.value.smokingAllowed)
    }
    editStatus.value = true
  } else {
    editStatus.value = false
  }
  // // 投保人为本人时，信息从投保人带入
  // if (obj.source && obj.source == 'policyholderRel') {
  //   form.value = {
  //     ...obj.customerInfo,
  //     policyholderRel: form.value.policyholderRel
  //   }
  //   if (form.value.smokingAllowed) {
  //     form.value.smokingAllowed = Number(form.value.smokingAllowed)
  //   }
  // }
  if (form.value['birthday']) {
    let age = calculateExactAge(proxy.formatToDate(form.value.birthday))
    if (age >= 0) {
      form.value.age = age
    }
  } else {
    form.value.age = null
  }
  processedinsuredData.value = oldAppointmentData.value = processedData
}

//弹出右侧抽屉
const handleFoucs = child => {
  if (child.disabled) return

  drawerInfo.value = JSON.parse(JSON.stringify(child))
  switch (child.drawerType) {
    case 'phone':
      phoneMenuList.value[0].key = child.code
      phoneMenuList.value[1].key = child.key
      phoneMenuList.value.forEach(item => {
        item.value = ''
        for (const key in saveKey.value) {
          if (key == child.key) {
            for (const key2 in saveKey.value[key]) {
              if (item.key == key2) {
                item.value = saveKey.value[key][key2]
              }
            }
          }
        }
      })

      showPhoneDrawer.value = true
      break
    case 'address':
      addressMenuList.value.forEach(item => {
        item.value = ''
        for (const key in saveKey.value) {
          if (key == child.key) {
            for (const key2 in saveKey.value[key]) {
              if (item.key == key2) {
                item.value = saveKey.value[key][key2]
              }
            }
          }
        }
      })
      showAddressDrawer.value = true
      break
    case 'country':
      showCountryDrawer.value = true
      break
    default:
      break
  }
}
// 处理抽屉关闭
const handleCloseDrawer = () => {
  showPhoneDrawer.value = false
  showAddressDrawer.value = false
  showCountryDrawer.value = false
  drawerInfo.value = {}
}
const confirmDrawer = info => {
  // info 为抽屉返回的值
  if (drawerInfo.value.domType == 'arrowRight' && drawerInfo.value.drawerType) {
    let newObj = info[drawerInfo.value.key]

    //要判断drawerType
    switch (drawerInfo.value.drawerType) {
      case 'phone':
        newObj.objType = drawerInfo.value.drawerType
        newObj.key = drawerInfo.value.key
        // 因为电话有多个，根据点击的电话类型在抽屉里回显，所以要用drawerInfo.value.code来控制
        form.value[info.key] = newObj.phoneString = `${newObj[drawerInfo.value.code]} ${
          newObj[drawerInfo.value.key]
        }`
        saveKey.value[drawerInfo.value.key] = newObj
        // 检查数组中是否已存在key的电话
        const existingIndex = phoneQuickList.value.findIndex(item => item.key === newObj.key)

        if (existingIndex !== -1) {
          // 更新已存在的电话
          phoneQuickList.value[existingIndex] = {
            code: newObj[drawerInfo.value.code],
            mobile: newObj[drawerInfo.value.key],
            key: drawerInfo.value.key,
            phoneString: newObj.phoneString
          }
        } else {
          // 添加新的快捷电话
          phoneQuickList.value.push({
            code: newObj[drawerInfo.value.code],
            mobile: newObj[drawerInfo.value.key],
            key: drawerInfo.value.key,
            phoneString: newObj.phoneString
          })
        }
        phoneQuickList.value = removeDuplicates(phoneQuickList.value, 'phoneString')
        break
      case 'address':
        newObj.objType = drawerInfo.value.drawerType
        newObj.type = drawerInfo.value.key

        form.value[info.key] = `${newObj.region} ${newObj.city} ${newObj.street} ${newObj.location}`
        saveKey.value[info.key] = newObj
        newObj.addressString = `${newObj.region} ${newObj.city} ${newObj.street} ${newObj.location}`
        // 检查数组中是否已存在key的地址
        // debugger

        const existinAddressIndex = addressQuickList.value.findIndex(
          item => item.type === newObj.type
        )

        if (existinAddressIndex !== -1) {
          // 更新已存在的电话
          addressQuickList.value[existinAddressIndex] = {
            ...newObj
          }
        } else {
          // 添加新的快捷电话
          addressQuickList.value.push(newObj)
        }
        addressQuickList.value = removeDuplicates(addressQuickList.value, 'addressString')
        console.log('填写地址', addressQuickList.value)
        break
      case 'country':
        info.objType = drawerInfo.value.drawerType
        form.value[drawerInfo.value.key] = info.name
        saveKey.value[drawerInfo.value.key] = info
        break
      default:
        break
    }
    // 手动触发表单验证
    nextTick(() => {
      // 根据不同的drawerType确定要验证的字段key
      const validateField = drawerInfo.value.key
      insuredInfoFormRef.value.clearValidate(validateField)
    })
  }

  handleCloseDrawer()
}
// 根据联动重置表单项的显示与否
const resetShow = obj => {
  for (const section of processedinsuredData.value) {
    switch (obj.type) {
      case 'father':
        if (section.key == obj.key) {
          section.showMoudle = obj.status
        }

        break
      case 'child':
        if (section.data) {
          for (const field of section.data) {
            if (field.key == obj.key) {
              // 获取字典数据
              field.show = obj.status
            }
          }
        }
        break

      default:
        break
    }
  }
}
const handleSelectChange = (father, child) => {
  switch (child.key) {
    case 'customerType':
      if (form.value[child.key] == 'COMPANY') {
        showContacts.value = false
        for (const section of processedinsuredData.value) {
          if (section.key == 'company') {
            for (const key1 in saveKey.value) {
              for (const key2 in commonObj.value) {
                if (key1 == key2) {
                  saveKey.value[key1]['fatherKey'] = section.key
                }
              }
            }
            section.showMoudle = true
          } else if (section.key !== 'customer') {
            section.showMoudle = false
          }
        }
      } else {
        showContacts.value = true
        for (const section of processedinsuredData.value) {
          if (section.key == 'company') {
            section.showMoudle = false
          } else {
            section.showMoudle = true
          }
        }
      }

      break
    case 'smokingAllowed':
      // 选择吸烟，展示吸烟数量
      if (form.value[child.key] == '1') {
        resetShow({ type: 'child', key: 'smokingVolume', status: true })
      } else {
        resetShow({ type: 'child', key: 'smokingVolume', status: false })
      }

      break
    case 'isVip':
      // 选择vip,展示vip备注
      if (form.value[child.key] == '1') {
        resetShow({ type: 'child', key: 'vipRemark', status: true })
      } else {
        resetShow({ type: 'child', key: 'vipRemark', status: false })
      }

      break
    case 'policyholderRel':
      //选择投保人为本人得时候，带入投保人得信息
      if (form.value['policyholderRel'] == 'MYSELF') {
        form.value = JSON.parse(JSON.stringify(props.currentPolicyholderInfo.form))
        saveKey.value = JSON.parse(JSON.stringify(props.currentPolicyholderInfo.saveKey))
        form.value['policyholderRel'] = 'MYSELF'
        if (form.value['customerType'] == 'COMPANY') {
          resetShow({ type: 'father', key: 'person', status: false })
          resetShow({ type: 'father', key: 'company', status: true })
        } else if (form.value['customerType'] == 'INDIVIDUAL') {
          resetShow({ type: 'father', key: 'person', status: true })
          resetShow({ type: 'father', key: 'company', status: false })
        }
        // 选择吸烟，展示吸烟数量
        if (form.value['smokingAllowed'] == '1') {
          resetShow({ type: 'child', key: 'smokingVolume', status: true })
        } else {
          resetShow({ type: 'child', key: 'smokingVolume', status: false })
        }
        if (form.value['isVip'] == '1') {
          resetShow({ type: 'child', key: 'vipRemark', status: true })
        } else {
          resetShow({ type: 'child', key: 'vipRemark', status: false })
        }
      }
      break

    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = status => {
  editStatus.value = status
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedinsuredData.value))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (editStatus.value) {
          field.disabled = true
        } else {
          if (field.key == 'age') {
            field.disabled = true
          } else {
            field.disabled = false
          }
        }
      }
    }
  }
  processedinsuredData.value = processedData
}
// 数组去重
function removeDuplicates(arr, key) {
  const seen = new Map()
  const result = []

  for (const item of arr) {
    if (item[key] && !seen.has(item[key])) {
      seen.set(item[key], true)
      result.push(item)
    }
  }

  return result
}
// 获取校验失败的字段信息
const getInvalidFields = fields => {
  const errors = []
  for (const field in fields) {
    if (fields[field] && fields[field].length > 0) {
      errors.push({
        field: field,
        message: `签约信息模块-${fields[field][0].message}`
      })
    }
  }
  return errors
}

// 处理表单填写得数据
const handleFormValues = () => {
  let submitObj = {}
  let addressList = []
  let result = {}
  if (props.activeName == 'insurantInfo') {
    result = JSON.parse(JSON.stringify(form.value))
  } else {
    result = JSON.parse(JSON.stringify(tempPolicyForm.value))
    saveKey.value = JSON.parse(JSON.stringify(tempSaveKey.value))
  }
  let newSaveKey = {}
  if (result.birthday) {
    result.birthday = proxy.formatToDateTime(result.birthday)
  }
  if (result.companyRegisterTime) {
    result.companyRegisterTime = proxy.formatToDateTime(result.companyRegisterTime)
  }
  //处理表单数据
  for (const key1 in result) {
    // if (key1 == 'birthday' || key1 == 'companyRegisterTime') {
    //   result[key1] = proxy.formatToDateTime(result[key1])
    // }
    // 根据选择的客户类型传值，公司和个人分开传值，因为电话和地址特殊所以也要处理
    if (key1 == 'customerType' && result[key1] == 'COMPANY') {
      for (const key4 in companyObj.value) {
        submitObj[key4] = result[key4]
        for (const key7 in saveKey.value) {
          if (key4 == key7) {
            newSaveKey[key4] = saveKey.value[key4]
          }
        }
      }
    } else if (key1 == 'customerType' && (!result[key1] || result[key1] == 'INDIVIDUAL')) {
      for (const key5 in personalObj.value) {
        submitObj[key5] = result[key5]
        for (const key7 in saveKey.value) {
          if (key5 == key7) {
            newSaveKey[key5] = saveKey.value[key5]
          }
        }
      }
    }
    for (const key6 in commonObj.value) {
      submitObj[key6] = result[key6]
      for (const key7 in saveKey.value) {
        if (key6 == key7) {
          newSaveKey[key6] = saveKey.value[key6]
        }
      }
    }
    for (const key2 in newSaveKey) {
      //要判断drawerType
      switch (newSaveKey[key2].objType) {
        // case 'phone':
        //   if (key1 == key2) {
        //     for (const key3 in newSaveKey[key2]) {
        //       if (key3 == 'phoneCode') {
        //         submitObj[newSaveKey[key2][key3]] = newSaveKey[key2].phoneString.split(' ')[0]
        //       }
        //       if (key3 == 'phoneString') {
        //         submitObj[newSaveKey[key2].key] = newSaveKey[key2][key3].split(' ')[1]
        //       }
        //     }
        //   }

        //   break
        case 'address':
          if (key1 == key2) {
            addressList.push(newSaveKey[key2])
          }
          break
        case 'country':
          if (key1 == key2 && key1 == 'customerType' && result[key1] == 'INDIVIDUAL') {
            submitObj['country'] = newSaveKey[key2]['countryCode']
            submitObj['countryName'] = newSaveKey[key2]['name']
          }
          break
        default:
          break
      }
    }
  }
  if (addressList.length > 0) {
    submitObj['addressList'] = addressList
  }
  if (submitObj['companyMobile']) {
    submitObj['companyMobileCode'] = submitObj['companyMobile'].split(' ')[0]
    submitObj['companyMobile'] = submitObj['companyMobile'].split(' ')[1]
  }
  if (submitObj['mobile']) {
    submitObj['mobileCode'] = submitObj['mobile'].split(' ')[0]
    submitObj['mobile'] = submitObj['mobile'].split(' ')[1]
  }
  if (submitObj['authMobile']) {
    submitObj['authMobileCode'] = submitObj['authMobile'].split(' ')[0]
    submitObj['authMobile'] = submitObj['authMobile'].split(' ')[1]
  }

  // 删除多余字段
  deleteKeyList.value.forEach(item => {
    delete submitObj[item]
  })

  console.log('====================================')
  console.log('受保人submitObj', submitObj)
  console.log('====================================')
  return submitObj
}
// 表单提交
const submitForm = () => {
  proxy.$refs['insuredInfoFormRef'].validate((valid, fields) => {
    if (valid) {
      let submitObj = handleFormValues()
      if (
        props.idsObj.appointmentBizId &&
        (props.pageSource == 'fnaList' || props.pageSource == 'appointmentList')
      ) {
        submitObj['appointmentBizId'] = props.apiInsurantInfoDto.appointmentBizId
        submitObj['id'] = props.apiInsurantInfoDto.id
        submitObj['insurantBizId'] = props.apiInsurantInfoDto.insurantBizId
        editInsurantInfo(submitObj).then(res => {
          if (res.code == 200) {
            handleEditStatus(true)
            proxy.$message.success('受保人修改成功')
            emit('handleSuccessEdit')
          }
        })
      }
      if (props.idsObj.policyBizId && props.pageSource == 'policyList') {
        submitObj['policyInsurantBizId'] = props.apiInsurantInfoDto.policyInsurantBizId
        submitObj['policyBizId'] = props.apiInsurantInfoDto.policyBizId
        submitObj['id'] = props.apiInsurantInfoDto.id
        updatePolicyInsurant(submitObj).then(res => {
          if (res.code == 200) {
            handleEditStatus(true)
            proxy.$message.success('新单跟进-受保人修改成功')
            emit('policyEditSuccess')
          }
        })
      }
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}

watch(
  () => props.activeName,
  newVal => {
    // 切换tab的时侯把表单值保存在临时变量里，方便切换回来的时候回显
    tempPolicyForm.value = { ...form.value }
    tempSaveKey.value = { ...saveKey.value }
    tempAddressQuickList.value = JSON.parse(JSON.stringify(addressQuickList.value))
    tempPhoneQuickList.value = JSON.parse(JSON.stringify(phoneQuickList.value))
    if (newVal === 'insurantInfo') {
      openList.value = false
      setTimeout(() => {
        if (props.showSubmitBtn) {
          processFormData({
            domdata: policyDomData,
            customerInfo: props.apiInsurantInfoDto,
            exportValue: null
          })
        } else {
          processFormData({
            domdata: policyDomData,
            exportValue: null
          })
        }
      }, 500)
      console.log('====================================')
      console.log('受保人拿到投保人信息', props.currentPolicyholderInfo)
      console.log('====================================')
    }
  }
)

// 暴露给父组件
defineExpose({
  handleFormValues,
  handleEditStatus
})
</script>
<style lang="scss" scoped>
.domEmpty {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #a8abb2;
  margin-top: 100px;
}
.topBtn {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .inputBox {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 0px 11px;
    .rightArrow {
      font-size: 14px;
      color: #a8abb2;
    }
  }
  .desBox {
    display: flex;
    justify-content: flex-start;
    .title {
      width: 120px;
      font-size: 14px;
      text-align: right;
    }
    .informationBox {
      margin-left: 5px;
      font-size: 14px;
      border: 1px solid #dcdfe6;
      width: 100%;
      border-radius: 4px;
      padding: 2px 4px;
      box-sizing: border-box;
    }
  }
}
.tabButton {
  box-shadow: 0 -1px 14px #00000014;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding-right: 20px; */
  padding-top: 20px;
  .sumbitBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    height: 60px;
    background-color: #165dff;
    color: #fff;
    padding: 0 30px;
    .buttonIcon {
      font-size: 16px;
      color: #fff;
    }
  }
}
.customerBox {
  .customerItem {
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 20px;
    box-shadow: 0 -1px 14px #00000014;
    .top {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .left {
        /* display: flex;
        align-items: center; */
        .infoItem {
          display: flex;
          align-items: center;
          margin: 5px 10px;
        }
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
</style>
