<template>
  <div
    class="appointment-container"
    :class="{
      'noembed-container': !embed,
      'embed-container': embed
    }"
  >
    <!-- <div v-if="!embed">
      <el-button type="primary" icon="Back" @click="handleBack" style="margin-bottom: 10px"
        >返回</el-button
      >
    </div> -->

    <el-card shadow="never">
      <div class="cardHeader" v-if="!embed">
        <div class="left">
          <img class="iconBox" src="@/assets/images/icon1.png" alt="" />
          <div class="rightBox">
            <div class="num">{{ processInfo.appointmentNo || '--' }}</div>
            <div class="bottom">
              <div class="status">
                {{ processInfo.status || '--' }}
              </div>
              <div class="time">
                <span class="iconfont icon-yanqiweiwancheng"></span>
                <span
                  >{{ parseTime(processInfo.createTime) }} 由{{
                    processInfo.creatorName || '--'
                  }}创建</span
                >
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <el-button type="success" :icon="Check" @click="handleSubmit('submit')">提交</el-button>
          <el-button
            v-if="idsObj.appointmentBizId"
            type="primary"
            icon="Plus"
            @click="handleAddExecl"
            >上传EXECL</el-button
          >
        </div>
      </div>
      <div class="tabsBox">
        <el-row v-if="embed">
          <el-col>
            <div class="topButtonBox">
              <el-button
                v-if="idsObj.appointmentBizId"
                type="primary"
                icon="Plus"
                @click="handleAddExecl"
                >上传EXECL</el-button
              >
              <el-button type="success" :icon="Check" @click="handleSubmit('submit')"
                >提交</el-button
              >
              <el-button
                type="primary"
                plain
                v-if="!idsObj.appointmentBizId"
                @click="handleSubmit('storage')"
                >暂存</el-button
              >
            </div>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName" type="card" class="demo-tabs" :before-leave="beforeTabLeave">
          <el-tab-pane v-for="tab in tabsList" :key="tab.name" :label="tab.label" :name="tab.name">
            <div
              class="appointmentTabPaneBox"
              :class="{ yesEmbedTabPaneBox: embed, noEmbedTabPaneBox: !embed }"
            >
              <div v-if="tab.name === 'appointmentInfo'">
                <AppointmentInfo
                  v-if="tab.name === 'appointmentInfo'"
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiAppointmentInfoDto="appointmentSummeryInfo.apiAppointmentInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="appointmentInfoRef"
                />
              </div>
              <div v-if="tab.name === 'productPlan'">
                <ProductPlan
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiProductPlanInfoDto="appointmentSummeryInfo.apiProductPlanInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="productPlanRef"
                />
              </div>
              <div v-if="tab.name === 'policyholder'">
                <PolicyHolderInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :customerInfo="customerInfo"
                  :idsObj="idsObj"
                  :apiPolicyholderInfoDto="appointmentSummeryInfo.apiPolicyholderInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="policyHolderInfoRef"
                />
              </div>
              <div v-if="tab.name === 'insurantInfo'">
                <InsuredInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :customerInfo="customerInfo"
                  :idsObj="idsObj"
                  :apiInsurantInfoDto="appointmentSummeryInfo.apiInsurantInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="insuredInfoRef"
                />
              </div>
              <div v-if="tab.name === 'secondHolder'">
                <SecondHolderInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiSecondHolderInfoDto="appointmentSummeryInfo.apiSecondHolderInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  :customerInfo="customerInfo"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="secondHolderInfoRef"
                />
              </div>
              <div v-if="tab.name === 'beneficiary'">
                <BeneficiaryInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiBeneficiaryInfoDtoList="appointmentSummeryInfo.apiBeneficiaryInfoDtoList"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="beneficiaryInfoRef"
                />
              </div>
              <div v-if="tab.name === 'questionnaires'">
                <HealthInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="questionnairesInfoRef"
                />
              </div>
              <div v-if="tab.name === 'fna'">
                <FnaInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                />
              </div>
              <div v-if="tab.name === 'policyTransfer'">
                <PolicyTransferInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiAppointmentInfoDto="appointmentSummeryInfo.apiAppointmentInfoDto"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="policyTransferRef"
                />
              </div>
              <div v-if="tab.name === 'accessories'">
                <FileUpload
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiAppointmentInfoDto="appointmentSummeryInfo.apiAppointmentInfoDto"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
    <!-- 展示行程单详情 -->
    <el-dialog v-model="execlDialog" title="Excel导入" width="40%">
      <div class="dialogBox">
        <div>
          <div class="tipTitle">您需要准备</div>
          <div class="tipContent">
            <div>
              1、下载模板 Excel
              <span class="downloadBtn" @click="downloadExcel"
                ><el-icon><Download /></el-icon>点击下载</span
              >
            </div>
            <div class="">2、将数据复制到模板 Excel 中</div>
            <div class="">3、填写后在这上传模板Excel</div>
          </div>
        </div>
        <div class="exprotBtn">
          <!-- :action="uploadImgUrl"
            :headers="headers" :on-success="uploadSuccess"  -->
          <el-upload
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".xlsx,.xls"
          >
            <el-button type="primary" @click="execlUpload">上传文件</el-button>
          </el-upload>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name="AppointmentEdit">
import AppointmentInfo from './components/appointmentInfo.vue'
import ProductPlan from './components/productPlan.vue'
import PolicyHolderInfo from './components/policyHolderInfo.vue'
import InsuredInfo from './components/insuredInfo.vue'
import SecondHolderInfo from './components/secondHolderInfo.vue'
import BeneficiaryInfo from './components/beneficiaryInfo.vue'
import FnaInfo from './components/fnaInfo.vue'
import PolicyTransferInfo from './components/policyTransferInfo.vue'
import FileUpload from './components/fileUpload.vue'
import HealthInfo from './components/healthInfo.vue'
import useUserStore from '@/store/modules/user'
import useDictStore from '@/store/modules/dict'
import { getCustomerDetail } from '@/api/sign/fna'
import {
  addAppointment,
  getAppointmentDetail,
  storageAppointment,
  editAppointmentDetail,
  uploadExcel
} from '@/api/sign/appointment'
import { listTenantUser, getInsuranceProductList, getAdditionalProductList } from '@/api/common'
import { Check } from '@element-plus/icons-vue'
import { ref, nextTick, onUnmounted } from 'vue'

const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
// const { csf_ap_status } = proxy.useDict('csf_ap_status')
const props = defineProps({
  embed: { type: Boolean, default: false }, //作为组件嵌入别的地方
  editStatus: { type: String, default: '' }, //作为组件嵌入别的地方
  tabName: { type: String, default: '' }, //父组件的tab名称
  processDetail: { type: Object, default: () => ({}) } //新增预约单时，传入的流程详情信息
})
const userStore = useUserStore()
const dictStore = useDictStore()
const showStorage = ref(false)
const route = useRoute()
const router = useRouter()
const activeName = ref('')
const formStatus = ref('')
const submitAppointmentObj = ref({})
const appointmentInfoRef = ref(null)
const productPlanRef = ref(null)
const policyHolderInfoRef = ref(null)
const insuredInfoRef = ref(null)
const secondHolderInfoRef = ref(null)
const beneficiaryInfoRef = ref(null)
const policyTransferRef = ref(null)
const questionnairesInfoRef = ref(null)
const customerInfo = ref({})
const idsObj = ref({}) //各个模块的bizId
// const appointmentSummeryInfo = ref({ apiAppointmentInfoDto: { appointmentBizId: '' } }) //预约详情总信息
const appointmentSummeryInfo = ref({}) //预约详情总信息
const currentFile = ref(null)
const processInfo = ref({
  fnaNo: '暂无',
  status: '未完成',
  createTime: proxy.parseTime(new Date()),
  customerName: userStore.name
})
const execlDialog = ref(false)

const tabsList = ref([
  {
    label: '预约信息',
    name: 'appointmentInfo',
    id: 1,
    key: 'appointmentBizId'
  },
  {
    label: '产品计划',
    name: 'productPlan',
    id: 2,
    status: '0',
    key: 'planBizId'
  },
  {
    label: '投保人',
    name: 'policyholder',
    id: 3,
    status: '0',
    key: 'policyholderBizId'
  },
  {
    label: '受保人',
    name: 'insurantInfo',
    id: 4,
    status: '0',
    key: 'insurantBizId'
  },
  {
    label: '受益人',
    name: 'beneficiary',
    id: 5,
    status: '0',
    key: 'beneficiaryBizId'
  },
  {
    label: '第二持有人',
    name: 'secondHolder',
    id: 6,
    status: '0',
    key: 'secondHolderBizId'
  },
  {
    label: '健康信息', //后端还没加这个字段
    name: 'questionnaires',
    id: 7,
    status: '0',
    key: 'questionnaireBizId'
  },
  {
    label: '关联FNA',
    name: 'fna',
    id: 8,
    status: '0',
    key: 'fnaBizId'
  },
  {
    label: '转保声明',
    name: 'policyTransfer',
    id: 9,
    status: '0',
    key: 'policyTransfer'
  },
  {
    label: '附件', //大提交的时候不用提交了，因为上传文件的时候已经入库了
    name: 'accessories',
    id: 10,
    status: '0',
    key: 'fnaBizId'
  }
  //
  // {
  //   label: '关联计划书', //关联计划书暂时先不做
  //   name: 'fna',
  //   id: 10,
  //   status: '0',
  //   key: 'fnaBizId'
  // },
  // {
  //   label: '其他', //先不做
  //   name: 'fna',
  //   id: 11,
  //   status: '0',
  //   key: 'fnaBizId'
  // },
])
// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}
// 上传EXECL
const handleAddExecl = () => {
  execlDialog.value = true
}
const downloadExcel = () => {
  // 创建隐藏的下载链接
  const link = document.createElement('a')
  link.href =
    'https://yd-ali-oss.oss-cn-shanghai-finance-1-pub.aliyuncs.com/xlsx/2025/10/13/1e7a3124c5c04c6b83a43c99fd5af241.xlsx'
  // link.target = '_blank' // 新窗口打开

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

  // 触发下载
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
const handleFileChange = async file => {
  // 文件验证
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }

  if (file.name.includes(',')) {
    ElMessage.error('文件名不正确，不能包含英文逗号!')
    return false
  }

  const isLt = file.size / 1024 / 1024 < 10
  if (!isLt) {
    ElMessage.error(`上传文件大小不能超过10MB!`)
    return false
  }

  // 直接上传
  try {
    // 创建 FormData 对象
    const formData = new FormData()

    // 获取原始文件对象（重要！）
    const rawFile = file.raw

    // 添加文件到 FormData（第二个参数是文件对象，第三个参数是文件名）
    formData.append('file', rawFile, rawFile.name)

    // 添加其他参数
    formData.append('appointmentBizId', idsObj.value.appointmentBizId)
    const res = await uploadExcel(formData)
    if (res.code === 200) {
      proxy.$message.success('上传文件成功')
      execlDialog.value = false
    }
  } catch (error) {
    proxy.$message.error('上传失败')
    console.error('Upload error:', error)
  }

  return false // 阻止自动上传
}

const execlUpload = () => {
  let data = {
    appointmentBizId: idsObj.value.appointmentBizId,
    file: currentFile.value
  }
  if (currentFile.value) {
    uploadExcel(data).then(res => {
      if (res.code == 200) {
        proxy.$message.success('上传文件成功')
        execlDialog.value = false
      }
    })
  }
}
// 获取预约详情
function getAppointmentInfo(appointmentBizId, changeTab) {
  getAppointmentDetail(appointmentBizId).then(res => {
    if (res.code == 200) {
      appointmentSummeryInfo.value = res.data
      let options = fetchDictData('csf_ap_status')
      options.forEach(item => {
        if (item.value == appointmentSummeryInfo.value.status) {
          processInfo.value.status = item.label
        }
      })
      getCustomerInfo(res.data.apiAppointmentInfoDto.customerBizId)
      if (!appointmentSummeryInfo.value.apiAppointmentInfoDto.appointmentBizId) {
        showStorage.value = true
      }
      idsObj.value.fnaNo = res.data.apiAppointmentInfoDto.fnaNo
      idsObj.value.fnaBizId = res.data.apiAppointmentInfoDto.fnaBizId
      // 从预约列表里的修改，改变状态
      if (route.query.appointmentNo) {
        formStatus.value = 'appointmentEdit'
        if (changeTab) {
          activeName.value = 'appointmentInfo'
        }
      }
    }
  })
}
// 获取客户详情，投保人模块回填用
function getCustomerInfo(customerBizId) {
  getCustomerDetail(customerBizId).then(res => {
    if (res.code == 200) {
      customerInfo.value = res.data
    }
  })
}
// 获取各个流程所需要得字典数据
const getDictsData = async () => {
  // 获取租户用户列表
  const params1 = {
    tenantBizId: userStore.projectInfo.tenantBizId,
    pageNo: 1,
    pageSize: 10
  }
  const response1 = await listTenantUser(params1)
  if (response1.code == 200) {
    dictStore.setTenantUserList(response1.data.records)
  }
  const params2 = {
    loginTenantBizId: userStore.projectInfo.tenantBizId,
    pageNo: 1,
    pageSize: 10
  }

  const response2 = await getInsuranceProductList(params2)
  if (response2.code == 200) {
    response2.data.records = response2.data.records.map(item => {
      return {
        ...item,
        label: item.productName,
        value: item.productBizId
      }
    })
    dictStore.setInsureProductList(response2.data.records)
  }
  const params3 = {
    pageNo: 1,
    pageSize: 10
  }

  const response3 = await getAdditionalProductList(params3)
  if (response3.code == 200) {
    response3.data.records = response3.data.records.map(item => {
      return {
        ...item,
        label: item.productName,
        value: item.additionalProductBizId
      }
    })
    dictStore.setAdditionalProductList(response3.data.records)
  }
  proxy.useDictLists([
    'csf_employment',
    'sys_no_yes',
    'bx_currency_type',
    'csf_liquid_asset_type',
    'csf_premium_funding_source',
    'csf_customer_type',
    'csf_customer_title',
    'sys_gender',
    'csf_marriage',
    'csf_education',
    'csf_id_type',
    'csf_ap_apply_type',
    'csf_ap_meeting_point',
    'csf_ap_first_issue',
    'csf_ap_dividend',
    'csf_ap_frequency',
    'csf_ap_rel',
    'csf_ap_registration',
    'csf_ap_exercise',
    'csf_ap_risk',
    'csf_ap_movie',
    'csf_ap_game',
    'csf_ap_policy_transfer',
    'wj_question_first_category',
    'wj_question_second_category',
    'csf_ap_status',
    'md_bank'
  ])
}
// Tab切换前的验证
const beforeTabLeave = (activeTabName, oldTabName) => {
  return true
}

const handleBack = () => {
  // 先手动清理状态
  submitAppointmentObj.value = {}
  appointmentSummeryInfo.value = {}
  router.go(-1)
}
// 判断是否为数组
const isArray = value => {
  return Array.isArray(value)
}

// 判断是否为对象
const isObject = value => {
  return typeof value === 'object' && value !== null && !Array.isArray(value)
}
const handleSubmit = type => {
  // 提交得时候要拿到各个步骤得表单数据
  if (appointmentInfoRef.value) {
    submitAppointmentObj.value.apiAppointmentInfoDto =
      appointmentInfoRef.value[0].handleFormValues()
  }
  if (productPlanRef.value) {
    submitAppointmentObj.value.apiProductPlanInfoDto = productPlanRef.value[0].handleSubmitForm()
  }
  if (policyHolderInfoRef.value) {
    submitAppointmentObj.value.apiPolicyholderInfoDto =
      policyHolderInfoRef.value[0].handleFormValues()
  }
  if (insuredInfoRef.value) {
    submitAppointmentObj.value.apiInsurantInfoDto = insuredInfoRef.value[0].handleFormValues()
  }
  if (secondHolderInfoRef.value) {
    submitAppointmentObj.value.apiSecondHolderInfoDto =
      secondHolderInfoRef.value[0].handleFormValues()
  }
  if (beneficiaryInfoRef.value) {
    submitAppointmentObj.value.apiBeneficiaryInfoDtoList =
      beneficiaryInfoRef.value[0].handleFormValues()
  }
  // return
  // 代表新增预约
  if (formStatus.value == 'appointmentAdd' && !idsObj.value.appointmentBizId) {
    submitAppointmentObj.value.apiAppointmentInfoDto.customerBizId =
      props.processDetail.customerBizId
    submitAppointmentObj.value.apiAppointmentInfoDto.fnaBizId = props.processDetail.fnaBizId
    submitAppointmentObj.value.apiAppointmentInfoDto.fnaNo = props.processDetail.fnaNo
    if (type == 'submit') {
      // 新增预约单
      addAppointment(submitAppointmentObj.value).then(res => {
        if (res.code == 200) {
          proxy.$message.success('预约成功')
          appointmentInfoRef.value[0].handleEditStatus(true)
          productPlanRef.value[0].handleEditStatus(true)
          policyHolderInfoRef.value[0].handleEditStatus(true)
          insuredInfoRef.value[0].handleEditStatus(true)
          secondHolderInfoRef.value[0].handleEditStatus(true)
          beneficiaryInfoRef.value[0].handleEditStatus(true)
          emit('handleSuccess', {
            tab: 'appointment',
            type: 'add'
          })
        }
      })
    }
  }
  // 代表修改预约单
  if (idsObj.value.appointmentBizId) {
    if (policyTransferRef.value) {
      submitAppointmentObj.value.apiAppointmentInfoDto.policyTransfer =
        policyTransferRef.value[0].form.policyTransfer
    }
    if (questionnairesInfoRef.value) {
      submitAppointmentObj.value.answerSessionsDtoList =
        questionnairesInfoRef.value[0].handleFormValues().answerSessionsDtoList
    }
    // 与预约聚合详情做对比，如果拿到得个表单数据有为空得就使用聚合详情得数据
    for (const key1 in appointmentSummeryInfo.value) {
      for (const key2 in submitAppointmentObj.value) {
        if (
          key1 == key2 &&
          isArray(submitAppointmentObj.value[key2]) &&
          submitAppointmentObj.value[key2].length == 0
        ) {
          submitAppointmentObj.value[key2] = appointmentSummeryInfo.value[key1]
        }
        if (
          key1 == key2 &&
          isObject(submitAppointmentObj.value[key2]) &&
          Object.keys(submitAppointmentObj.value[key2]).length == 0
        ) {
          submitAppointmentObj.value[key2] = appointmentSummeryInfo.value[key1]
        }
        if (
          key2 == 'apiPolicyholderInfoDto' &&
          Object.keys(submitAppointmentObj.value[key2]).length !== 0
        ) {
          submitAppointmentObj.value[key2]['appointmentBizId'] =
            appointmentSummeryInfo.value.apiPolicyholderInfoDto.appointmentBizId
          submitAppointmentObj.value[key2]['id'] =
            appointmentSummeryInfo.value.apiPolicyholderInfoDto.id
          submitAppointmentObj.value[key2]['policyholderBizId'] =
            appointmentSummeryInfo.value.apiPolicyholderInfoDto.policyholderBizId
        }
        if (
          key2 == 'apiInsurantInfoDto' &&
          Object.keys(submitAppointmentObj.value[key2]).length !== 0
        ) {
          submitAppointmentObj.value[key2]['appointmentBizId'] =
            appointmentSummeryInfo.value.apiInsurantInfoDto.appointmentBizId
          submitAppointmentObj.value[key2]['id'] =
            appointmentSummeryInfo.value.apiInsurantInfoDto.id
          submitAppointmentObj.value[key2]['insurantBizId'] =
            appointmentSummeryInfo.value.apiInsurantInfoDto.insurantBizId
        }
      }
    }

    // 编辑预约单
    editAppointmentDetail(submitAppointmentObj.value).then(res => {
      if (res.code == 200) {
        getAppointmentInfo(idsObj.value.appointmentBizId)
        appointmentInfoRef.value[0].handleEditStatus(true)
        productPlanRef.value[0].handleEditStatus(true)
        policyHolderInfoRef.value[0].handleEditStatus(true)
        insuredInfoRef.value[0].handleEditStatus(true)
        secondHolderInfoRef.value[0].handleEditStatus(true)
        beneficiaryInfoRef.value[0].handleEditStatus(true)
        policyTransferRef.value[0].handleEditStatus(true)
        questionnairesInfoRef.value[0].handleEditStatus(true)
        proxy.$message.success('修改预约单成功')
      }
    })
  }
  if (type == 'storage') {
    submitAppointmentObj.value.apiAppointmentInfoDto.customerBizId =
      props.processDetail.customerBizId
    submitAppointmentObj.value.apiAppointmentInfoDto.fnaBizId = props.processDetail.fnaBizId
    submitAppointmentObj.value.apiAppointmentInfoDto.fnaNo = props.processDetail.fnaNo
    // 暂存预约单
    storageAppointment(submitAppointmentObj.value).then(res => {
      if (res.code == 200) {
        proxy.$message.success('预约暂存成功')
        router.push({ path: '/sign/appointment' })
      }
    })
  }
}

//修改预约数据
if (route.query.appointmentNo) {
  processInfo.value = route.query

  idsObj.value.appointmentBizId = route.query.appointmentBizId
  getDictsData()
  // 请求预约单聚合详情
  getAppointmentInfo(idsObj.value.appointmentBizId, true)
}
// 预约作为组件在别的地放提交成功后processDetail会改变，所以需要监听
watch(
  () => props.processDetail,
  newVal => {
    idsObj.value = { ...newVal }
  }
)
watch(
  () => props.tabName,
  newVal => {
    if (newVal === 'appointment') {
      // 这个页面作为组件在别的地方使用，所以需要判断是新增还是编辑
      //props.editStatus == 'add'
      //代表是新增预约状态
      if (!idsObj.value.appointmentBizId) {
        formStatus.value = 'appointmentAdd'
        getCustomerInfo(props.processDetail.customerBizId)

        tabsList.value = [
          {
            label: '预约信息',
            name: 'appointmentInfo',
            id: 1,
            key: 'appointmentBizId'
          },
          {
            label: '产品计划',
            name: 'productPlan',
            id: 2,
            status: '0',
            key: 'planBizId'
          },
          {
            label: '投保人',
            name: 'policyholder',
            id: 3,
            status: '0',
            key: 'policyholderBizId'
          },
          {
            label: '受保人',
            name: 'insurantInfo',
            id: 4,
            status: '0',
            key: 'insurantBizId'
          },
          {
            label: '受益人',
            name: 'beneficiary',
            id: 4,
            status: '0',
            key: 'beneficiaryBizId'
          },
          {
            label: '第二持有人',
            name: 'secondHolder',
            id: 5,
            status: '0',
            key: 'secondHolderBizId'
          }
        ]
        nextTick(() => {
          activeName.value = 'appointmentInfo'
        })
      } else {
        getAppointmentInfo(idsObj.value.appointmentBizId)
        tabsList.value = [
          {
            label: '预约信息',
            name: 'appointmentInfo',
            id: 1,
            key: 'appointmentBizId'
          },
          {
            label: '产品计划',
            name: 'productPlan',
            id: 2,
            status: '0',
            key: 'planBizId'
          },
          {
            label: '投保人',
            name: 'policyholder',
            id: 3,
            status: '0',
            key: 'policyholderBizId'
          },
          {
            label: '受保人',
            name: 'insurantInfo',
            id: 4,
            status: '0',
            key: 'insurantBizId'
          },
          {
            label: '受益人',
            name: 'beneficiary',
            id: 5,
            status: '0',
            key: 'beneficiaryBizId'
          },
          {
            label: '第二持有人',
            name: 'secondHolder',
            id: 6,
            status: '0',
            key: 'secondHolderBizId'
          },
          {
            label: '健康信息', //后端还没加这个字段
            name: 'questionnaires',
            id: 7,
            status: '0',
            key: 'questionnaireBizId'
          },
          {
            label: '关联FNA',
            name: 'fna',
            id: 8,
            status: '0',
            key: 'fnaBizId'
          },
          {
            label: '转保声明',
            name: 'policyTransfer',
            id: 9,
            status: '0',
            key: 'policyTransfer'
          },
          {
            label: '附件', //大提交的时候不用提交了，因为上传文件的时候已经入库了
            name: 'accessories',
            id: 10,
            status: '0',
            key: 'fnaBizId'
          }
        ]
      }

      nextTick(() => {
        activeName.value = 'appointmentInfo'
      })
    }
  }
)

onUnmounted(() => {
  console.log('预约编辑页面完全销毁')

  // 彻底重置所有响应式数据
  submitAppointmentObj.value = {}
  appointmentSummeryInfo.value = {}
  customerInfo.value = {}
  idsObj.value = {}
  activeName.value = ''
  formStatus.value = ''

  // 强制清理数组
  tabsList.value = []

  // 清理所有 ref 引用
  appointmentInfoRef.value = null
  productPlanRef.value = null
  policyHolderInfoRef.value = null
  insuredInfoRef.value = null
  secondHolderInfoRef.value = null
  beneficiaryInfoRef.value = null
  policyTransferRef.value = null
  questionnairesInfoRef.value = null

  // 清理事件监听器（如果有的话）
  // window.removeEventListener('resize', yourHandler)
})
</script>
<style lang="scss" scoped>
::v-deep .el-card {
  border: none !important;
}
::v-deep .el-input-group__append,
.el-input-group__prepend {
  background-color: #fff !important;
}
.noembed-container {
  padding: 20px;
  background-color: #f2f3f5;
  min-height: calc(100vh - 84.5px);
}
.embed-container {
  min-height: calc(100vh - 325px);
}
.appointment-container {
  display: flex;
  flex-direction: column;
  .cardHeader {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .iconBox {
        width: 40px;
        height: 40px;
        margin-right: 5px;
        background-color: #e8f3ff;
        border-radius: 3px;
        text-align: center;
        padding: 5px;
      }
      .rightBox {
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        .num {
          font-size: 14px;
        }
        .bottom {
          display: flex;
          align-items: center;
          margin-top: 3px;
          .status {
            font-size: 11px;
            color: #00b42a;
            background-color: #e8ffea;
            padding: 4px 6px;
            border-radius: 2px;
            margin-right: 10px;
          }

          .time {
            font-size: 12px;
            color: #86909c;
            .icon-yanqiweiwancheng {
              margin-right: 5px;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
  .tabsBox {
    .topButtonBox {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }
    .tabButton {
      box-shadow: 0 -1px 14px #00000014;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      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;
        }
      }
    }
  }
  .noEmbedTabPaneBox {
    height: calc(100vh - 276px);
  }
  .yesEmbedTabPaneBox {
    height: calc(100vh - 407px);
  }
  .appointmentTabPaneBox {
    overflow-y: auto;
    padding-right: 10px;
  }

  .overviewBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .oneItem {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      .circle {
        width: 35px;
        height: 35px;
        box-sizing: border-box;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 5px;
      }
      .el-icon {
        font-size: 16px;
        font-weight: 600;
      }
    }
    .finfishCircle {
      background-color: #e8f3ff;
      color: #165dff;
    }
    .todoCircle {
      background-color: #165dff;
      color: #fff;
    }
    .unFinishCircle {
      background-color: #f2f3f5;
      color: #4e5969;
    }
    .title {
      font-size: 14px;
      margin-bottom: 5px;
    }
    .finfishTitle {
      color: #1d2129;
      font-size: 14px;
    }
    .unFinishTitle {
      color: #4e5969;
      font-size: 13px;
    }
    .status {
      font-size: 12px;
      margin-bottom: 8px;
      color: #86909c;
    }
    .finfishStatus {
      color: #165dff;
    }
    .unFinishStatus {
      color: #4e5969;
    }
    .operation {
      display: flex;
      align-items: center;
      font-size: 12px;
      .editIcon {
        margin-right: 3px;
        color: #165dff;
        font-size: 12px;
      }
    }
    .finfishOperation {
      color: #4e5969;
    }
    .unFinishOperation {
      color: #165dff;
    }
  }
}
.dialogBox {
  .tipTitle {
    font-size: 16px;
    font-weight: 600;
  }
  .tipContent {
    margin-top: 10px;
    div {
      margin-top: 10px;
      .downloadBtn {
        color: #165dff;
      }
    }
  }
  .exprotBtn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
