<template>
  <div class="customerContainer" style="padding-top: 10px">
    <div ref="customerRightRef">
      <div class="editBtn">
        <el-button
          v-if="props.customerBizId && tabSource == 'customer'"
          type="primary"
          icon="EditPen"
          @click="handleEditStatus"
          >编辑</el-button
        >
      </div>
      <CommonForm
        :anchorList="anchorList"
        :affixOffset="affixOffset"
        :anchorOffset="10"
        :scrollContainerSelector="anchorContainer"
        :scrollOffset="10"
        :domIndex="tabIndex"
        :activeName="activeName"
        v-if="customerRightRef"
      >
        <template #form-right>
          <el-form :model="form" :rules="rules" label-width="120px" ref="customerFormRef">
            <el-row v-for="(father, fIndex) in processedCustomerData" :id="father.anchorKey">
              <div class="formBox">
                <CardOne
                  :showTitle="father.showTitle"
                  :title="father.fatherTitle"
                  v-if="father.showMoudle"
                >
                  <template #content>
                    <el-row :gutter="20" v-if="!father.showTable">
                      <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>
                            <el-form-item
                              :label="
                                child.key === 'residentialAddress' && child.domType === 'arrowRight'
                                  ? ''
                                  : child.label
                              "
                              :prop="child.key"
                              :key="child.key"
                              :label-width="child.labelWidth"
                              :label-position="child.labelPosition"
                            >
                              <!-- 自定义 label 插槽 -->
                              <template
                                v-if="
                                  child.key === 'residentialAddress' &&
                                  child.domType === 'arrowRight'
                                "
                                #label
                              >
                                <div class="custom-label">
                                  <span>{{ child.label }}</span>
                                  <el-checkbox-group
                                    v-model="form.isCopyAddress"
                                    size="small"
                                    style="margin-left: 8px"
                                    @change="changeAddressStatus(child)"
                                    :disabled="copyAddress"
                                  >
                                    <el-checkbox :value="true" name="isCopyAddress">
                                      同通讯地址
                                    </el-checkbox>
                                  </el-checkbox-group>
                                </div>
                              </template>
                              <el-input
                                v-if="child.domType === 'Input'"
                                :type="child.inputType"
                                v-model="form[child.key]"
                                :placeholder="child.placeholder"
                                maxlength="30"
                                :disabled="
                                  child.key == 'age' ||
                                  child.key == 'bmi' ||
                                  child.key == 'dependentsNum'
                                    ? true
                                    : editStatus
                                "
                                @blur="handleInputBlur(child)"
                              >
                                <template #append v-if="child.unit">
                                  <span
                                    @click="handleAppendInput(child)"
                                    :style="{ color: child.unitColor }"
                                    >{{ child.unit }}</span
                                  >
                                </template>
                              </el-input>
                              <el-select
                                v-if="child.domType === 'Select'"
                                v-model="form[child.key]"
                                :placeholder="child.placeholder"
                                :data-key="child.key"
                                @change="handleSelectChange(child)"
                                :disabled="editStatus"
                                clearable
                              >
                                <el-option
                                  v-for="item in child.options"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </el-select>
                              <el-date-picker
                                style="width: 100%"
                                v-if="child.domType === 'DatePicker'"
                                v-model="form[child.key]"
                                type="date"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                :placeholder="child.placeholder"
                                :disabled="editStatus"
                                :disabled-date="time => disabledDate(time, child)"
                                :default-value="defaultDisplayDate"
                                @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="editStatus"
                              >
                              </el-input>
                            </el-form-item>
                          </div>
                        </el-col>
                      </template>
                    </el-row>
                    <el-row v-if="father.showTable">
                      <el-col :span="24" v-if="father.addChildren">
                        <el-button
                          :disabled="editStatus"
                          type="primary"
                          icon="Plus"
                          size="small"
                          style="margin-bottom: 10px"
                          @click="addChildren(father)"
                          >{{ father.addChildrenTxt }}</el-button
                        >
                      </el-col>
                      <el-table :data="father.data" border v-if="father.data.length > 0">
                        <template v-if="father.key == 'apiTaxationDtoList'">
                          <el-table-column label="税务国家" prop="taxCountry" align="center">
                            <template #default="scope">
                              <el-input
                                size="default"
                                placeholder="请输入"
                                v-model="scope.row.taxCountry"
                                :disabled="editStatus"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="税务编号" prop="taxId" align="center">
                            <template #default="scope">
                              <el-input
                                v-model="scope.row.taxId"
                                size="default"
                                placeholder="请输入"
                                :disabled="editStatus"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column width="60px" align="center" label="操作">
                            <template #default="scope">
                              <el-icon
                                class="deleteIcon"
                                @click="deleteChildren(father, scope.$index)"
                                ><Delete
                              /></el-icon>
                            </template>
                          </el-table-column>
                        </template>
                      </el-table>
                    </el-row>
                  </template>
                </CardOne>
              </div>
            </el-row>
            <el-row v-if="tabSource == 'customer'">
              <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="handleFormValues"
                    size="large"
                    :disabled="editStatus"
                    >提交</el-button
                  >
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </CommonForm>
    </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"
    />
    <!-- 历史客户的弹窗 -->

    <CommonDialog
      dialogTitle="历史客户"
      :showConfirm="false"
      cancleText="关闭"
      dialogWidth="70%"
      :openDialog="openList"
      @close="openList = false"
    >
      <div class="dialogBox">
        <CommonPage
          :operationBtnList="operationBtnList"
          :visibleDefaultButtons="visibleDefaultButtons"
          :showSearchForm="true"
          :show-pagination="true"
          :currentPage="queryParams.pageNo"
          :total="total"
          :pageSize="queryParams.pageSize"
          @current-change="changePageNo"
          @size-change="changePageSize"
        >
          <!-- 查询条件插槽 -->
          <template #searchForm>
            <el-form :model="queryParams" ref="queryRef" label-width="100px" label-position="top">
              <el-row :gutter="30">
                <el-col :sm="12" :lg="8" :xs="24">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :sm="12" :lg="8" :xs="24">
                  <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>

          <!-- 表格插槽 -->
          <template #table>
            <el-table v-loading="tableLoading" :data="tableData" @row-click="handleExport">
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column label="姓名" align="center" prop="nameCn" width="200" />
              <el-table-column label="性别" align="center" prop="gender">
                <template #default="scope">
                  <dict-tag :options="fetchDictData('sys_gender')" :value="scope.row.gender" />
                </template>
              </el-table-column>
              <el-table-column label="证件类型" align="center" prop="documentType">
                <template #default="scope">
                  <dict-tag
                    :options="fetchDictData('csf_id_type')"
                    :value="scope.row.documentType"
                  />
                </template>
              </el-table-column>

              <el-table-column label="证件号码" align="center" prop="idNumber" />
              <el-table-column label="电话号码" align="center" prop="mobile" />
              <el-table-column label="出生日期" align="center" width="180" prop="birthday">
                <template #default="scope">
                  <span>{{ scope.row.birthday ? formatToDate(scope.row.birthday) : '--' }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="150"
                class-name="small-padding fixed-width"
                fixed="right"
              >
                <template #default="scope">
                  <el-button link type="primary" @click="handleExport(scope.row)"
                    >使用客户资料</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </CommonPage>
      </div>
    </CommonDialog>
  </div>
</template>
<script setup name="customer">
import { validateEnglish, validateBMI, validateIdCard, validateChinese } from '@/utils/validate'
import { calculateExactAge } from '@/utils/date'
import dayjs from 'dayjs'
import { ArrowRight } from '@element-plus/icons-vue'
import customerDomData from '@/formJson/customer'
import Country from '@/views/components/country'
import Phone from '@/views/components/phone'
import Address from '@/views/components/address'
import CommonForm from '@/views/components/commonForm'
import CommonDialog from '@/components/commonDialog'
import CommonPage from '@/components/commonPage'
import CardOne from '@/components/formCard/cardOne'
import { watch } from 'vue'
import {
  addCustomer,
  getCustomerDetail,
  editCustomer,
  getCustomerList,
  addFna,
  calculateFieldValue
} from '@/api/sign/fna'
import useDictStore from '@/store/modules/dict'
const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  fatherEditStatus: { type: Boolean, default: false }, //因为嵌套了双层tab,所以需要父组件传值控制子组件的编辑状态
  anchorContainer: { type: String, default: '' }, //锚点滚动容器
  tabIndex: { type: [String, Number], default: '' }, //tab索引
  affixOffset: { type: Number, default: 250 }, //锚点吸顶距离
  customerBizId: { type: String, default: '' }, //提交状态，新增、修改
  tabSource: { type: String, default: '' },
  idsObj: { type: Object, default: () => ({}) }, //引用这个组件的页面来源，用于逻辑判断
  apiPolicyholderInfoDto: { type: Object, default: () => ({}) }, //投保人编辑状态详情
  apiInsurantInfoDto: { type: Object, default: () => ({}) } //受保人编辑状态详情
})
const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
const customerRightRef = ref(null)
const showPhoneDrawer = ref(false) //电话抽屉开关
const showAddressDrawer = ref(false) //地址抽屉开关
const showCountryDrawer = ref(false) //国家/地区抽屉开关
const drawerInfo = ref({}) // 用于存储所有arrowRight类型的输入框输入值
const saveKey = ref({}) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作

const tableLoading = ref(false)
const tableData = ref([])
const total = ref(0)
//计算默认显示的日期（18年前的今天）
const defaultDisplayDate = ref(dayjs().subtract(19, 'year').toDate())

// 地址组件菜单数据
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 deleteKeyList = ref([
  'objType',
  'mailingAddress',
  'residentialAddress',
  'mailingAddress',
  'companyAddress'
]) // 存储需要删除的key
const data = reactive({
  form: { isCopyAddress: [] },
  processedCustomerData: [], // 处理后的表单数据
  oldCustomerData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    name: undefined
  }
})
const { form, rules, processedCustomerData, queryParams, oldCustomerData } = toRefs(data)
// 控制要显示的默认按钮
const visibleDefaultButtons = ref(['query', 'reset']) // 只显示新增和查询两个默认按钮
// 按钮配置
const operationBtnList = ref([
  {
    key: 'reset',
    size: 'small',
    direction: 'right',
    click: resetQuery
  },
  {
    key: 'query',
    size: 'small',
    direction: 'right',
    click: handleQuery
  }
])
const customerFormRef = ref(null)

const changePageNo = val => {
  queryParams.value.pageNo = val
  customerList()
}
const changePageSize = val => {
  queryParams.value.pageSize = val
  customerList()
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1
  customerList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value = {
    pageNo: 1,
    pageSize: 10
  }
  handleQuery()
}
const handleAppendInput = child => {
  if (child.key == 'nameCn') {
    if (editStatus.value) {
      proxy.$modal.confirm(`请先点击编辑在导入客户信息`, { showCancel: '0', title: '填写提示' })
      return
    }
    openList.value = true
    queryParams.value = {
      pageNo: 1,
      pageSize: 10
    }
    customerList()
  }
}
const handleInputBlur = child => {
  if (form.value['documentType'] == 'idCard' && child.key == 'idNumber') {
    getFieldValue(child.key)
  } else if (
    (child.key == 'weight' || child.key == 'height') &&
    form.value['weight'] &&
    form.value['height']
  ) {
    getFieldValue(child.key)
  } else if (child.key == 'nameCn' && form.value['nameCn']) {
    getFieldValue(child.key)
  }
}
const getFieldValue = key => {
  let obj = {}
  if (form.value['documentType'] == 'idCard' && key == 'idNumber') {
    obj = {
      calculateType: 6,
      requestValue: form.value['idNumber']
    }
  } else if (key == 'weight' || key == 'height') {
    obj = {
      calculateType: 5,
      requestValueList: [form.value['height'], form.value['weight']]
    }
  } else if (key == 'nameCn') {
    obj = {
      calculateType: 1,
      requestValue: form.value['nameCn']
    }
  }
  calculateFieldValue(obj).then(res => {
    if (res.code == 200) {
      res.data.forEach(item => {
        if (obj.calculateType == 6) {
          if (item.calculateType == 2) {
            form.value['gender'] = item.responseKey
          } else if (item.calculateType == 3) {
            form.value['birthday'] = item.requestValue
          } else if (item.calculateType == 4) {
            form.value['age'] = item.requestValue
          }
        } else if (obj.calculateType == 5) {
          form.value['bmi'] = item.responseValue
        } else if (obj.calculateType == 1) {
          form.value['namePyEn'] = item.responseValue
        }
      })
    }
  })
}
// 添加表单子级dom
const addChildren = father => {
  const processedData = JSON.parse(JSON.stringify(processedCustomerData.value))

  let obj4 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    taxCountry: '',
    taxId: ''
  }

  for (const section of processedData) {
    if (father.key == 'apiTaxationDtoList' && section.key == father.key) {
      section.data.push(obj4)
    }
  }
  processedCustomerData.value = processedData
  console.log('processedCustomerData.value', processedCustomerData.value)
}
const deleteChildren = (father, childIndex) => {
  if (editStatus.value) {
    proxy.$modal.confirm(`请先点击编辑再进行删除操作`, { showCancel: '0', title: '填写提示' })
    return
  }
  const processedData = JSON.parse(JSON.stringify(processedCustomerData.value))
  for (const section of processedData) {
    if (father.key == 'apiTaxationDtoList' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
  }
  processedCustomerData.value = processedData
}
const copyAddress = computed(() => {
  const mailingAddressIndex = addressQuickList.value.findIndex(
    item => item.type === 'mailingAddress'
  )
  if (mailingAddressIndex !== -1) {
    return false
  } else {
    return true
  }
})
const changeAddressStatus = child => {
  // 复用地址
  if (form.value.isCopyAddress.length > 0 && form.value.isCopyAddress[0]) {
    if (child.key == 'residentialAddress') {
      form.value[child.key] = form.value['mailingAddress']
      // 这里是直接复用地址了，但是地址组件的值是双向绑定的，所以这里需要手动更新地址组件的值
      addressQuickList.value.forEach(item => {
        if (item.type == 'mailingAddress') {
          saveKey.value[child.key] = { ...item, type: child.key }
        }
      })
    }
  }
  console.log('saveKey.value', saveKey.value)
}

const handleDateChange = child => {
  let age = null
  if (child.key == 'birthday') {
    age = calculateExactAge(proxy.formatToDate(form.value.birthday))
    if (age >= 18) {
      form.value.age = age
    }
  }
}
const disabledDate = (time, child) => {
  if (child.key == 'birthday') {
    // 计算18年前的今天
    const eighteenYearsAgo = dayjs().subtract(19, '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
  }
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    name: undefined
  }
  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 handleExport = row => {
  oldCustomerData.value = JSON.parse(JSON.stringify(processedCustomerData.value)) // 修改时存储原始数据，便于撤销操作
  oldObjInfo.value = JSON.parse(JSON.stringify(form.value)) // 修改时存储原始数据，便于撤销操作

  setFormValue(row, processedCustomerData.value, true)
  openList.value = false
}

// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == 'sys_no_yes') {
        item.dictItemList.forEach(item2 => {
          item2.value = String(item2.itemValue)
        })
      }
      if (item.dictType == dictType) {
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}
// 处理表单配置，添加字典数据
const processFormData = async () => {
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(customerDomData))
  rules.value = {}
  for (const section of processedData) {
    if (props.activeName == 'insurantInfo' && section.key == 'policyholderRel') {
      section.showMoudle = true
    } else if (props.activeName !== 'insurantInfo' && section.key == 'policyholderRel') {
      section.showMoudle = false
    }

    if (section.data) {
      for (const field of section.data) {
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
        if (field.required) {
          if (field.key === 'namePyEn') {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' },
              { validator: validateEnglish, trigger: 'change' }
            ]
          } else if (field.key === 'nameCn') {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' },
              { validator: validateChinese, trigger: 'blur' }
            ]
          } else {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
            ]
          }
        }
      }
    }
  }
  // 为私有的加form验证
  if (props.activeName == 'insurantInfo') {
    rules.value['policyholderRel'] = [
      { required: true, message: `与投保人关系不能为空`, trigger: 'blur' }
    ]
  }
  if (props.customerBizId && props.tabSource == 'customer') {
    // 在客户资料中是编辑客户资料，需要回显客户资料
    getCustomerInfo(props.customerBizId, processedData)
  } else if (
    props.customerBizId &&
    (props.tabSource == 'policyholder' || props.tabSource == 'insurantInfo') &&
    !props.idsObj.appointmentBizId
  ) {
    //是投保人/受保人但是新增预约 需要引用客户资料的值
    getCustomerInfo(props.customerBizId, processedData)
  } else if (props.tabSource == 'policyholder' && props.idsObj.appointmentBizId) {
    // 投保人回显值
    setFormValue(props.apiPolicyholderInfoDto, processedData)
  } else if (props.tabSource == 'insurantInfo' && props.idsObj.appointmentBizId) {
    // 投保人回显值
    setFormValue(props.apiInsurantInfoDto, processedData)
  } else {
    processedCustomerData.value = oldCustomerData.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 => {
  // console.log('抽屉info', info)

  // info 为抽屉返回的值
  if (drawerInfo.value.domType == 'arrowRight' && drawerInfo.value.drawerType) {
    console.log('drawerInfo.value', drawerInfo.value)

    let newObj = info[drawerInfo.value.key]
    //要判断drawerType
    switch (drawerInfo.value.drawerType) {
      case 'phone':
        newObj.objType = drawerInfo.value.drawerType
        // 因为电话有多个，根据点击的电话类型在抽屉里回显，所以要用drawerInfo.value.code来控制
        form.value[info.key] = newObj.phoneString = `${newObj[drawerInfo.value.code]} ${
          newObj[drawerInfo.value.key]
        }`
        newObj.key = drawerInfo.value.key
        saveKey.value[drawerInfo.value.key] = newObj
        // debugger
        // 检查数组中是否已存在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
        console.log('newObj', 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('填写地址', copyAddress.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
    }
    console.log('form.value', form.value)
    console.log(' saveKey.value', saveKey.value)

    // 手动触发表单验证
    nextTick(() => {
      // 根据不同的drawerType确定要验证的字段key
      const validateField = drawerInfo.value.key
      customerFormRef.value.clearValidate(validateField)
    })
  }

  handleCloseDrawer()
}

const handleSelectChange = child => {
  switch (child.key) {
    case 'documentType':
      break
    case 'isRetirement':
      if (form.value[child.key] == '1') {
        resetShow('retirementAge', true)
      } else {
        resetShow('retirementAge', false)
      }
      break
    case 'policyholderRel':
      // 强制同步：确保form.value.policyholderRel与当前选择的值一致

      processedCustomerData.value.forEach(section => {
        if (form.value[child.key] == 'MYSELF') {
          if (section.key == 'policyholderRel') {
            section.showMoudle = true
          } else {
            section.showMoudle = false
          }
        } else {
          section.showMoudle = true
        }
      })
      console.log('下拉', form.value)

      break
    default:
      break
  }
}

// 改变编辑状态
const handleEditStatus = () => {
  editStatus.value = !editStatus.value
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedCustomerData.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.key == 'bmi') {
            field.disabled = true
          } else {
            field.disabled = false
          }
        }
      }
    }
  }
  processedCustomerData.value = processedData
}
//给表单赋值 方便表单回显 obj 为表单数据
const setFormValue = (obj, formData, exportValue) => {
  let tempPhoneList = []
  let tempAddressList = []
  addressQuickList.value = []
  phoneQuickList.value = []
  // 深拷贝原始数据
  form.value = JSON.parse(JSON.stringify(obj))
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(formData))
  for (const section of processedData) {
    // 这里还要回显受供养人数，等调试的时候再加
    // if (section.key == 'personInfo') {
    //   section.data.push()
    // }
    if (
      section.key == 'apiTaxationDtoList' &&
      obj.apiTaxationDtoList &&
      obj.apiTaxationDtoList.length > 0
    ) {
      section.data = JSON.parse(JSON.stringify(obj.apiTaxationDtoList))
    }
    // 编辑状态当tab为受保人时，与投保人关系为本人控制受保人信息模块隐藏
    if (
      props.activeName == 'insurantInfo' &&
      props.idsObj.appointmentBizId &&
      obj.policyholderRel == 'MYSELF' &&
      section.key !== 'policyholderRel'
    ) {
      section.showMoudle = false
    }
    if (section.data) {
      for (const field of section.data) {
        if (obj.isRetirement && obj.isRetirement == '1' && field.key == 'retirementAge') {
          field.show = true
        }
        if (obj.isRetirement || obj.isRetirement == 0) {
          form.value['isRetirement'] = String(obj.isRetirement)
        }
        if (obj.dependentsNum) {
          field.show = true
        }
        if (field.dictType == 'sys_no_yes') {
          form.value[field.key] = String(obj[field.key])
        }
        //要判断drawerType,因为抽屉要回显数据
        switch (field.drawerType) {
          case 'phone':
            let phoneObj = {}
            for (const key1 in field) {
              for (const key2 in obj) {
                if (key1 !== 'drawerType' && field[key1] == key2) {
                  if (key1 == 'code' && obj[key2]) {
                    phoneObj[field[key1]] = obj[key2].includes('+') ? obj[key2] : `+${obj[key2]}`
                  } else {
                    phoneObj[field[key1]] = obj[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
            saveKey.value[field.key] = phoneObj
            break
          case 'address':
            let addressObj = null
            for (const key1 in field) {
              if (obj.addressList && obj.addressList.length > 0) {
                obj.addressList.forEach(item => {
                  if (key1 == 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
              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.nationality
            saveKey.value[field.key] = {
              // country: obj.country || '',
              // countryCode: obj.country || '',
              // countryName: obj.countryName || '',
              name: obj.nationality || '',
              objType: field.drawerType
            }
            break
          default:
            break
        }
      }
    }
  }
  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]
          }
        }
      }
    }
  })
  if (form.value['birthday']) {
    let age = calculateExactAge(proxy.formatToDate(form.value.birthday))
    if (age >= 18) {
      form.value.age = age
    }
  } else {
    form.value.age = null
  }

  phoneQuickList.value = removeDuplicates(tempPhoneList, 'phoneString')
  addressQuickList.value = removeDuplicates(tempAddressList, 'addressString')

  processedCustomerData.value = processedData
  console.log('form.value', form.value)
}
// 数组去重
function removeDuplicates(arr, key) {
  const seen = new Map()
  const result = []

  for (const item of arr) {
    if (!seen.has(item[key]) && 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:
          props.activeName == 'policyHolderInfo'
            ? `投保人模块-${fields[field][0].message}`
            : props.activeName == 'insuredInfo'
            ? `受保人模块-${fields[field][0].message}`
            : fields[field][0].message
      })
    }
  }
  return errors
}

const resetForm = () => {
  proxy.$modal
    .confirm('是否确认撤销所作操作？')
    .then(function () {
      customerFormRef.value.resetFields()
      console.log('切换之前的form', oldObjInfo.value)
      console.log('切换之前的dom', oldCustomerData.value)
      // processedCustomerData.value = JSON.parse(JSON.stringify(oldCustomerData.value))
      setFormValue(oldObjInfo.value, oldCustomerData.value)
    })

    .catch(() => {})
}
// 获取客户详情
function getCustomerInfo(customerBizId, formData) {
  getCustomerDetail(customerBizId).then(async res => {
    if (res.code == 200) {
      // 回显值
      setFormValue(res.data, formData)
    }
  })
}
// 根据联动重置表单项的显示与否
const resetShow = (key, status) => {
  for (const section of processedCustomerData.value) {
    if (section.data) {
      for (const field of section.data) {
        if (field.key == key) {
          // 获取字典数据
          field.show = status
        }
      }
    }
  }
}

//source：因为这个组件是公共组件所以提交的时候要知道是哪里要获取表单的值
const handleFormValues = source => {
  let submitObj = {}
  // 因为投保人没有policyholderRel的校验会影响 受保人，所以暂时先赋值处理
  if (source == 'policyHolderInfoRef') {
    form.value['policyholderRel'] = '111' //因为校验在form上所以这句不能去除
    submitObj = { ...policyholderForm.value }
  } else if (source == 'insuredInfoRef') {
    submitObj = { ...insuredForm.value }
  } else {
    submitObj = { ...form.value }
  }
  let processedData = JSON.parse(JSON.stringify(processedCustomerData.value))
  return new Promise(async resolve => {
    // 如果没有点击受保人这个tab页就进行填写提醒，
    if (
      source == 'insuredInfoRef' &&
      !props.idsObj.appointmentBizId &&
      !form.value['policyholderRel']
    ) {
      resolve(undefined)
      return
    }
    if (processedData.length > 0) {
      customerFormRef.value.validate((valid, fields) => {
        if (valid) {
          if (source == 'insuredInfoRef') {
            console.log('====================================')
            console.log('submitObj', form.value['policyholderRel'])
            console.log('====================================')
          }
          let addressList = []
          if (submitObj['birthday']) {
            if (source == 'insuredInfoRef' || source == 'policyHolderInfoRef') {
              submitObj['birthday'] = proxy.formatToDateTime(submitObj['birthday'])
            } else {
              submitObj['birthday'] = proxy.formatToDate(submitObj['birthday'])
            }
          }

          errorFields.value = [] // 清空错误信息
          //处理表单数据
          for (const key1 in form.value) {
            for (const key2 in saveKey.value) {
              //要判断drawerType
              switch (saveKey.value[key2].objType) {
                case 'phone':
                  if (key1 == key2) {
                    for (const key3 in saveKey.value[key2]) {
                      submitObj[key3] = saveKey.value[key2][key3]
                    }
                  }

                  break
                case 'address':
                  if (key1 == key2) {
                    addressList.push(saveKey.value[key2])
                  }
                  break
                case 'country':
                  if (key1 == key2) {
                    submitObj['country'] = saveKey.value[key2]['countryCode']
                    submitObj['countryName'] = saveKey.value[key2]['name']
                  }
                  break
                default:
                  break
              }
            }
          }
          if (addressList.length > 0) {
            submitObj['addressList'] = addressList
          }

          processedCustomerData.value.forEach(item => {
            if (item.key == 'apiTaxationDtoList' && item.data.length > 0) {
              submitObj['apiTaxationDtoList'] = item.data.filter(item => {
                return item.taxCountry && item.taxCountry.trim() && item.taxId && item.taxId.trim()
              })
            }
          })

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

          if (errorFields.value.length > 0) {
            proxy.$message.error(errorFields.value[0].message)
            return undefined
          }

          if (props.customerBizId && props.activeName == 'customer') {
            editCustomer(submitObj).then(res => {
              if (res.code == 200) {
                handleEditStatus()
                proxy.$message.success('客户修改成功')
                emit('handleSuccess', {
                  tab: 'customer',
                  customerBizId: props.customerBizId,
                  type: 'edit'
                })
              }
            })
          } else if (!props.customerBizId && props.activeName == 'customer') {
            addFna({ remark: '' }).then(response => {
              if (response.code == 200) {
                addCustomer(submitObj).then(res => {
                  if (res.code == 200) {
                    proxy.$message.success('客户新增成功')
                    emit('handleSuccess', {
                      tab: 'customer',
                      customerBizId: res.data.customerBizId,
                      fnaBizId: response.data.fnaBizId,
                      type: 'add'
                    })
                  }
                })
              }
            })
          }

          resolve(errorFields.value.length == 0 ? submitObj : null)
        } else {
          errorFields.value = getInvalidFields(fields)
          if (errorFields.value.length > 0) {
            proxy.$message.error(errorFields.value[0].message)
          }
          resolve(undefined)
        }
      })
    } else {
      // 编辑状态
      if (props.idsObj.appointmentBizId) {
        if (source == 'policyHolderInfoRef') {
          resolve(props.apiPolicyholderInfoDto)
        } else if (source == 'insuredInfoRef') {
          resolve(props.apiInsurantInfoDto)
        }
      } else {
        // 新增状态
        // 因为这两个在同一个大提交里，所以要判断是哪个提交，方便这两个都有自己独立的提交验证
        resolve(undefined)
      }
    }
  })
}
const anchorList = computed(() => {
  let data = []
  for (const section of processedCustomerData.value) {
    if (section.showMoudle) {
      data.push({ title: section.anchorKey, name: section.fatherTitle })
    }
  }
  return data
})
const policyholderForm = ref({}) //投保人表单值
const insuredForm = ref({}) //受保人表单值
watch(
  () => form.value,
  newVal => {
    if (props.activeName == 'policyholder') {
      policyholderForm.value = JSON.parse(JSON.stringify(newVal))
    } else if (props.activeName == 'insurantInfo') {
      insuredForm.value = JSON.parse(JSON.stringify(newVal))
    }
  },
  { immediate: true, deep: true }
)
watch(
  () => props.activeName,
  (newVal, oldVal) => {
    editStatus.value = false
    customerRightRef.value = null
    if (newVal === 'customer' || newVal === 'policyholder' || newVal === 'insurantInfo') {
      processFormData()
      // 因为客户资料里的编辑状态是单独控制的
      if (props.tabSource == 'customer' && props.customerBizId) {
        editStatus.value = true
      } else if (props.tabSource == 'customer' && !props.customerBizId) {
        editStatus.value = false
      }
      if (newVal === 'policyholder' || newVal === 'insurantInfo') {
        editStatus.value = props.fatherEditStatus
      }
    }
    // 切换tab要保存各自的表单值
    if (oldVal == 'policyholder') {
      policyholderForm.value = JSON.parse(JSON.stringify(form.value))
    } else if (oldVal == 'insurantInfo') {
      insuredForm.value = JSON.parse(JSON.stringify(form.value))
    }
  }
)
watch(
  () => props.fatherEditStatus,
  newVal => {
    editStatus.value = newVal
  }
)
// 暴露给父组件
defineExpose({
  handleFormValues,
  handleEditStatus,
  getRawForm: () => JSON.parse(JSON.stringify(form.value))
})
</script>
<style lang="scss" scoped>
.dialogBox {
  margin: 10px;
  width: 100%;
  height: 600px;
  overflow-y: scroll;
}
.customerContainer {
  /* display: flex; */
  height: 100%;
  box-sizing: border-box;
  position: relative;
}
.editBtn {
  position: fixed;
  right: 3.5%;
  top: 22%;
  z-index: 999;
}
.customerLeft {
  width: 15%;
  height: 100vh;
}
.customerRight {
  width: calc(100% - 15%);
  border-left: 3px solid rgb(247 247 247);
  padding-left: 10px;
  box-sizing: border-box;
}
.deleteIcon {
  color: red;
  font-size: 18px;
  padding-top: 10px;
}
.custom-label {
  width: 100%;
  display: flex;
  align-items: center;
}
.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;
    }
  }
}
.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: space-between;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      .infoItem {
        display: flex;
        align-items: center;
        margin: 5px 0;
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
/* 响应式调整 */
/* @media (max-width: 768px) {
  .editBtn {
    right: 5.5%;
    top: 16%;
  }
} */
</style>
