<template>
  <div v-if="processedAppointmentData.length > 0">
    <div ref="appointmentRef">
      <CommonForm
        :anchorList="anchorList"
        :affixOffset="360"
        :anchorOffset="10"
        :scrollContainerSelector="anchorContainer"
        :scrollOffset="10"
        :domIndex="tabIndex"
        :activeName="activeName"
        v-if="appointmentRef"
      >
        <template #form-right>
          <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" :id="father.anchorKey">
                <div class="formBox">
                  <CardOne :title="father.fatherTitle">
                    <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="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"
                                  :rows="child.rows"
                                  :disabled="editStatus"
                                />
                                <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>
                                <!-- 带时分的时间框 -->
                                <div
                                  v-if="child.domType === 'datetimePicker'"
                                  class="compositionDateTime"
                                >
                                  <el-date-picker
                                    type="date"
                                    placeholder="选择日期"
                                    style="width: 100%"
                                    v-model="form[child.key]"
                                    :disabled="editStatus"
                                    @change="handleDateChange(child)"
                                    :disabled-date="time => disabledDate(time, child)"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    @clear="handleDateClear(child)"
                                  />
                                  <span class="text-gray-500">-</span>
                                  <el-time-picker
                                    placeholder="选择时分"
                                    style="width: 100%"
                                    v-model="child.timeValue"
                                    :disabled="editStatus"
                                    format="HH:mm"
                                    value-format="HH:mm"
                                  />
                                </div>
                                <!-- 不带时分 -->
                                <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)"
                                  @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="editStatus"
                                  @focus="handleFoucs(child)"
                                >
                                </el-input>
                                <el-button
                                  class="formBtn"
                                  v-if="child.domType === 'button'"
                                  :type="child.buttonType"
                                  @click="handleButtonClick(child)"
                                  >{{ child.buttonTxt }}</el-button
                                >

                                <el-select
                                  v-model="form[child.key]"
                                  v-if="child.domType === 'SearchSelect'"
                                  filterable
                                  :allow-create="child.allowCreate"
                                  reserve-keyword
                                  @change="handleSelectChange(father, child)"
                                  :remote-method="query => searchSelectList(query, child.key)"
                                  placeholder="请输入关键词搜索"
                                  :loading="searchLoadingStates[child.key]"
                                  :disabled="editStatus"
                                >
                                  <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>
                      <!-- 是表格数据 -->
                      <el-row v-if="father.showTable">
                        <el-col :span="24" v-if="father.addChildren">
                          <el-button
                            :disabled="editStatus"
                            type="primary"
                            icon="Plus"
                            size="small"
                            style="margin-bottom: 10px"
                            @click="addChildren(father)"
                            >{{ father.addChildrenTxt }}</el-button
                          >
                        </el-col>
                        <el-table :data="father.data" border v-if="father.data.length > 0">
                          <template v-if="father.key == 'referrerDtoList'">
                            <el-table-column label="姓名" prop="realName" align="center">
                              <template #header>
                                <span class="required-label">姓名</span>
                              </template>
                              <template #default="scope">
                                <el-select
                                  v-model="scope.row.realName"
                                  filterable
                                  remote
                                  reserve-keyword
                                  placeholder="请输入关键词搜索"
                                  :remote-method="query => searchSelectList(query, 'realName')"
                                  :loading="searchLoadingStates['realName']"
                                  :disabled="editStatus"
                                >
                                  <el-option
                                    v-for="item in searchOptions['realName'] || []"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                  />
                                </el-select>
                              </template>
                            </el-table-column>
                            <el-table-column label="手机号" prop="phone" align="center">
                              <template #header>
                                <span class="required-label">手机号</span>
                              </template>
                              <template #default="scope">
                                <el-input
                                  v-model="scope.row.phone"
                                  size="default"
                                  placeholder="请输入"
                                  :disabled="editStatus"
                                />
                              </template>
                            </el-table-column>
                            <el-table-column label="邮箱" prop="email" align="center">
                              <template #header>
                                <span class="required-label">邮箱</span>
                              </template>
                              <template #default="scope">
                                <el-input
                                  v-model="scope.row.email"
                                  size="default"
                                  placeholder="请输入"
                                  :disabled="editStatus"
                                />
                              </template>
                            </el-table-column>
                            <el-table-column width="60px" align="center" label="操作">
                              <template #default="scope">
                                <el-icon
                                  class="deleteIcon"
                                  @click="deleteChildren(father, scope.$index)"
                                  ><Delete
                                /></el-icon>
                              </template>
                            </el-table-column>
                          </template>
                          <template v-if="father.key == 'userSignDtoList'">
                            <el-table-column label="姓名" prop="name" align="center">
                              <template #header>
                                <span class="required-label">姓名</span>
                              </template>
                              <template #default="scope">
                                <el-select
                                  v-model="scope.row.name"
                                  filterable
                                  remote
                                  reserve-keyword
                                  placeholder="请选择"
                                  :remote-method="query => searchSelectList(query, 'name')"
                                  :loading="searchLoadingStates['name']"
                                  :disabled="editStatus"
                                >
                                  <el-option
                                    v-for="item in searchOptions['name'] || []"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                  />
                                </el-select>
                              </template>
                            </el-table-column>
                            <el-table-column label="手机号" prop="phone" align="center">
                              <template #header>
                                <span class="required-label">手机号</span>
                              </template>
                              <template #default="scope">
                                <el-input
                                  v-model="scope.row.phone"
                                  size="default"
                                  placeholder="请输入"
                                  :disabled="editStatus"
                                />
                              </template>
                            </el-table-column>
                            <el-table-column label="执业编码" prop="practiceCode" align="center">
                              <template #header>
                                <span class="required-label">执业编码</span>
                              </template>
                              <template #default="scope">
                                <el-input
                                  v-model="scope.row.practiceCode"
                                  size="default"
                                  placeholder="请输入"
                                  :disabled="editStatus"
                                />
                              </template>
                            </el-table-column>
                            <el-table-column label="邮箱" prop="email" align="center">
                              <template #default="scope">
                                <el-input
                                  v-model="scope.row.email"
                                  size="default"
                                  placeholder="请输入"
                                  :disabled="editStatus"
                                />
                              </template>
                            </el-table-column>

                            <el-table-column label="证件类型" prop="cardType" align="center">
                              <template #default="scope">
                                <el-select
                                  v-model="scope.row.cardType"
                                  placeholder="请选择"
                                  :disabled="editStatus"
                                  clearable
                                >
                                  <el-option
                                    v-for="item in fetchDictData('csf_id_type')"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                  />
                                </el-select>
                              </template>
                            </el-table-column>
                            <el-table-column label="证件号" prop="cardNo" align="center">
                              <template #default="scope">
                                <el-input
                                  v-model="scope.row.cardNo"
                                  size="default"
                                  placeholder="请输入"
                                  :disabled="editStatus"
                                />
                              </template>
                            </el-table-column>
                            <el-table-column width="60px" align="center" label="操作">
                              <template #default="scope">
                                <el-icon
                                  @click="deleteChildren(father, scope.$index)"
                                  class="deleteIcon"
                                  ><Delete
                                /></el-icon>
                              </template>
                            </el-table-column>
                          </template>
                        </el-table>
                      </el-row>
                    </template>
                  </CardOne>
                </div>
              </el-row>
            </div>
          </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"
    />
  </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 { editAppointmentInfo, newPolicy } from '@/api/sign/appointment'
import { getBankList, getAllSignList, getUserSaleExpandList } from '@/api/common'
import CommonForm from '@/views/components/commonForm'
import CardOne from '@/components/formCard/cardOne'
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: '' }, //提交状态，新增、修改
  fatherTabName: { type: String, default: '' }, //一级tab名称
  anchorContainer: { type: String, default: '' }, //锚点滚动容器
  editStatus: { type: Boolean, default: true }, //编辑状态
  tabIndex: { type: [String, Number], default: '' } //tab索引
})
const emit = defineEmits(['handleSuccessEdit'])
const { proxy } = getCurrentInstance()
const appointmentRef = 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 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)
// 添加表单子级dom
const addChildren = father => {
  const processedData = JSON.parse(JSON.stringify(processedAppointmentData.value))

  let obj4 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    email: '',
    phone: '',
    realName: ''
  }
  let obj5 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    name: '', //姓名
    practiceCode: '', //执业编码
    phone: '', //手机号
    cardType: '', //证件类型
    cardNo: '', //证件号码
    email: '' //邮箱
  }

  for (const section of processedData) {
    if (father.key == 'referrerDtoList' && section.key == father.key) {
      section.data.push(obj4)
    }
    if (father.key == 'userSignDtoList' && section.key == father.key) {
      section.data.push(obj5)
    }
  }
  //更新form表单对应的数据，以便收集填写的值
  // form.value[father.key].push(obj)
  processedAppointmentData.value = processedData
}
const deleteChildren = (father, childIndex) => {
  if (props.editStatus.value) {
    proxy.$modal.confirm(`请先点击编辑再进行删除操作`, { showCancel: '0', title: '填写提示' })
    return
  }
  const processedData = JSON.parse(JSON.stringify(processedAppointmentData.value))
  for (const section of processedData) {
    if (father.key == 'referrerDtoList' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
    if (father.key == 'userSignDtoList' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
  }
  processedAppointmentData.value = processedData
}
// 搜索方法
const searchSelectList = async (query, key) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[key] = true
  let queryString = query.trim()
  try {
    // 根据不同的字段key调用不同的API
    if (key === 'bankName') {
      const params4 = {
        pageNo: 1,
        pageSize: 10,
        queryContent: queryString
      }
      const response4 = await getBankList(params4)
      if (response4.code == 200) {
        response4.data.records = response4.data.records.map(item => {
          return {
            ...item,
            label: item.bankName,
            value: item.bankBizId
          }
        })
        searchOptions.value[key] = response4.data.records
      }
    } else if (key == 'realName') {
      const params5 = {
        pageNo: 1,
        pageSize: 10,
        queryContent: queryString
      }
      const response5 = await getUserSaleExpandList(params5)
      if (response5.code == 200) {
        response5.data.records = response5.data.records.map(item => {
          return {
            ...item,
            label: item.realName,
            value: item.userSaleBizId
          }
        })
        searchOptions.value[key] = response5.data.records
      }
    } else if (key == 'name') {
      const params5 = {
        pageNo: 1,
        pageSize: 10,
        realName: queryString
      }
      const response5 = await getAllSignList(params5)
      if (response5.code == 200) {
        response5.data.records = response5.data.records.map(item => {
          return {
            ...item,
            label: item.realName,
            value: item.userSignBizId
          }
        })
        searchOptions.value[key] = response5.data.records
      }
    }
  } catch (error) {
    console.error(` 搜索失败`, error)
    searchOptions.value[key] = []
  } finally {
    searchLoadingStates.value[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 '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' })
  }

  // 离港时间在到港时间之前
  if (
    child.key == 'arrivalTime' &&
    form.value['departureTime'] &&
    !dayjs(form.value['arrivalTime']).isBefore(dayjs(form.value['departureTime']))
  ) {
    proxy.$message.error('到港时间应在离港时间之前！！')
  }
  if (
    child.key == 'departureTime' &&
    form.value['arrivalTime'] &&
    dayjs(form.value['departureTime']).isBefore(dayjs(form.value['arrivalTime']))
  ) {
    proxy.$message.error('离港时间应在到港时间之后！！')
  }
  if (child.key === 'confirmAppointmentTime' && !form.value[child.key]) {
    resetShow({ type: 'child', key: 'newPolicyButton', status: false, flag: 'show' })
  } else if (child.key === 'confirmAppointmentTime' && form.value[child.key]) {
    resetShow({ type: 'child', key: 'newPolicyButton', status: true, flag: 'show' })
  }
}
// 获取字典数据
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] = dictStore.bankList
        }
        if (field.key == 'realName') {
          searchOptions.value[field.key] = dictStore.userSaleExpandList
        }
        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 {
    // 新增给默认值
    form.value['isReferrerAccompany'] = form.value['isOpenAccount'] = form.value['isUseCar'] = 0
    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 'isReferrerAccompany':
      // 选择吸烟，展示吸烟数量
      if (form.value[child.key] == '1') {
        resetShow({ type: 'father', key: 'referrerDtoList', status: true })
      } else {
        resetShow({ type: 'father', key: 'referrerDtoList', 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
    case 'bankName':
      // 选择吸烟，展示吸烟数量
      if (form.value[child.key]) {
        if (
          searchOptions.value[child.key].findIndex(item => item.value == form.value[child.key]) !==
          -1
        ) {
          searchOptions.value[child.key].forEach(item => {
            if (item.value == form.value[child.key]) {
              form.value['materials'] = item.materials
            }
          })
        } else {
          form.value['materials'] = ''
        }
      }

      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 = () => {
  return new Promise(resolve => {
    let submitObj = { ...form.value }
    const pattern = /Time$/

    proxy.$refs['appointmentInfoFormRef'].validate((valid, fields) => {
      if (valid) {
        errorFields.value = [] // 清空错误信息
        //处理表单数据
        for (const key1 in form.value) {
          // 不开户去除开户相关信息
          if (key1 == 'isOpenAccount' && form.value[key1] == 0) {
            for (const key4 in openAccountKey.value) {
              delete submitObj[key4]
            }
          }

          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
            }
          }
        }
        if (submitObj['bankName']) {
          searchOptions.value['bankName'].forEach(item => {
            if (submitObj['bankName'] == item.bankBizId) {
              submitObj['bankName'] = item.bankName
            }
          })
        }

        let obj = {
          realName: '转介人姓名',
          phone: '转介人手机',
          email: '转介人邮箱'
        }
        let obj1 = {
          name: '签单员姓名',
          phone: '签单员电话',
          practiceCode: '签单员执业编码'
        }
        processedAppointmentData.value.forEach(item => {
          if (item.key == 'referrerDtoList') {
            if (form.value['isReferrerAccompany'] == 1 && item.data.length > 0) {
              submitObj['referrerDtoList'] = item.data.map((item1, index) => {
                if (item1.realName) {
                  searchOptions.value['realName'].forEach(item2 => {
                    if (item1.realName == item2.userSaleBizId) {
                      item1.realName = item2.realName
                    }
                  })
                }
                for (const key in item1) {
                  if (!item1[key]) {
                    errorFields.value.push({
                      message: `陪同转介人-第${index + 1}行${obj[key]}不能为空`
                    })
                  }
                }
                return {
                  realName: item1.realName,
                  phone: item1.phone,
                  email: item1.email
                }
              })
            } else if (form.value['isReferrerAccompany'] == 1 && item.data.length == 0) {
              errorFields.value.push({
                message: '签约信息模块--转介人陪同时，陪同转介人信息不能为空！！'
              })
            }
          }
          if (item.key == 'position') {
            item.data.forEach((item1, index) => {
              if (item1.compositionTime) {
                if (item1.timeValue) {
                  submitObj[item1.key] = form.value[item1.key] + ' ' + item1.timeValue + ':00'
                } else {
                  submitObj[item1.key] = form.value[item1.key] + ' 00:00:00'
                }
              }
            })
          }
          if (item.key == 'userSignDtoList' && item.data.length > 0) {
            submitObj['userSignDtoList'] = item.data.map((item1, index) => {
              if (item1.name) {
                searchOptions.value['name'].forEach(item2 => {
                  if (item1.name == item2.userSignBizId) {
                    item1.name = item2.realName
                  }
                })
              }
              for (const key in item1) {
                if (!item1[key]) {
                  errorFields.value.push({
                    message: `签单员-第${index + 1}行${obj1[key]}不能为空`
                  })
                }
              }
              return {
                name: item1.name,
                phone: item1.phone,
                email: item1.email,
                practiceCode: item1.practiceCode,
                cardType: item1.cardType,
                cardNo: item1.cardNo
              }
            })
          }
        })
        console.log('submitObj', submitObj)
        if (submitObj['departureTime']) {
          // 开始时间是否在结束时间之前
          if (
            submitObj['arrivalTime'] &&
            !dayjs(submitObj['arrivalTime']).isBefore(dayjs(submitObj['departureTime']))
          ) {
            errorFields.value.push({
              message: '签约信息模块--离港时间必须晚于到港时间！！'
            })
            // return undefined
          }
        }

        if (errorFields.value.length > 0) {
          proxy.$message.error(errorFields.value[0].message)
        }
        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)
      }
    })
  })
}
const anchorList = computed(() => {
  let data = []
  for (const section of processedAppointmentData.value) {
    if (section.showMoudle) {
      data.push({ title: section.anchorKey, name: section.fatherTitle })
    }
  }
  return data
})
watch(
  () => props.activeName,
  newVal => {
    appointmentRef.value = null
    if (newVal === 'appointmentInfo') {
      openList.value = false
      processFormData()
    }
  }
)

// 因为tab嵌套了两层，所以需要监听父组件的tab否则锚点的显示就会有bug
watch(
  () => props.fatherTabName,
  newVal => {
    if (newVal) {
      appointmentRef.value = null
    }
  }
)
watch(
  () => props.formStatus,
  newVal => {
    if (newVal === 'appointmentEdit') {
      openList.value = false
      processFormData()
    }
  }
)
// 暴露给父组件
defineExpose({
  handleFormValues,
  handleEditStatus
})
</script>
<style lang="scss" scoped>
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.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;
  }
}
.deleteIcon {
  color: red;
  font-size: 18px;
  padding-top: 10px;
}
.compositionDateTime {
  display: flex;
  width: 100%;
  box-sizing: border-box;
}
@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>
