<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.customLabel ? '' : child.label"
                              :prop="child.key"
                              :key="child.key"
                              :label-width="child.labelWidth"
                              :label-position="child.labelPosition"
                            >
                              <!-- 自定义 label 插槽 -->
                              <template v-if="child.customLabel" #label>
                                <div class="custom-label">
                                  <span>{{ child.label }}</span>
                                  <el-checkbox-group
                                    v-if="child.customAddress"
                                    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'"
                                v-model="form[child.key]"
                                :type="child.inputType"
                                :placeholder="child.placeholder"
                                :maxlength="child.maxlength"
                                :formatter="
                                  value =>
                                    child.isFormatter
                                      ? `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                                      : value
                                "
                                :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                                :disabled="
                                  child.key == 'age' ||
                                  child.key == 'bmi' ||
                                  child.key == 'dependentsNum'
                                    ? true
                                    : editStatus
                                "
                                @blur="handleInputBlur(child)"
                                @input="val => handleInputChange(val, 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">
                        <!-- 动态渲染列 -->
                        <!--  :label="column.label" -->
                        <el-table-column
                          v-for="column in father.columns"
                          :key="column.prop"
                          :prop="column.prop"
                          align="center"
                          :width="column.width"
                        >
                          <template #header>
                            <span
                              :class="{ 'required-label': column.required ? 'required-label' : '' }"
                              >{{ column.label }}</span
                            >
                          </template>
                          <template #default="scope">
                            <!-- 远程搜索选择框 -->
                            <el-select
                              v-if="column.type === 'remoteSelect'"
                              v-model="scope.row[column.prop]"
                              filterable
                              remote
                              reserve-keyword
                              :placeholder="column.placeholder"
                              :remote-method="
                                query => searchSelectList(query, column.searchType, scope.row)
                              "
                              :loading="searchLoadingStates[column.searchType]"
                              :disabled="editStatus"
                              @change="handleRemoteSelectChange(scope.row, column, father)"
                            >
                              <template>
                                <el-option
                                  v-for="item in searchOptions[column.searchType] || []"
                                  :key="item.id"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </template>
                            </el-select>

                            <!-- 普通选择框 -->
                            <el-select
                              v-else-if="column.type === 'select'"
                              v-model="scope.row[column.prop]"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                              @change="changeSelect(father, scope.row, column.prop, $event)"
                            >
                              <el-option
                                v-for="item in fetchDictData(column.dictType)"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              />
                            </el-select>

                            <!-- 日期选择器  -->
                            <div v-else-if="column.prop === 'certificateValidityPeriod'">
                              <el-date-picker
                                v-model="scope.row.certificateStartDate"
                                type="date"
                                placeholder="开始日期"
                                :disabled="editStatus"
                                :style="{
                                  width: scope.row.isPermanent == '1' ? '100%' : 'calc(50% - 10px)'
                                }"
                              />
                              <span
                                v-if="!scope.row.isPermanent || scope.row.isPermanent == '0'"
                                style="display: inline-block; width: 20px; text-align: center"
                                >-</span
                              >
                              <el-date-picker
                                v-model="scope.row.certificateEndDate"
                                v-if="!scope.row.isPermanent || scope.row.isPermanent == '0'"
                                type="date"
                                placeholder="结束日期"
                                :disabled="editStatus"
                                style="width: calc(50% - 10px)"
                              />
                            </div>
                            <el-radio-group
                              v-model="scope.row[column.prop]"
                              v-else-if="column.type === 'radioGroup'"
                              @change="
                                handleIsPermanentChange(father, scope.row, column.prop, $event)
                              "
                              :disabled="editStatus"
                            >
                              <el-radio value="1" size="large">是</el-radio>
                              <el-radio value="0" size="large">否</el-radio>
                            </el-radio-group>
                            <!-- 普通输入框（默认） -->
                            <el-input
                              v-else
                              v-model="scope.row[column.prop]"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                              @blur="tableInputBlur(father, scope.row, column.prop, $event)"
                              :formatter="
                                value =>
                                  column.isFormatter
                                    ? `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                                    : value
                              "
                              :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                            />
                            <!-- 满足一定条件展示得控件 -->
                          </template>
                        </el-table-column>

                        <!-- 操作列（固定） -->
                        <el-table-column width="80" align="center" label="操作">
                          <template #default="scope">
                            <el-button
                              type="danger"
                              size="small"
                              @click="deleteChildren(father, scope.$index)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </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" fixed="left" />
              <el-table-column label="姓名(英文)" align="center" prop="namePyEn" 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" width="150">
                <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" width="200" />
              <el-table-column label="电话号码" align="center" prop="mobile" width="200" />
              <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 { numberFormat } from '@/utils/number'
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: () => ({}) }, //受保人编辑状态详情
  isExportAppointment: { type: Boolean, default: false } //是否导入
})
const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
const tempPolicyholderDom = ref([]) //投保人dom
const tempInsurantDom = ref([]) //受保人dom
const tempCustomerDom = ref([]) //受保人dom
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()

// 地址组件菜单数据
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 handleIsPermanentChange = (father, row, prop, newValue) => {
  if (prop == 'isPermanent') {
    row.certificateStartDate = null
    row.certificateEndDate = null
  }
}
// 表格改变下拉框
const changeSelect = (father, row, prop, newValue) => {
  if (prop == 'documentType') {
    // 检查其他行是否已有相同的证件类型（排除自己）
    const hasDuplicate = father.data.some(item => item !== row && item.documentType === newValue)

    if (hasDuplicate) {
      //如果选择的是身份证，给性别，生日，年龄赋值
      proxy.$modal.confirm(`该证件类型已存在，请勿重复添加！`, {
        showCancel: '0',
        title: '填写提示'
      })
      // 清空当前行的选择
      row.documentType = null // 或者 undefined，根据你的数据结构
    }
  }
  console.log('提交', processedCustomerData.value)
}
const tableInputBlur = (father, row, prop, newValue) => {
  if (prop == 'idNumber' && row.documentType == 'idCard') {
    getFieldValue(prop, row.idNumber)
  }
}
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 handleInputChange = (val, child) => {
  let newVal = numberFormat(val, child)
  form.value[child.key] = newVal
  if (child.key == 'nameCn' && !form.value['nameCn']) {
    form.value['namePyEn'] = ''
  }
}
const handleInputBlur = child => {
  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, value) => {
  let obj = {}
  if (key == 'idNumber') {
    obj = {
      calculateType: 6,
      requestValue: value
    }
  } 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: ''
  }
  let obj5 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    documentType: '',
    idNumber: '',
    certificateValidityPeriod: '',
    certificateStartDate: '',
    certificateEndDate: '',
    isPermanent: ''
  }

  for (const section of processedData) {
    if (father.key == 'apiTaxationDtoList' && section.key == father.key) {
      section.data.push(obj4)
    }
    if (father.key == 'apiCertificateDtoList' && section.key == father.key) {
      section.data.push(obj5)
    }
  }
  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)
    }
    if (father.key == 'apiCertificateDtoList' && 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 && props.activeName !== 'insurantInfo') {
      form.value.age = age
    } else if (props.activeName == 'insurantInfo') {
      form.value.age = age
    }
  }
}
const disabledDate = (time, child) => {
  if (child.key == 'birthday' && props.activeName !== 'insurantInfo') {
    // 计算18年前的今天
    const eighteenYearsAgo = dayjs().subtract(19, 'year')
    // 禁用今天之后的日期和18年前的今天之后的日期
    return time.getTime() > Date.now() || time.getTime() > eighteenYearsAgo.valueOf()
  }
}
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 (props.activeName == 'insurantInfo') {
      if (form.value['policyholderRel'] && form.value['policyholderRel'] == 'MYSELF') {
        if (section.key == 'policyholderRel') {
          section.showMoudle = true
        } else {
          section.showMoudle = false
        }
      } else {
        section.showMoudle = true
      }
    }
    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 &&
    !props.isExportAppointment
  ) {
    //是投保人/受保人但是新增预约 需要引用客户资料的值
    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 {
    if (props.tabSource == 'customer') {
      form.value.smokingStatus = '0'
    }
    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 (section.keyType == 'Array') {
          section.data = []
        }
        if (section.data) {
          for (const field of section.data) {
            if (field.key !== 'policyholderRel') {
              form.value[field.key] = ''
              delete saveKey.value[field.key]
            }
          }
        }
        if (form.value[child.key] == 'MYSELF') {
          if (section.key == 'policyholderRel') {
            section.showMoudle = true
          } else {
            section.showMoudle = false
          }
        } else {
          section.showMoudle = true
        }
      })

      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))
  // 新增预约，是受保人，与投保人关系默认值是本人
  if (props.activeName == 'insurantInfo' && !props.idsObj.appointmentBizId && !exportValue) {
    form.value['policyholderRel'] = 'MYSELF'
  }
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(formData))

  for (const section of processedData) {
    if (
      section.key == 'apiTaxationDtoList' &&
      obj.apiTaxationDtoList &&
      obj.apiTaxationDtoList.length > 0
    ) {
      section.data = JSON.parse(JSON.stringify(obj.apiTaxationDtoList))
    }
    if (
      section.key == 'apiCertificateDtoList' &&
      obj.apiCertificateDtoList &&
      obj.apiCertificateDtoList.length > 0
    ) {
      obj.apiCertificateDtoList.forEach(item => {
        if (item.isPermanent || item.isPermanent == 0) {
          item.isPermanent = String(item.isPermanent)
        }
      })
      section.data = JSON.parse(JSON.stringify(obj.apiCertificateDtoList))
    }
    // 编辑状态当tab为受保人时，与投保人关系为本人控制受保人信息模块隐藏
    if (
      props.activeName == 'insurantInfo' &&
      form.value['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) {
              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
        }
        for (const key in obj) {
          if (field.key == key && !obj[key]) {
            obj[key] = ''
            form.value[key] = ''
          }
        }
      }
    }
  }
  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
  }
  // 使用历史客户导入的，要保持原来的与投保人关系的值
  if (exportValue) {
    form.value['policyholderRel'] = oldObjInfo.value['policyholderRel']
  }
  phoneQuickList.value = removeDuplicates(tempPhoneList, 'phoneString')
  addressQuickList.value = removeDuplicates(tempAddressList, 'addressString')
  if (addressQuickList.value.length > 0) {
    addressQuickList.value.forEach(item => {
      form.value[item.type] = `${item.region} ${item.city} ${item.street} ${item.location}`
    })
  }
  processedCustomerData.value = processedData
}
// 数组去重
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()
      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 = {}
  let processedData = []
  // 因为投保人没有policyholderRel的校验会影响 受保人，所以暂时先赋值处理
  if (source == 'policyHolderInfoRef') {
    form.value['policyholderRel'] = '111' //因为校验在form上所以这句不能去除
    submitObj = { ...policyholderForm.value }
    processedData = JSON.parse(JSON.stringify(tempPolicyholderDom.value))
  } else if (source == 'insuredInfoRef') {
    submitObj = { ...insuredForm.value }
    processedData = JSON.parse(JSON.stringify(tempInsurantDom.value))
  } else {
    submitObj = { ...form.value }
    processedData = JSON.parse(JSON.stringify(processedCustomerData.value))
  }
  let tipName =
    source == 'policyHolderInfoRef'
      ? '投保人'
      : source == 'insuredInfoRef'
        ? '受保人'
        : props.activeName == 'customer'
          ? '客户资料'
          : ''

  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) {
          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 = [] // 清空错误信息
          console.log('errorFields.value', errorFields.value)

          //处理表单数据
          for (const key1 in form.value) {
            if (key1 == 'nameCn' && submitObj[key1]) {
              if (submitObj[key1].length < 2) {
                errorFields.value.push({
                  message: `${tipName}-名字至少为2个字符`
                })
              }
              if (submitObj[key1].length > 6) {
                errorFields.value.push({
                  message: `${tipName}-名字长度不能超过6个字符`
                })
              }
            }
            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
          }
          let obj1 = {
            documentType: '证件类型',
            idNumber: '证件号码'
          }

          processedData.forEach(item => {
            if (item.key == 'apiCertificateDtoList' && item.data.length > 0) {
              item.data.forEach((item1, index) => {
                // if (!item1.isPermanent || item1.isPermanent == '0') {
                //   if (!item1.certificateStartDate) {
                //     obj1.certificateStartDate = '证件开始时间'
                //   }
                //   if (!item1.certificateEndDate) {
                //     obj1.certificateEndDate = '证件结束时间'
                //   }
                // } else if (item1.isPermanent == '1' && !item1.certificateStartDate) {
                //   obj1.certificateStartDate = '证件有效时间'
                // }
                for (const key in obj1) {
                  if (!item1[key]) {
                    errorFields.value.push({
                      message: `${tipName}证件信息-第${index + 1}行${obj1[key]}不能为空`
                    })
                    return
                  }
                  if (item1.certificateStartDate) {
                    item1.certificateStartDate = proxy.formatToDate(item1.certificateStartDate)
                  }
                  if (item1.certificateEndDate) {
                    item1.certificateEndDate = proxy.formatToDate(item1.certificateEndDate)
                  }
                }
              })
              submitObj['apiCertificateDtoList'] = item.data
            } else if (item.key == 'apiCertificateDtoList' && item.data.length == 0) {
              if (source !== 'insuredInfoRef') {
                errorFields.value.push({
                  message: `${tipName}证件信息不能为空`
                })
              } else if (source == 'insuredInfoRef') {
                if (submitObj['policyholderRel'] !== 'MYSELF') {
                  errorFields.value.push({
                    message: `${tipName}证件信息不能为空`
                  })
                }
              }
            }
            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') {
            submitObj['fnaBizId'] = props.idsObj.fnaBizId

            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) {
                submitObj['fnaBizId'] = response.data.fnaBizId
                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({}) //受保人表单值
const customerForm = 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))
    } else if (props.activeName == 'customer') {
      customerForm.value = JSON.parse(JSON.stringify(newVal))
    }
  },
  { immediate: true, deep: true }
)
watch(
  () => processedCustomerData.value,
  newVal => {
    if (props.activeName == 'policyholder') {
      tempPolicyholderDom.value = JSON.parse(JSON.stringify(newVal))
    } else if (props.activeName == 'insurantInfo') {
      tempInsurantDom.value = JSON.parse(JSON.stringify(newVal))
    } else if (props.activeName == 'customer') {
      tempCustomerDom.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') {
      defaultDisplayDate.value = dayjs().subtract(19, 'year').toDate()
    }
    if (newVal === 'customer') {
      processFormData()
      // if (JSON.stringify(customerForm.value) != '{}') {
      //   form.value = JSON.parse(JSON.stringify(customerForm.value))

      //   processedCustomerData.value = JSON.parse(JSON.stringify(tempCustomerDom.value))
      //   return
      // } else {
      //   processFormData()
      // }
      // 因为客户资料里的编辑状态是单独控制的
      if (props.tabSource == 'customer' && props.customerBizId) {
        editStatus.value = true
      } else if (props.tabSource == 'customer' && !props.customerBizId) {
        editStatus.value = false
      }
    }
    if (newVal === 'policyholder') {
      editStatus.value = props.fatherEditStatus
      if (JSON.stringify(policyholderForm.value) != '{}') {
        form.value = JSON.parse(JSON.stringify(policyholderForm.value))

        processedCustomerData.value = JSON.parse(JSON.stringify(tempPolicyholderDom.value))
        return
      } else {
        processFormData()
      }
    } else if (newVal === 'insurantInfo') {
      defaultDisplayDate.value = dayjs().startOf('day')
      editStatus.value = props.fatherEditStatus
      if (JSON.stringify(insuredForm.value) != '{}') {
        form.value = JSON.parse(JSON.stringify(insuredForm.value))
        processedCustomerData.value = JSON.parse(JSON.stringify(tempInsurantDom.value))
        return
      } else {
        processFormData()
      }
    }
  }
)
watch(
  () => props.fatherEditStatus,
  newVal => {
    editStatus.value = newVal
  }
)
//导入预约单成功后，要重新渲染页面回显值
watch(
  () => props.isExportAppointment,
  newVal => {
    console.log('导入发生变化', newVal)

    if (newVal) {
      if (props.tabSource == 'policyholder') {
        // 投保人回显值
        setFormValue(props.apiPolicyholderInfoDto, processedCustomerData.value)
      } else if (props.tabSource == 'insurantInfo') {
        // 受保人回显值
        setFormValue(props.apiInsurantInfoDto, processedCustomerData.value)
      }
    }
  }
)
// 暴露给父组件
defineExpose({
  handleFormValues,
  handleEditStatus,
  getInsuredForm: () => JSON.parse(JSON.stringify(insuredForm.value))
})
</script>
<style lang="scss" scoped>
.dialogBox {
  margin: 10px;
  width: 100%;
  height: 600px;
  overflow-y: scroll;
}
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.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;
  .numberTxt {
    font-size: 14px;
    font-weight: normal;
    margin-left: 5px;
    color: #a8abb2;
  }
}
.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>
