<template>
  <div>
    <div v-if="processedAppointmentData.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <el-button
              v-if="props.idsObj.appointmentBizId"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus(!editStatus)"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="appointmentInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <div v-for="father in processedAppointmentData">
          <el-row style="margin-bottom: 10px" v-if="father.showMoudle">
            <div class="formBox">
              <div class="fatherLable">{{ father.fatherTitle }}</div>
              <div class="fatherDes">{{ father.description }}</div>

              <el-row :gutter="20">
                <template v-for="child in father.data" :key="child.key">
                  <el-col :sm="child.sm" :lg="child.lg" class="formItemBox" v-if="child.show">
                    <div>
                      <el-form-item
                        :label-width="child.labelWidth"
                        :label="child.label"
                        :prop="child.key"
                        :key="child.key"
                        :label-position="child.labelPosition"
                        class="button-form-item"
                      >
                        <el-input
                          v-if="child.domType === 'Input'"
                          :type="child.inputType"
                          v-model="form[child.key]"
                          :placeholder="child.placeholder"
                          maxlength="30"
                          :disabled="child.disabled"
                        />
                        <el-select
                          v-if="child.domType === 'Select'"
                          v-model="form[child.key]"
                          :placeholder="child.placeholder"
                          @change="handleSelectChange(father, child)"
                          :disabled="child.disabled"
                        >
                          <el-option
                            v-for="item in child.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                        <!-- 带时分的时间框 -->
                        <el-date-picker
                          v-model="form[child.key]"
                          style="width: 100%"
                          v-if="child.domType === 'datetimePicker'"
                          :type="child.timeType || 'datetime'"
                          :placeholder="child.placeholder"
                          :disabled="child.disabled"
                          @change="handleDateChange(child)"
                          :disabled-date="time => disabledDate(time, child)"
                          format="YYYY-MM-DD HH:mm"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          @clear="handleDateClear(child)"
                        />
                        <!-- 不带时分 -->
                        <el-date-picker
                          style="width: 100%"
                          v-if="child.domType === 'DatePicker'"
                          v-model="form[child.key]"
                          type="date"
                          :placeholder="child.placeholder"
                          :disabled="child.disabled"
                          :disabled-date="time => disabledDate(time, child)"
                          @change="handleDateChange(child)"
                          @clear="handleDateClear(child)"
                        />
                        <el-input
                          v-if="child.domType === 'arrowRight'"
                          v-model="form[child.key]"
                          :placeholder="child.placeholder"
                          :suffix-icon="ArrowRight"
                          readonly
                          :disabled="child.disabled"
                          @focus="handleFoucs(child)"
                        >
                        </el-input>
                        <el-button
                          class="formBtn"
                          v-if="child.domType === 'button'"
                          :type="child.buttonType"
                          @click="handleButtonClick(child)"
                          >{{ child.buttonTxt }}</el-button
                        >

                        <!-- 搜索下拉框  :remote-method="query => searchSelectList(query, child)"  remote-->
                        <el-select
                          v-model="form[child.key]"
                          v-if="child.domType === 'SearchSelect'"
                          filterable
                          :allow-create="child.allowCreate"
                          :reserve-keyword="false"
                          placeholder="请输入关键词搜索"
                          :loading="searchLoadingStates[child.key]"
                          :disabled="child.disabled"
                        >
                          <el-option
                            v-for="item in searchOptions[child.key] || []"
                            :key="item.id"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                      <div v-if="child.domType === 'Div'" class="divClass">
                        <div v-if="child.key == 'information'" class="desBox">
                          <div class="title">{{ child.title }}：</div>
                          <div class="informationBox">
                            <div v-for="(item, index) in child.informationList" :key="index">
                              {{ item.name }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </template>
              </el-row>
            </div>
          </el-row>
        </div>
        <el-row v-if="props.idsObj.appointmentBizId">
          <el-col>
            <div class="tabButton">
              <!-- <el-button
                type="primary"
                icon="RefreshRight"
                @click="resetForm"
                size="large"
                :disabled="editStatus"
                >重置</el-button
              > -->
              <el-button
                type="primary"
                icon="Check"
                @click="submitForm"
                size="large"
                :disabled="editStatus"
                >提交</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- <div v-else class="domEmpty" v-loading="loading"></div> -->
    <Phone
      @close="handleCloseDrawer"
      :showDrawer="showPhoneDrawer"
      :drawerInfo="drawerInfo"
      :phoneMenuList="phoneMenuList"
      :phoneQuickList="phoneQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Address
      @close="handleCloseDrawer"
      :showAddressDrawer="showAddressDrawer"
      :drawerInfo="drawerInfo"
      :addressMenuList="addressMenuList"
      :addressQuickList="addressQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Country
      :showCountryDrawer="showCountryDrawer"
      @close="handleCloseDrawer"
      @confirmCountry="confirmDrawer"
    />
  </div>
</template>
<script setup name="appointmentInfo">
import dayjs from 'dayjs'
import { ArrowRight } from '@element-plus/icons-vue'
import appointmentDomData from '@/formJson/appointmentInfo'
import Country from '@/views/components/country'
import Phone from '@/views/components/phone'
import Address from '@/views/components/address'

import { watch, nextTick } from 'vue'
import { getCustomerDetail } from '@/api/sign/fna'
import { editAppointmentInfo, newPolicy } from '@/api/sign/appointment'
import useDictStore from '@/store/modules/dict'

const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  apiAppointmentInfoDto: { type: Object, default: () => ({}) }, //父组件传递过来的预约信息的详情
  appointmentStatus: { type: Number }, //父组件传递过来的预约的状态
  customerBizId: { type: String, default: '' } //提交状态，新增、修改
})
const emit = defineEmits(['handleSuccessEdit'])
const { proxy } = getCurrentInstance()
// const { csf_id_type, sys_gender } = proxy.useDict('csf_id_type', 'sys_gender')
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 consultKey = ref({})
const openAccountKey = 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',
  'residenceAddress',
  'companyAddress'
]) // 存储需要删除的key
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
const data = reactive({
  form: {},
  processedAppointmentData: [], // 处理后的表单数据
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedAppointmentData, queryParams, oldAppointmentData } = toRefs(data)
// 搜索方法
const searchSelectList = async (query, field) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[field.key] = true

  try {
    // 根据不同的字段key调用不同的API
    if (field.key === 'bankName') {
      console.log('searchOptions.value[field.key]', searchOptions.value[field.key])
    }
  } catch (error) {
    console.error(`${field.label} 搜索失败`, error)
    searchOptions.value[field.key] = []
  } finally {
    searchLoadingStates.value[field.key] = false
  }
}
const disabledDate = (time, child) => {
  // 获取“今天”的日期，并将其时间部分设置为 00:00:00
  const today = dayjs().startOf('day') // :cite[7]

  // 将传入的 timestamp 转换为 dayjs 对象
  const inputDate = dayjs(time)

  switch (child.key) {
    case 'intentionAppointmentTime':
      // 默认禁用今天及今天之前
      return inputDate.isBefore(today, 'day') || inputDate.isSame(today, 'day')
      break
    case 'arrivalTime':
      // 如果允许选择今天，只禁用今天之前的日期
      return inputDate.isBefore(today, 'day')
      break
    case 'departureTime':
      // 获取开始日期（需要从表单数据中获取）
      const startTime1 = form.value.arrivalTime
      if (startTime1) {
        const arrivalDate = dayjs(startTime1).startOf('day')
        // 只禁用到达日期之前的日期，允许选择同一天
        return inputDate.isBefore(arrivalDate, 'day')
      } else {
        // 如果没有选择到达时间，禁用今天之前的日期
        return inputDate.isBefore(today, 'day')
      }
      break
    case 'confirmAppointmentTime':
      return inputDate.isBefore(today, 'day')
      break
    case 'openAccountStartTime':
      return time.getTime() > Date.now()
      break
    case 'openAccountEndTime':
      // 获取开始日期（需要从表单数据中获取）
      const startTime = form.value.openAccountStartTime
      if (startTime) {
        const startDate = dayjs(startTime).startOf('day')
        // 禁用开始日期之前的所有日期（包括开始日期当天）
        return inputDate.isBefore(startDate, 'day') || inputDate.isSame(startDate, 'day')
      } else {
        // 如果没有选择开始日期，禁用今天之前的日期
        return inputDate.isBefore(today, 'day')
      }
      break

    default:
      // return time.getTime() > Date.now()
      break
  }
}

const handleButtonClick = child => {
  if (child.key == 'newPolicyButton') {
    let obj = {
      appointmentBizId: props.idsObj.appointmentBizId,
      confirmAppointmentTime: form.value.confirmAppointmentTime
    }
    newPolicy(obj).then(response => {
      if (response.code == 200) {
        proxy.$modal.msgSuccess('新单已生成')
        emit('handleSuccessEdit')
      }
    })
  }
}
const handleDateClear = child => {
  if (child.key == 'openAccountStartTime' && !form.value['openAccountStartTime']) {
    form.value['openAccountEndTime'] = ''
    resetShow({ type: 'child', key: 'openAccountEndTime', status: true, flag: 'disabled' })
    return
  }
  if (child.key == 'arrivalTime' && !form.value['arrivalTime']) {
    form.value['departureTime'] = ''
    resetShow({ type: 'child', key: 'departureTime', status: true, flag: 'disabled' })
    return
  }
}
const handleDateChange = child => {
  if (child.key == 'openAccountStartTime' && form.value['openAccountStartTime']) {
    resetShow({ type: 'child', key: 'openAccountEndTime', status: false, flag: 'disabled' })
    disabledDate(form.value['openAccountStartTime'], { key: 'openAccountEndTime' })

    return
  }
  if (child.key == 'arrivalTime' && form.value['arrivalTime']) {
    resetShow({ type: 'child', key: 'departureTime', status: false, flag: 'disabled' })
    disabledDate(form.value['arrivalTime'], { key: 'departureTime' })
  }
  if (child.key === 'confirmAppointmentTime' && form.value[child.key]) {
    if (form.value['arrivalTime']) {
      const appointmentTimestamp = dayjs(form.value['confirmAppointmentTime']).valueOf()
      const arrivalTimestamp = dayjs(form.value['arrivalTime']).valueOf()
      if (appointmentTimestamp < arrivalTimestamp) {
        proxy.$modal.msgError('预约时间早于到港时间,请重新选择预约时间')
        form.value['confirmAppointmentTime'] = ''
        return
      } else if (appointmentTimestamp > arrivalTimestamp) {
      } else {
        proxy.$modal.msgError('预约时间应晚于到港时间,请重新选择预约时间')
        form.value['confirmAppointmentTime'] = ''
        return
      }
    }
    resetShow({ type: 'child', key: 'newPolicyButton', status: true, flag: 'show' })
  } else if (child.key === 'confirmAppointmentTime' && !form.value[child.key]) {
    resetShow({ type: 'child', key: 'newPolicyButton', status: false, flag: 'show' })
  } else if (child.key === 'arrivalTime') {
    if (form.value['confirmAppointmentTime']) {
      const appointmentTimestamp = dayjs(form.value['confirmAppointmentTime']).valueOf()
      const arrivalTimestamp = dayjs(form.value['arrivalTime']).valueOf()
      if (appointmentTimestamp < arrivalTimestamp) {
        proxy.$modal.msgError('预约时间早于到港时间,请重新选择到港时间')
        form.value['arrivalTime'] = ''
        form.value['departureTime'] = ''
        resetShow({ type: 'child', key: 'departureTime', status: true, flag: 'disabled' })
      } else if (appointmentTimestamp > arrivalTimestamp) {
        console.log('预约时间晚于到港时间')
      } else {
        proxy.$modal.msgError('到港时间应早于预约时间,请重新选择到港时间')
        form.value['arrivalTime'] = ''
        form.value['departureTime'] = ''
        resetShow({ type: 'child', key: 'departureTime', status: true, flag: 'disabled' })
      }
    }
  } else if (child.key === 'confirmAppointmentTime') {
    if (form.value['arrivalTime']) {
      const appointmentTimestamp = dayjs(form.value['confirmAppointmentTime']).valueOf()
      const arrivalTimestamp = dayjs(form.value['arrivalTime']).valueOf()
      console.log('appointmentTimestamp', appointmentTimestamp)
      console.log('arrivalTimestamp', arrivalTimestamp)
    }
  }
}
// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        // options = item.dictItemList
        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 []
  }
}
// 添加英文校验函数
const validateEnglish = (rule, value, callback) => {
  if (value && !/^[A-Za-z]*$/.test(value)) {
    // 清空非英文字符
    form.value.firstNamePinyin = ''
    callback(new Error('只能输入英文字母'))
  } else {
    callback()
  }
}

// 处理表单配置，添加字典数据
const processFormData = async () => {
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(appointmentDomData))

  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (section.key == 'openAccount') {
          openAccountKey.value[field.key] = field.key
        }
        if (section.key == 'consult') {
          consultKey.value[field.key] = field.key
        }
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
        if (field.key == 'bankName') {
          searchOptions.value[field.key] = fetchDictData(field.dictType)
        }
        if (field.required) {
          if (field.key === 'firstNamePinyin') {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' },
              { validator: validateEnglish, trigger: 'change' }
            ]
          } else {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
            ]
          }
        }
      }
    }
  }

  if (props.idsObj.appointmentBizId) {
    editStatus.value = true
    setFormValue(props.apiAppointmentInfoDto, processedData)
  } else {
    editStatus.value = false
    processedAppointmentData.value = processedData
  }
}

//弹出右侧抽屉
const handleFoucs = child => {
  if (child.disabled) return
  console.log('saveKey.value', saveKey.value)

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

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

        if (existingIndex !== -1) {
          // 更新已存在的电话
          phoneQuickList.value[existingIndex] = {
            code: newObj[drawerInfo.value.code],
            mobile: newObj[drawerInfo.value.key],
            key: drawerInfo.value.key,
            phoneString: newObj.phoneString
          }
        } else {
          // 添加新的快捷电话
          phoneQuickList.value.push({
            code: newObj[drawerInfo.value.code],
            mobile: newObj[drawerInfo.value.key],
            key: drawerInfo.value.key,
            phoneString: newObj.phoneString
          })
        }
        phoneQuickList.value = removeDuplicates(phoneQuickList.value, 'phoneString')
        break
      case 'address':
        newObj.objType = drawerInfo.value.drawerType
        newObj.type = drawerInfo.value.key
        form.value[info.key] = `${newObj.region} ${newObj.city} ${newObj.street} ${newObj.location}`
        saveKey.value[info.key] = newObj
        break
      case 'country':
        info.objType = drawerInfo.value.drawerType
        form.value[drawerInfo.value.key] = info.name
        saveKey.value[drawerInfo.value.key] = info
        break
      default:
        break
    }
  }

  handleCloseDrawer()
}
// 根据联动重置表单项的显示与否 是否禁用
const resetShow = obj => {
  for (const section of processedAppointmentData.value) {
    if (obj.type == 'father' && section.key == obj.key) {
      section.showMoudle = obj.status
      // if (!obj.status) {
      //   if (section.data) {
      //     for (const field of section.data) {
      //       form.value[field.key] = ''
      //     }
      //   }
      // }
    } else if (obj.type == 'child') {
      if (section.data) {
        for (const field of section.data) {
          if (field.key == obj.key && obj.flag == 'show') {
            // 获取字典数据
            field.show = obj.status
          } else if (field.key == obj.key && obj.flag == 'disabled') {
            field.disabled = obj.status
          }
        }
      }
    }
  }
}
const handleSelectChange = (father, child) => {
  switch (child.key) {
    case 'isAccompany':
      // 选择吸烟，展示吸烟数量
      if (form.value[child.key] == '1') {
        resetShow({ type: 'father', key: 'consult', status: true })
      } else {
        resetShow({ type: 'father', key: 'consult', status: false })
      }

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

      break

    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = status => {
  editStatus.value = status
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedAppointmentData.value))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (editStatus.value) {
          field.disabled = true
        } else {
          if (!form.value['openAccountStartTime'] && field.key == 'openAccountEndTime') {
            field.disabled = true
          } else if (!form.value['arrivalTime'] && field.key == 'departureTime') {
            field.disabled = true
          } else {
            field.disabled = false
          }
        }
      }
    }
  }
  processedAppointmentData.value = processedData
}
//给表单赋值 方便表单回显 obj 为表单数据
const setFormValue = (obj, formData) => {
  let tempPhoneList = []
  let tempAddressList = []
  addressQuickList.value = []
  phoneQuickList.value = []
  // 深拷贝原始数据
  form.value = JSON.parse(JSON.stringify(obj))
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(formData))
  for (const section of processedData) {
    if (obj.isOpenAccount === 1 && section.key == 'openAccount') {
      section.showMoudle = true
    }
    if (obj.isAccompany === 1 && section.key == 'consult') {
      section.showMoudle = true
    }

    if (section.data) {
      for (const field of section.data) {
        if (field.key == 'confirmAppointmentTime' && props.appointmentStatus !== 0) {
          field.show = true
        }
        if (obj.confirmAppointmentTime && field.key == 'newPolicyButton') {
          field.show = true
        }
        if (props.apiAppointmentInfoDto.appointmentBizId) {
          field.disabled = true
        } else {
          field.disabled = false
        }
        if (field.key == 'bankName') {
          searchOptions.value[field.key] = fetchDictData(field.dictType)
        }
        // 处理时间
        if (field.key == 'openAccountEndTime' && obj[field.key]) {
          // 开始时间是否在结束时间之前
          if (
            obj['openAccountStartTime'] &&
            !dayjs(obj['openAccountStartTime']).isBefore(dayjs(obj[field.key]))
          ) {
            form.value[field.key] = ''
            field.disabled = true
          }
        }
        if (field.key == 'departureTime' && obj[field.key]) {
          // 开始时间是否在结束时间之前
          if (obj['arrivalTime'] && !dayjs(obj['arrivalTime']).isBefore(dayjs(obj[field.key]))) {
            form.value[field.key] = ''
            field.disabled = true
          }
        }
        //要判断drawerType,因为抽屉要回显数据
        switch (field.drawerType) {
          case 'phone':
            let phoneObj = {}
            for (const key1 in field) {
              for (const key2 in obj) {
                if (key1 !== 'drawerType' && field[key1] == key2) {
                  if (key1 == 'code' && obj[key2]) {
                    phoneObj[field[key1]] = obj[key2].includes('+') ? obj[key2] : `+${obj[key2]}`
                  } else {
                    phoneObj[field[key1]] = obj[key2]
                  }
                }
              }
            }

            if (phoneObj[field.key]) {
              phoneObj.phoneString = form.value[field.key] = `${phoneObj[field.code]} ${
                phoneObj[field.key]
              }`
              tempPhoneList.push(phoneObj)
            }
            phoneObj.objType = field.drawerType
            phoneObj.key = field.key
            phoneObj.phoneCode = field.code
            saveKey.value[field.key] = phoneObj
            break
          case 'address':
            let addressObj = null
            for (const key1 in field) {
              if (obj.addressList && obj.addressList.length > 0) {
                obj.addressList.forEach(item => {
                  if (key1 == item.type) {
                    addressObj = item
                  }
                })
              }
            }

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

            break
          case 'country':
            form.value[field.key] = obj.countryName
            saveKey.value[field.key] = {
              country: obj.country || '',
              countryCode: obj.country || '',
              countryName: obj.countryName || '',
              name: obj.countryName || '',
              objType: field.drawerType
            }
            break
          default:
            break
        }
      }
    }
  }
  addressQuickList.value = tempAddressList
  tempPhoneList.forEach(item => {
    for (const key in saveKey.value) {
      if (item.key == key) {
        for (const key2 in saveKey.value[key]) {
          if (item.key == key2) {
            item.mobile = saveKey.value[key][key2]
          }
          if (item.phoneCode == key2) {
            item.code = saveKey.value[key][key2]
          }
        }
      }
    }
  })

  phoneQuickList.value = removeDuplicates(tempPhoneList, 'phoneString')
  addressQuickList.value = removeDuplicates(tempAddressList, 'addressString')
  processedAppointmentData.value = oldAppointmentData.value = processedData
  oldObjInfo.value = JSON.parse(JSON.stringify(form.value))
}
// 数组去重
function removeDuplicates(arr, key) {
  const seen = new Map()
  const result = []

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

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

// 处理表单填写得数据
const handleFormValues = () => {
  let submitObj = { ...form.value }
  const pattern = /Time$/ // 以Time结尾

  //处理表单数据
  for (const key1 in form.value) {
    // 不开户去除开户相关信息
    if (key1 == 'isOpenAccount' && form.value[key1] === 0) {
      for (const key4 in openAccountKey.value) {
        delete submitObj[key4]
      }
    }
    // 没顾问去除顾问相关信息
    if (key1 == 'isAccompany' && form.value[key1] === 0) {
      for (const key5 in consultKey.value) {
        delete submitObj[key5]
      }
    }
    if (pattern.test(key1) && form.value[key1]) {
      submitObj[key1] = proxy.formatToDateTime(form.value[key1])
    }
    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
      }
    }
  }

  return submitObj
}
// 表单提交
const submitForm = () => {
  // return
  proxy.$refs['appointmentInfoFormRef'].validate((valid, fields) => {
    if (valid) {
      let submitObj = handleFormValues()
      console.log('====================================')
      console.log('submitObj', submitObj)
      console.log('====================================')
      // return

      if (props.idsObj.appointmentBizId) {
        editAppointmentInfo(submitObj).then(res => {
          if (res.code == 200) {
            handleEditStatus(true)
            proxy.$message.success('预约信息修改成功')
            emit('handleSuccessEdit')
          }
        })
      }
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}
const resetForm = () => {
  proxy.$modal
    .confirm('是否确认撤销所作操作？')
    .then(function () {
      form.value = { ...oldObjInfo.value }
      editStatus.value = true
      processedAppointmentData.value = JSON.parse(JSON.stringify(oldAppointmentData.value))
      proxy.$refs['appointmentInfoFormRef'].resetFields()
    })

    .catch(() => {})
}
// 获取流程详情
function getCustomerInfo(customerBizId, formData) {
  getCustomerDetail(customerBizId).then(async res => {
    if (res.code == 200) {
      // 回显值
      setFormValue(res.data, formData)
    }
  })
}

watch(
  () => props.activeName,
  newVal => {
    if (newVal === 'appointmentInfo') {
      openList.value = false
      setTimeout(() => {
        processFormData()
      }, 500)
    }
  }
)
watch(
  () => props.formStatus,
  newVal => {
    if (newVal === 'appointmentEdit') {
      openList.value = false
      processFormData()
    }
  }
)
// 暴露给父组件
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: space-between;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .inputBox {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 0px 11px;
    .rightArrow {
      font-size: 14px;
      color: #a8abb2;
    }
  }
  .desBox {
    .title {
      width: 120px;
      font-size: 14px;
      text-align: left;
      margin-bottom: 10px;
      color: #606266;
      font-weight: 700;
    }
    .informationBox {
      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: 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 only screen and (min-width: 768px) {
  .formBtn {
    margin-top: 0 !important;
  }
}

@media only screen and (min-width: 1200px) {
  .formBtn {
    margin-top: 30px !important;
  }
}
</style>
