<template>
  <div style="padding-top: 10px">
    <div ref="beneficiaryRef">
      <CommonForm :showAnchor="false">
        <template #form-right>
          <el-form ref="beneficiaryInfoFormRef" :model="form" :rules="rules">
            <el-row v-for="father in processedBeneficiaryData" style="margin-bottom: 10px">
              <div class="formBox formFna">
                <CardOne
                  :showTitle="father.showTitle"
                  :title="father.fatherTitle"
                  v-if="father.showMoudle"
                >
                  <template #content>
                    <el-row v-if="!father.showTable" :gutter="20">
                      <template v-for="child in father.data" :key="child.key">
                        <el-col :sm="child.sm" :lg="child.lg" class="formItem" v-if="child.show">
                          <div>
                            <el-form-item
                              :label="child.label"
                              :prop="child.key"
                              :key="child.key"
                              :label-width="child.labelWidth"
                              :label-position="child.labelPosition"
                            >
                              <el-input
                                v-if="child.domType === 'Input'"
                                :type="child.inputType"
                                v-model="form[child.key]"
                                :placeholder="child.placeholder"
                                maxlength="30"
                                :disabled="editStatus"
                                :style="{ width: child.inputWidth ? child.inputWidth : '100%' }"
                              />
                              <el-select
                                v-if="child.domType === 'Select'"
                                v-model="form[child.key]"
                                :placeholder="child.placeholder"
                                @change="handleSelectChange(father, child)"
                                :disabled="editStatus"
                              >
                                <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"
                                :placeholder="child.placeholder"
                                :disabled="editStatus"
                              />
                              <el-checkbox-group
                                v-if="child.domType === 'Checkbox'"
                                v-model="form[child.key]"
                                :disabled="editStatus"
                              >
                                <el-checkbox
                                  v-for="item in child.options"
                                  :key="item.value"
                                  :label="item.value"
                                >
                                  {{ item.label }}
                                </el-checkbox>
                              </el-checkbox-group>
                              <el-select
                                v-model="form[child.key]"
                                v-if="child.domType === 'SearchSelect'"
                                filterable
                                remote
                                reserve-keyword
                                placeholder="请输入关键词搜索"
                                :remote-method="query => searchSelectList(query, child.key)"
                                :loading="searchLoadingStates[child.key]"
                                :disabled="editStatus"
                                @change="handleSearchSelectChange(child.key)"
                              >
                                <el-option
                                  v-for="item in searchOptions[child.key] || []"
                                  :key="item.id"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </el-select>
                            </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">
                        <!-- 动态渲染列 -->
                        <el-table-column
                          v-for="column in father.columns"
                          :key="column.prop"
                          :label="column.label"
                          :prop="column.prop"
                          align="center"
                        >
                          <template #default="scope">
                            <span v-if="column.type === 'text'">{{ scope.row[column.prop] }}</span>
                          </template>
                        </el-table-column>

                        <!-- 操作列（固定） -->
                        <el-table-column align="center" label="操作" width="150">
                          <template #default="scope">
                            <el-button
                              type="primary"
                              size="small"
                              :disabled="props.editStatus"
                              @click="updateChildren(father, scope.row)"
                            >
                              修改
                            </el-button>
                            <el-button
                              type="danger"
                              size="small"
                              :disabled="props.editStatus"
                              @click="deleteChildren(father, scope.$index)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-row>
                  </template>
                </CardOne>
              </div>
            </el-row>
          </el-form>
        </template>
      </CommonForm>

      <CommonDialog
        :dialogTitle="dialogTitle"
        confirmText="确定"
        cancleText="关闭"
        dialogWidth="70%"
        :showClose="true"
        :openDialog="dialogVisible"
        @close="dialogVisible = false"
        @confirm="dialogConfirm"
      >
        <div class="dialogBox">
          <el-form :model="dialogForm" ref="dialogFormRef">
            <el-row :gutter="20">
              <template v-for="(child, dIndex) in addBeneficiaryForm">
                <el-col :sm="child.sm" :lg="child.lg" class="formItem">
                  <el-form-item
                    :label="child.label"
                    :prop="child.key"
                    :key="child.key"
                    :label-width="child.labelWidth"
                    :label-position="child.labelPosition"
                    :rules="getRules(child)"
                  >
                    <el-input
                      v-if="child.domType === 'Input'"
                      :type="child.inputType"
                      v-model="dialogForm[child.key]"
                      :placeholder="child.placeholder"
                      maxlength="30"
                      @blur="handleInputBlur(child)"
                    />

                    <el-select
                      v-if="child.domType === 'Select'"
                      v-model="dialogForm[child.key]"
                      :placeholder="child.placeholder"
                    >
                      <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'"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      v-model="dialogForm[child.key]"
                      type="date"
                      :placeholder="child.placeholder"
                    />
                    <el-input
                      v-if="child.domType === 'arrowRight'"
                      v-model="dialogForm[child.key]"
                      :placeholder="child.placeholder"
                      @click="handleFoucs(child)"
                      :suffix-icon="ArrowRight"
                      readonly
                      :disabled="editStatus"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </el-form>
        </div>
      </CommonDialog>
    </div>
    <Phone
      @close="handleCloseDrawer"
      :showDrawer="showPhoneDrawer"
      :drawerInfo="drawerInfo"
      :phoneMenuList="phoneMenuList"
      :phoneQuickList="phoneQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Address
      @close="handleCloseDrawer"
      :showAddressDrawer="showAddressDrawer"
      :drawerInfo="drawerInfo"
      :addressMenuList="addressMenuList"
      :addressQuickList="addressQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Country
      :showCountryDrawer="showCountryDrawer"
      @close="handleCloseDrawer"
      @confirmCountry="confirmDrawer"
    />
  </div>
</template>
<script setup name="beneficiaryInfo">
import { getCustomerList, calculateFieldValue } from '@/api/sign/fna'
import CommonDialog from '@/components/commonDialog'

import CardOne from '@/components/formCard/cardOne'
import CommonForm from '@/views/components/commonForm'
import { validateEnglish } from '@/utils/validate'
import { ArrowRight } from '@element-plus/icons-vue'
import beneficiaryDomData from '@/formJson/beneficiary'
import Country from '@/views/components/country'
import Phone from '@/views/components/phone'
import Address from '@/views/components/address'

import { watch, nextTick } from 'vue'
import { updatePolicyBeneficiary, delPolicyBeneficiary } from '@/api/sign/underwritingMain'
import { editBeneficiaryInfo, delBeneficiary } from '@/api/sign/appointment'
import useDictStore from '@/store/modules/dict'

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

const tableLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const beneficiaryInfoFormRef = ref(null)
// 地址组件菜单数据
const addressMenuList = ref([
  {
    name: '国家/地区',
    icon: false,
    value: '',
    placeholder: '请输入国家/地区',
    key: 'region'
  },
  {
    name: '省市',
    icon: false,
    value: '',
    placeholder: '请输入省市',
    key: 'city'
  },
  {
    name: '街道',
    icon: false,
    value: '',
    placeholder: '请输入街道',
    key: 'street'
  },
  {
    name: '详细地址',
    icon: false,
    value: '',
    placeholder: '请输入详细地址',
    key: 'location'
  }
])
// 快捷地址的数据
const addressQuickList = ref([])
const phoneMenuList = ref([
  {
    name: '区号',
    icon: true,
    value: '',
    placeholder: '请输入区号',
    arrow: true,
    type: 'string'
  },
  {
    name: '电话号码',
    icon: false,
    value: '',
    placeholder: '请输入电话号码',
    type: 'number'
  }
])
const phoneQuickList = ref([])
const tempAddressQuickList = ref([])
const tempPhoneQuickList = ref([])
const personalObj = ref({}) //存储个人key
const companyObj = ref({}) //存储公司key
const dialogVisible = ref(false) //新增受益人弹窗
const addBeneficiaryForm = ref([]) //新增受益人表单
const dialogTitle = ref('') //新增受益人弹窗标题
const dialogKey = ref('') //新增受益人弹窗标题
const deleteKeyList = ref([
  'objType',
  'mailingAddress',
  'residentialAddress',
  'residenceAddress',
  'companyAddress',
  'txAddress',
  'companyEnterAddress',
  'phoneString',
  'phoneCode'
]) // 存储需要删除的key
const data = reactive({
  form: { apiBeneficiaryInfoDtoList: [] },
  tempBeneficiaryForm: {}, //由于切换tab的时候，表单数据会重置，所以需要
  processedBeneficiaryData: [], // 处理后的表单数据
  tempBeneficiaryDomData: [], //保存旧的表单Dom,便于撤销操作
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  dialogForm: {},
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const {
  form,
  rules,
  processedBeneficiaryData,
  queryParams,
  oldAppointmentData,
  tempBeneficiaryForm,
  tempBeneficiaryDomData,
  dialogForm
} = toRefs(data)
const deleteChildren = (father, index) => {
  if (father.key == 'apiBeneficiaryInfoDtoList') {
    father.data.splice(index, 1)
    proxy.$message.success('受益人删除成功')
  }
}
const updateChildren = (father, row) => {
  dialogForm.value = JSON.parse(JSON.stringify(row))
  if (father.key == 'apiBeneficiaryInfoDtoList') {
    dialogTitle.value = '修改受益人'
    dialogKey.value = 'apiBeneficiaryInfoDtoList'
    addBeneficiaryForm.value = JSON.parse(JSON.stringify(father.formItem))
  }
  dialogVisible.value = true
}

const dialogConfirm = () => {
  let newDOM = JSON.parse(JSON.stringify(processedBeneficiaryData.value))
  proxy.$refs['dialogFormRef'].validate((valid, fields) => {
    if (valid) {
      for (const section of newDOM) {
        if (section.key == dialogKey.value) {
          // 处理下拉值得显示
          for (const child of section.formItem) {
            if (child.domType == 'Select' && dialogForm.value[child.key]) {
              child.options.forEach(item => {
                if (item.value == dialogForm.value[child.key]) {
                  dialogForm.value[child.key + 'Name'] = item.label
                }
              })
            }
          }
          let index = section.data.findIndex(item => item.id == dialogForm.value.id)
          if (index == -1) {
            section.data.push(dialogForm.value)
          } else {
            section.data[index] = JSON.parse(JSON.stringify(dialogForm.value))
          }
        }
      }
      processedBeneficiaryData.value = newDOM
      dialogVisible.value = false
      dialogForm.value = {}
    }
  })
}
// 添加表单子级dom
const addChildren = father => {
  if (props.editStatus) {
    proxy.$message.warning('请先点击编辑')
    return
  }
  dialogForm.value = { id: Date.now() + Math.floor(Math.random()) }
  if (father.key == 'apiBeneficiaryInfoDtoList') {
    dialogTitle.value = '新增受益人'
    dialogKey.value = 'apiBeneficiaryInfoDtoList'
    addBeneficiaryForm.value = JSON.parse(JSON.stringify(father.formItem))

    dialogVisible.value = true
  }
}
const handleInputBlur = child => {
  if (dialogForm.value['documentType'] == 'idCard' && child.key == 'idNumber') {
    getFieldValue(child.key)
  } else if (child.key == 'nameCn' && dialogForm.value['nameCn']) {
    getFieldValue(child.key)
  }
}
const getFieldValue = key => {
  let obj = {}
  if (dialogForm.value['documentType'] == 'idCard' && key == 'idNumber') {
    obj = {
      calculateType: 6,
      requestValue: dialogForm.value['idNumber']
    }
  } else if (key == 'nameCn') {
    obj = {
      calculateType: 1,
      requestValue: dialogForm.value['nameCn']
    }
  }
  calculateFieldValue(obj).then(res => {
    if (res.code == 200) {
      res.data.forEach(item => {
        if (obj.calculateType == 6) {
          if (item.calculateType == 2) {
            dialogForm.value['gender'] = item.responseKey
          } else if (item.calculateType == 3) {
            dialogForm.value['birthday'] = item.requestValue
          } else if (item.calculateType == 4) {
            dialogForm.value['age'] = item.requestValue
          }
        } else if (obj.calculateType == 1) {
          dialogForm.value['namePyEn'] = item.responseValue
        }
      })
    }
  })
}
// 获取表单项的校验规则
const getRules = child => {
  const rules = []

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

  return rules
}

const customerList = () => {
  console.log('触发了')

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

// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        if (dictType == 'sys_no_yes') {
          item.dictItemList.forEach(item1 => {
            item1.value = Number(item1.value)
          })
        }
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}

// 处理表单配置，添加字典数据
/**
 * domdata:表单的dom数据
 * customerInfo:根据客户信息回显表单
 * exportValue:是否从导入联系人列表中导入客户信息到当前表单
 */
const processFormData = async obj => {
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(obj.domdata))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        rules.value[field.key] = [
          { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
        ]
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
      }
    }
    if (section.formItem) {
      for (const field of section.formItem) {
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
      }
    }
  }
  if (props.idsObj.appointmentBizId ) {
    setFormValue(processedData)
  } else {
    processedBeneficiaryData.value = oldAppointmentData.value = processedData
  }
}

//弹出右侧抽屉
const handleFoucs = (child, l1, level1) => {
  if (child.disabled) return
  drawerInfo.value = JSON.parse(JSON.stringify(child))
  console.log('drawerInfo', drawerInfo.value)
  switch (child.drawerType) {
    // case 'phone':
    //   phoneMenuList.value[0].key = child.code
    //   phoneMenuList.value[1].key = child.key
    //   phoneMenuList.value.forEach(item => {
    //     item.value = ''
    //   })
    //   let phoneString = form.value.apiBeneficiaryInfoDtoList[l1][child.key]
    //   if (phoneString) {
    //     phoneMenuList.value[0].value = phoneString.split(' ')[0]
    //     phoneMenuList.value[1].value = phoneString.split(' ')[1]
    //   }
    //   showPhoneDrawer.value = true
    //   break
    // case 'address':
    //   addressMenuList.value.forEach(item => {
    //     item.value = ''
    //     phoneOraddressKey.value.forEach(item1 => {
    //       if (item1.id == level1.id && item1.type == child.key) {
    //         for (const key in item1) {
    //           if (item.key == key) {
    //             item.value = item1[key]
    //           }
    //         }
    //       }
    //     })
    //   })
    //   showAddressDrawer.value = true
    //   break
    case 'country':
      showCountryDrawer.value = true
      break
    default:
      break
  }
}
// 处理抽屉关闭
const handleCloseDrawer = () => {
  showPhoneDrawer.value = false
  showAddressDrawer.value = false
  showCountryDrawer.value = false
  drawerInfo.value = {}
}
const confirmDrawer = info => {
  // info 为抽屉返回的值
  if (drawerInfo.value.domType == 'arrowRight' && drawerInfo.value.drawerType) {
    let newObj = info[drawerInfo.value.key]
    //要判断drawerType
    switch (drawerInfo.value.drawerType) {
      case 'phone':
        newObj.key = drawerInfo.value.key
        form.value.apiBeneficiaryInfoDtoList[drawerInfo.value.l1][drawerInfo.value.key] =
          newObj.phoneString = `${newObj[drawerInfo.value.code]} ${newObj[drawerInfo.value.key]}`
        // 检查数组中是否已存在key的电话
        const existingIndex1 = phoneQuickList.value.findIndex(item => item.key === newObj.key)

        if (existingIndex1 !== -1) {
          // 更新已存在的电话
          phoneQuickList.value[existingIndex1] = {
            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':
        //因为可以添加多个受益人，所以需要判断是哪个受益人，一定要有id
        newObj.type = drawerInfo.value.key
        newObj.id = drawerInfo.value.id
        newObj.drawerType = drawerInfo.value.drawerType
        form.value.apiBeneficiaryInfoDtoList[drawerInfo.value.l1][drawerInfo.value.key] =
          `${newObj.region} ${newObj.city} ${newObj.street} ${newObj.location}`
        newObj.addressString = `${newObj.region} ${newObj.city} ${newObj.street} ${newObj.location}`

        // 检查数组中是否已存在相同ID的地址
        const existingIndex = phoneOraddressKey.value.findIndex(
          item => item.id === newObj.id && item.type === newObj.type
        )

        if (existingIndex !== -1) {
          // 更新已存在的地址
          phoneOraddressKey.value[existingIndex] = { ...newObj }
        } else {
          // 添加新地址
          phoneOraddressKey.value.push({ ...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')

        break
      case 'country':
        // info.objType = drawerInfo.value.drawerType
        dialogForm.value[drawerInfo.value.key] = info.name
        // saveKey.value[drawerInfo.value.key] = info
        break
      default:
        break
    }
    // 手动触发表单验证
    nextTick(() => {
      // 根据不同的drawerType确定要验证的字段key
      const validateField = drawerInfo.value.key
      beneficiaryInfoFormRef.value.clearValidate(validateField)
    })
  }

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

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

      default:
        break
    }
  }
  console.log('更新', processedBeneficiaryData.value)
}
const handleSelectChange = (father, child) => {
  switch (child.key) {
    case 'isLegalBeneficiary':
      if (form.value[child.key] == '0') {
        resetShow({ type: 'father', key: 'apiBeneficiaryInfoDtoList', status: true })
      } else {
        resetShow({ type: 'father', key: 'apiBeneficiaryInfoDtoList', status: false })
      }

      break
    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = status => {
  editStatus.value = status
  console.log('触发了编辑状态', editStatus.value)

  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedBeneficiaryData.value))
  for (const section of processedData) {
    for (const child of section.children) {
      for (const field of child.data) {
        if (editStatus.value) {
          field.disabled = true
        } else {
          field.disabled = false
        }
      }
    }
  }
  processedBeneficiaryData.value = processedData
}

// 数组去重
function removeDuplicates(arr, key) {
  const seen = new Map()
  const result = []

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

  return result
}
// 修改状态下，处理表单数据
const setFormValue = processedData => {
  personalObj.value = {}
  companyObj.value = {}
  processedBeneficiaryData.value = []
  let quickMobile = []
  let qucikAddress = []
  // 深拷贝原始数据
  const oldDom = JSON.parse(JSON.stringify(processedData))
  let obj = JSON.parse(JSON.stringify(props.apiBeneficiaryInfoFzDto))
  for (const section of oldDom) {
    for (const key in obj) {
      if (section.keyType == 'Object') {
        form.value[key] = obj[key]
      }
      if (section.keyType == 'Array' && key == section.key && obj[key].length > 0) {
        if (section.formItem) {
          for (const child of section.formItem) {
            if (child.domType == 'Select') {
              obj[key].forEach((item1, index) => {
                if (section.key == 'apiBeneficiaryInfoDtoList' && item1.birthday) {
                  item1.birthday = proxy.formatToDate(item1.birthday)
                }
                fetchDictData(child.dictType).forEach(item2 => {
                  if (item1[child.key] == item2.value) {
                    item1[child.key + 'Name'] = item2.label
                  }
                })
              })
            }
          }
        }

        section.data = obj[key]
        if (section.key == 'apiBeneficiaryInfoDtoList') {
          if (obj['isLegalBeneficiary'] == '0') {
            section.showMoudle = true
          } else {
            section.data = []
            section.showMoudle = false
          }
        }
      }
    }
  }
  processedBeneficiaryData.value = oldDom
  console.log('dom', processedBeneficiaryData.value)
}
// 获取校验失败的字段信息
const getInvalidFields = fields => {
  const errors = []
  for (const field in fields) {
    if (fields[field] && fields[field].length > 0) {
      errors.push({
        field: field,
        message: `受益人模块-${fields[field][0].message}`
      })
    }
  }
  return errors
}

// 处理表单填写得数据
const handleFormValues = () => {
  return new Promise(async resolve => {
    if (processedBeneficiaryData.value.length > 0) {
      let submitObj = { ...form.value }

      proxy.$refs['beneficiaryInfoFormRef'].validate((valid, fields) => {
        if (valid) {
          errorFields.value = [] // 清空错误信息
          //处理表单数据
          processedBeneficiaryData.value.forEach(item => {
            if (item.keyType == 'Array') {
              submitObj[item.key] = JSON.parse(JSON.stringify(item.data))
              submitObj[item.key].forEach((item1, index) => {
                if (item1['birthday']) {
                  item1['birthday'] = proxy.formatToDateTime(item1['birthday'])
                }
              })
            }
          })
          if (submitObj['isLegalBeneficiary'] == '1') {
            delete submitObj['apiBeneficiaryInfoDtoList']
          }
          if (errorFields.value.length > 0) {
            proxy.$message.error(errorFields.value[0].message)
            return undefined
          }

          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) {
        resolve(props.apiBeneficiaryInfoFzDto)
      } else {
        resolve(undefined)
      }
    }
  })
}

const resetForm = () => {
  proxy.$modal
    .confirm('是否确认撤销所作操作？')
    .then(function () {
      if (props.customerBizId) {
        form.value = { ...oldObjInfo.value }
        editStatus.value = true
      } else {
        // resetShow('smokeQuantity', false)
        proxy.$refs['beneficiaryInfoFormRef'].resetFields()
      }
      processedBeneficiaryData.value = JSON.parse(JSON.stringify(oldAppointmentData.value))
    })

    .catch(() => {})
}
const hasLoaded = ref(false) // 新增：是否已加载过数据
watch(
  () => props.activeName,
  newVal => {
    if (newVal === 'beneficiary') {
      openList.value = false
      if (!hasLoaded.value) {
        processFormData({
          domdata: beneficiaryDomData,
          exportValue: null
        })
        hasLoaded.value = true
      }
    }
  }
)
//导入预约单成功后，要重新渲染页面回显值
watch(
  () => props.isExportAppointment,
  newVal => {
    if (newVal) {
      setFormValue(processedBeneficiaryData.value)
    }
  }
)
// 暴露给父组件
defineExpose({
  handleFormValues,
  handleEditStatus
})
</script>
<style lang="scss" scoped>
.domEmpty {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #a8abb2;
  margin-top: 100px;
}
.topBtn {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .level1Label {
    font-size: 18px;
    margin: 15px 0;
    display: flex;
    align-items: center;
  }
  .fatherLable {
    font-size: 15px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
    margin-bottom: 10px;
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .inputBox {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 0px 11px;
    .rightArrow {
      font-size: 14px;
      color: #a8abb2;
    }
  }
  .desBox {
    display: flex;
    justify-content: flex-start;
    .title {
      width: 120px;
      font-size: 14px;
      text-align: right;
    }
    .informationBox {
      margin-left: 5px;
      font-size: 14px;
      border: 1px solid #dcdfe6;
      width: 100%;
      border-radius: 4px;
      padding: 2px 4px;
      box-sizing: border-box;
    }
  }
}
.tabButton {
  box-shadow: 0 -1px 14px #00000014;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding-right: 20px; */
  padding-top: 20px;
  .sumbitBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    height: 60px;
    background-color: #165dff;
    color: #fff;
    padding: 0 30px;
    .buttonIcon {
      font-size: 16px;
      color: #fff;
    }
  }
}
.customerBox {
  .customerItem {
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 20px;
    box-shadow: 0 -1px 14px #00000014;
    .top {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .left {
        .infoItem {
          display: flex;
          align-items: center;
          margin: 5px 10px;
        }
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
</style>
