<template>
  <div v-if="processedAppointmentData.length > 0">
    <div>
      <CommonForm
        :showAnchor="false"
        :anchorList="anchorList"
        :affixOffset="affixOffset"
        :anchorOffset="10"
        :scrollContainerSelector="anchorContainer"
      >
        <template #form-right>
          <el-form ref="appointmentInfoFormRef" :model="form" 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 #mainTitCustom v-if="props.idsObj.appointmentBizId">
                      <div style="margin-left: 10px">
                        <el-button
                          @click="viewHistory"
                          type="primary"
                          link
                          v-if="father.key == 'administration'"
                          >历史记录</el-button
                        >
                      </div>
                    </template> -->
                    <!-- <template #headerRight v-if="father.key == 'administration'">
                      <div>
                        <el-button
                          v-if="idsObj.appointmentBizId"
                          @click="handleExprot"
                          type="primary"
                          link
                          >导出预约表</el-button
                        >
                        <el-button
                          v-if="appointmentStatus >= 2"
                          @click="getItineraryInfo"
                          type="primary"
                          link
                          >行程单预览</el-button
                        >
                      </div>
                    </template> -->
                    <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"
                                    @change="timeValueChange(child)"
                                  />
                                </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-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"
                                  @change="handleTableSelectChange(father, scope.row, 'realName')"
                                >
                                  <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"
                                  @change="handleTableSelectChange(father, scope.row, 'name')"
                                >
                                  <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 CommonPage from '@/components/commonPage'
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 DetailPanel from '@/components/DetailPanel'
import { watch, nextTick } from 'vue'
import {
  getAppointmentlog,
  getAppointmentlogDetail,
  getItineraryExprot,
  getItineraryDetail,
  getAppointmentExprot
} from '@/api/sign/appointment'
import { getBankList, getAllSignList, getUserSaleExpandList } from '@/api/common'
import CommonForm from '@/views/components/commonForm'
import CommonDialog from '@/components/commonDialog'
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对象
  detailInfo: { type: Object, default: () => ({}) }, //父组件传递过来的签约信息的详情
  appointmentStatus: { type: Number }, //父组件传递过来的预约状态
  customerBizId: { type: String, default: '' }, //提交状态，新增、修改
  fatherTabName: { type: String, default: '' }, //一级tab名称
  anchorContainer: { type: String, default: '' }, //锚点滚动容器
  editStatus: { type: Boolean, default: true }, //编辑状态

  affixOffset: { type: Number, default: 360 } //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 oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作
const consultKey = ref({})
const openAccountKey = ref({})
const openList = ref(false) //历史签约记录弹窗开关
const showDetail = ref(false) //签约详情弹窗开关
const detailTitle = ref('') //签约详情弹窗title
const detailInfo = ref({}) //签约详情信息
const tableData = ref([])
const tableLoading = ref([])
const itineraryData = ref([]) //行程单数据
const appointmentSummeryInfo = ref({}) //行程单数据
const exportLoading = ref(false) //下载行程单loading
const showItinerary = ref(false) //下载行程单loading
// 地址组件菜单数据
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 total = ref(0)
const data = reactive({
  form: {},
  processedAppointmentData: [], // 处理后的表单数据
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 10
  }
})
const { form, rules, processedAppointmentData, queryParams, oldAppointmentData } = toRefs(data)
// 获取预约行程单详情
function getItineraryInfo() {
  getItineraryDetail(props.idsObj.appointmentBizId).then(res => {
    if (res.code == 200) {
      appointmentSummeryInfo.value = res.data
      fetchDictData('csf_ap_meeting_point').forEach(item => {
        if (item.value == appointmentSummeryInfo.value.meetingPoint) {
          appointmentSummeryInfo.value.meetingPoint = item.label
        }
      })
      if (appointmentSummeryInfo.value.total) {
        appointmentSummeryInfo.value.total = Number(appointmentSummeryInfo.value.total).toFixed(2)
      }

      itineraryData.value = [
        {
          title: '集合信息',
          data: [
            // 第一行：2列布局（各占12）
            {
              label: '集合时间',
              value: appointmentSummeryInfo.value.arrivalTime,
              span: 12 // 占12/24
            },
            {
              label: '集合地点',
              value: appointmentSummeryInfo.value.meetingPoint,
              span: 12 // 占12/24
            },
            {
              label: '意向地点',
              value: appointmentSummeryInfo.value.signingAddress,
              span: 12 // 占12/24
            }
          ]
        },
        {
          title: '业务代表',
          data: [
            // 第一行：2列布局（各占12）
            {
              label: '业务代表',
              value: appointmentSummeryInfo.value.businessRepresentName1,
              span: 12 // 占12/24
            },
            {
              label: '联系电话',
              value: appointmentSummeryInfo.value.businessRepresentMobile1
                ? appointmentSummeryInfo.value.businessRepresentMobile1Code +
                  appointmentSummeryInfo.value.businessRepresentMobile1
                : '-',
              span: 12 // 占12/24
            }
          ]
        },
        {
          title: '咨询内容',
          data: [
            // 第一行：2列布局（各占12）
            {
              label: '咨询人',
              value: appointmentSummeryInfo.value.name,
              span: 12 // 占12/24
            },

            {
              label: '意向缴费年期',
              value: appointmentSummeryInfo.value.paymentTerm,
              span: 12 // 占12/24
            },
            {
              label: '保单征费',
              value: appointmentSummeryInfo.value.policyFee || '-',
              span: 12 // 占12/24
            },
            {
              label: '首期保费',
              value: appointmentSummeryInfo.value.eachIssuePremium || '-',
              span: 12 // 占12/24
            },
            {
              label: '币种',
              value: appointmentSummeryInfo.value.currency,
              span: 12 // 占12/24
            },
            {
              label: '意向咨询产品',
              value: appointmentSummeryInfo.value.productName,
              span: 12 // 占12/24
            },
            {
              label: '首期合计金额',
              value: appointmentSummeryInfo.value.total,
              span: 12 // 占12/24
            }
          ]
        }
      ]

      showItinerary.value = true
    }
  })
}
// 导出行程单Pdf
const handleExprotPdf = () => {
  exportLoading.value = true
  getItineraryExprot(appointmentSummeryInfo.value.appointmentBizId).then(res => {
    if (res.code == 200) {
      // 创建隐藏的下载链接
      const link = document.createElement('a')
      link.href = res.data
      link.target = '_blank' // 新窗口打开

      // 设置下载文件名（重要）
      // 从URL中提取文件名，或者使用返回的文件名
      const fileName = `香港行程安排.pdf`
      link.download = fileName

      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      exportLoading.value = false
      showItinerary.value = false
    } else {
      proxy.$message.error('行程单下载失败')
      exportLoading.value = false
    }
  })
}
//导出预约表
const handleExprot = async row => {
  try {
    const res = await getAppointmentExprot(props.idsObj.appointmentBizId)
    if (res.code == 200) {
      // 创建隐藏的下载链接
      const link = document.createElement('a')
      link.href = res.data.url
      // link.target = '_blank' // 新窗口打开

      // 设置下载文件名（重要）
      // 从URL中提取文件名，或者使用返回的文件名
      const fileName = '预约导出.xlsx'
      link.download = fileName

      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      proxy.$message.success('导出成功')
    }
  } catch (error) {
    console.error('导出失败:', error)
  }
}
const changePageNo = val => {
  queryParams.value.pageNo = val
  // getList()
}
const changePageSize = val => {
  queryParams.value.pageSize = val
  // getList()
}
const timeValueChange = child => {
  if (form.value[child.key]) {
    child.finishTime = `${form.value[child.key]} ${child.timeValue}:00`
  } else if (!form.value[child.key]) {
    proxy.$message.warning(`请先选择${child.label}日期`)
    child.timeValue = ''
  }
}
// 签约详情
const viewDetail = row => {
  try {
    getAppointmentlogDetail(row.appointmentLogBizId).then(response => {
      detailInfo.value = response.data
      detailTitle.value = `${row.creatorName}签约详情`
      showDetail.value = true
    })
  } catch (error) {
    detailTitle.value = ''
    detailInfo.value = {}
    showDetail.value = false
  }
}
// 签约历史记录
const viewHistory = () => {
  try {
    getAppointmentlog(queryParams.value).then(response => {
      tableData.value = response.data.records
      total.value = response.data.total
      tableLoading.value = false
      openList.value = true
    })
  } catch (error) {
    tableData.value = []
  } finally {
    tableLoading.value = false
  }
}
const handleTableSelectChange = (father, row, key) => {
  searchOptions.value[key].forEach(item => {
    if (row[key] == item.value) {
      row[key] = item.label
      row.userBizId = item.userBizId
      if (key == 'name') {
        row.userSignBizId = item.value
      } else if (key == 'realName') {
        row.userSaleBizId = item.value
      }
    }
  })
}
// 添加表单子级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) {
    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 'signDate':
      // 默认禁用今天及今天之前
      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 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' && child.finishTime && child.finishTime.split(' ').length == 2) {
    child.finishTime = `${form.value[child.key]} ${child.timeValue}:00`
  } else if (
    child.key == 'departureTime' &&
    child.finishTime &&
    child.finishTime.split(' ').length == 2
  ) {
    child.finishTime = `${form.value[child.key]} ${child.timeValue}:00`
  }
  // 离港时间在到港时间之前
  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.keyType == 'Array') {
      //给表格类型里的下拉框options赋值，否则提交的时候会报错
      searchOptions.value['realName'] = dictStore.userSaleExpandList
      searchOptions.value['name'] = dictStore.userSaleExpandList
    }
    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.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' }
            ]
          }
        }
      }
    }
  }

  // setFormValue(props.detailInfo, 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]) {
        searchOptions.value[child.key].forEach(item => {
          if (item.value == form.value[child.key]) {
            form.value[child.key] = item.label
            form.value['bankId'] = item.value
          }
        })

        if (
          searchOptions.value[child.key].findIndex(item => item.value == form.value['bankId']) !==
          -1
        ) {
          searchOptions.value[child.key].forEach(item => {
            if (item.value == form.value['bankId']) {
              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 {
            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.isReferrerAccompany == 1 && section.key == 'referrerDtoList') {
      section.showMoudle = true
    }
    // 给表单表格赋值
    for (const objKey in obj) {
      if (objKey == section.key && section.keyType == 'Array') {
        console.log('key', section.key, obj[section.key])

        section.data = obj[section.key]
      }
    }
    if (section.data) {
      for (const field of section.data) {
        if (field.key == 'confirmAppointmentTime' && props.appointmentStatus !== 0) {
          field.show = true
        }

        // 处理时间
        if (field.key == 'openAccountEndTime' && obj[field.key]) {
          // 开始时间是否在结束时间之前
          if (
            obj['openAccountStartTime'] &&
            !dayjs(obj['openAccountStartTime']).isBefore(dayjs(obj[field.key]))
          ) {
            form.value[field.key] = ''
          }
        }
        if (field.key == 'departureTime' && obj[field.key]) {
          if (obj[field.key].split(' ').length > 1) {
            form.value[field.key] = obj[field.key].split(' ')[0]
            field.timeValue = obj[field.key].split(' ')[1]
          }
          field.finishTime = obj[field.key]
          // 开始时间是否在结束时间之前
          if (obj['arrivalTime'] && !dayjs(obj['arrivalTime']).isBefore(dayjs(obj[field.key]))) {
            form.value[field.key] = ''
          }
        }
        // 给到港时间的时分赋值
        if (field.key == 'arrivalTime') {
          if (obj[field.key] && obj[field.key].split(' ').length > 1) {
            form.value[field.key] = obj[field.key].split(' ')[0]
            field.timeValue = obj[field.key].split(' ')[1]
          }

          field.finishTime = obj[field.key]
        }
        //要判断drawerType,因为抽屉要回显数据
        switch (field.drawerType) {
          case 'phone':
            let phoneObj = {}
            for (const key1 in field) {
              for (const key2 in obj) {
                if (key1 !== 'drawerType' && field[key1] == key2) {
                  if (key1 == 'code' && obj[key2]) {
                    phoneObj[field[key1]] = obj[key2].includes('+') ? obj[key2] : `+${obj[key2]}`
                  } else {
                    phoneObj[field[key1]] = obj[key2]
                  }
                }
              }
            }

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

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

            break
          case 'country':
            form.value[field.key] = obj.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))
  console.log('form.value', form.value)
  console.log('====================================')
  console.log('详情', processedAppointmentData.value)
  console.log('====================================')
}
// 数组去重
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
            }
          }
        }
        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) {
              item.data.forEach((item1, index) => {
                for (const key in item1) {
                  if (!item1[key]) {
                    errorFields.value.push({
                      message: `陪同转介人-第${index + 1}行${obj[key]}不能为空`
                    })
                  }
                }
              })
              submitObj['referrerDtoList'] = item.data
            } 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) {
                submitObj[item1.key] = item1.finishTime
              }
            })
          }
          if (item.key == 'userSignDtoList' && item.data.length > 0) {
            item.data.forEach((item1, index) => {
              for (const key in item1) {
                if (!item1[key]) {
                  errorFields.value.push({
                    message: `签单员-第${index + 1}行${obj1[key]}不能为空`
                  })
                }
              }
            })
            submitObj['userSignDtoList'] = item.data
          }
        })
        if (submitObj['signDate']) {
          submitObj['signDate'] = proxy.formatToDateTime(submitObj['signDate'])
        }
        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
})

// 因为tab嵌套了两层，所以需要监听父组件的tab否则锚点的显示就会有bug
watch(
  () => props.fatherTabName,
  newVal => {
    if (newVal) {
      appointmentRef.value = null
    }
  }
)
if (Object.keys(props.detailInfo).length > 0) {
  // processFormData()
  setFormValue(props.detailInfo, appointmentDomData)
}
// 暴露给父组件
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;
}
.itineraryDialogBox {
  .dialogItem {
    .dialogItemTitle {
      font-size: 16px;
      font-weight: 500;
      margin: 10px 0;
      color: #333;
    }
  }
}
@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>
