<template>
  <div
    class="appointment-container"
    :class="{
      'noembed-container': !isEmbed
    }"
    :style="{
      minHight
    }"
  >
    <el-card shadow="never">
      <div class="cardHeader" v-if="!isEmbed">
        <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="isEmbed">
          <el-col>
            <div class="topButtonBox">
              <!-- <el-button
                v-if="idsObj.appointmentBizId && pageSource !== 'policyList'"
                type="primary"
                icon="Plus"
                @click="handleAddExecl"
                >上传EXECL</el-button
              > -->
              <el-button
                v-if="pageSource !== 'policyList'"
                type="primary"
                :icon="Edit"
                @click="handleEdit"
                >编辑</el-button
              >
              <el-button
                v-if="pageSource !== 'policyList'"
                type="success"
                :icon="Check"
                @click="handleSubmit('submit')"
                >提交</el-button
              >
              <el-button
                type="primary"
                plain
                v-if="!idsObj.appointmentBizId && source == 'fnaList'"
                @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"
              :style="{
                height: tabHight
              }"
            >
              <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"
                  :tabIndex="tabsList.findIndex(t => t.name === 'appointmentInfo')"
                  anchorContainer=".appointmentTabPaneBox"
                  :fatherTabName="tabName"
                  :editStatus="editStatus"
                />
              </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"
                  @policyEditSuccess="getPolicyDetail"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  :tabIndex="tabsList.findIndex(t => t.name === 'productPlan')"
                  anchorContainer=".appointmentTabPaneBox"
                  :fatherTabName="tabName"
                  :editStatus="editStatus"
                />
              </div>
              <!-- 投保人 -->
              <div v-if="tab.name === 'policyholder'">
                <!-- :customerBizId="processInfo.customerBizId"  @handleSuccess="handleSuccess"-->
                <Customer
                  :activeName="activeName"
                  :fatherTabName="tabName"
                  :fatherStatus="editStatus"
                  :affixOffset="360"
                  :tabIndex="tabsList.findIndex(t => t.name === 'policyholder')"
                  anchorContainer=".appointmentTabPaneBox"
                  tabSource="policyholder"
                  ref="policyHolderInfoRef"
                  :fatherEditStatus="editStatus"
                />
                <!-- <PolicyHolderInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :customerInfo="customerInfo"
                  :idsObj="idsObj"
                  :apiPolicyholderInfoDto="appointmentSummeryInfo.apiPolicyholderInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="policyHolderInfoRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                /> -->
              </div>
              <div v-if="tab.name === 'insurantInfo'">
                <!-- :customerBizId="processInfo.customerBizId"  @handleSuccess="handleSuccess"-->
                <Customer
                  :activeName="activeName"
                  :fatherTabName="tabName"
                  :fatherStatus="editStatus"
                  :affixOffset="360"
                  :tabIndex="tabsList.findIndex(t => t.name === 'insurantInfo')"
                  anchorContainer=".appointmentTabPaneBox"
                  tabSource="insurantInfo"
                  ref="insuredInfoRef"
                  :fatherEditStatus="editStatus"
                />
                <!-- <InsuredInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :customerInfo="customerInfo"
                  :idsObj="idsObj"
                  :apiInsurantInfoDto="appointmentSummeryInfo.apiInsurantInfoDto"
                  :currentPolicyholderInfo="currentPolicyholderInfo"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="insuredInfoRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                /> -->
              </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"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                />
              </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"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                />
              </div>
              <div v-if="tab.name === 'questionnaires'">
                <HealthInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="questionnairesInfoRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  :foldInsurantInfo="foldInsurantInfo"
                />
              </div>
              <div v-if="tab.name === 'fna'">
                <FnaInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  :pageSource="pageSource"
                />
              </div>
              <div v-if="tab.name === 'policyTransfer'">
                <PolicyTransferInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiAppointmentInfoDto="appointmentSummeryInfo.apiAppointmentInfoDto"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  ref="policyTransferRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                />
              </div>
              <div v-if="tab.name === 'accessories'">
                <FileUpload
                  :activeName="activeName"
                  :idsObj="idsObj"
                  @handleSuccessEdit="getAppointmentInfo(idsObj.appointmentBizId)"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                />
              </div>
              <div v-if="tab.name === 'policyInfo'">
                <PolicyInfo
                  :activeName="activeName"
                  :policyBizId="route.query.policyBizId"
                  :policyFollowUpdateDto="policyDetailInfo.policyFollowUpdateDto"
                  @policyEditSuccess="getPolicyDetail"
                />
              </div>
              <div v-if="tab.name === 'policyAccessories'">
                <PolicyFileUpload :activeName="activeName" :policyBizId="route.query.policyBizId" />
              </div>
              <div v-if="tab.name === 'policyBroker'">
                <PolicyBrokerInfo
                  :activeName="activeName"
                  :policyBizId="route.query.policyBizId"
                  :brokerList="policyDetailInfo.brokerList"
                />
              </div>
              <div v-if="tab.name === 'policyMailing'">
                <PolicyMailing
                  :activeName="activeName"
                  :policyBizId="route.query.policyBizId"
                  :policyMailing="policyDetailInfo.policyMailing"
                />
              </div>
              <div v-if="tab.name === 'newpolicyTodo'">新单事项</div>
              <div v-if="tab.name === 'verifyPolicyInfo'">
                <VerifyPolicyInfo
                  :activeName="activeName"
                  :policyBizId="route.query.policyBizId"
                  :verifyPolicyInfo="policyDetailInfo.verifyPolicyInfo"
                />
              </div>
              <div v-if="tab.name === 'expectedCommission'">
                <ExpectedCommission
                  :activeName="activeName"
                  :policyBizId="route.query.policyBizId"
                  :policyNo="policyNo"
                />
              </div>
              <div v-if="tab.name === 'expectedFortune'">
                <expectedFortuneInfo
                  :activeName="activeName"
                  :policyBizId="route.query.policyBizId"
                  :policyNo="policyNo"
                />
              </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 PolicyInfo from '@/views/sign/underwritingMain/components/policyInfo' //新单跟进里的保单信息
import Customer from '@/views/sign/FnaList/components/customer'
import PolicyFileUpload from '@/views/sign/underwritingMain/components/fileUpload.vue' //新单跟进里的保单附件
import PolicyBrokerInfo from '@/views/sign/underwritingMain/components/brokerInfo.vue' //新单跟进里的保单附件
import PolicyMailing from '@/views/sign/underwritingMain/components/policyMailing.vue' //新单跟进里的保单附件
import VerifyPolicyInfo from '@/views/sign/underwritingMain/components/verifyPolicyInfo.vue' //新单跟进里的保单附件
import ExpectedCommission from '@/views/sign/underwritingMain/components/expectedCommission.vue' //新单跟进里的保单附件
import expectedFortuneInfo from '@/views/sign/underwritingMain/components/expectedFortuneInfo.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 { getPolicyfollow, getPolicyInfo, signName } from '@/api/sign/underwritingMain'
import {
  listTenantUser,
  getInsuranceProductList,
  getAdditionalProductList,
  getBankList,
  getUserSaleExpandList,
  secondAdditonalList,
  getAllSignList
} from '@/api/common'
import { Check, Edit } from '@element-plus/icons-vue'
import { ref, nextTick, onUnmounted } from 'vue'

const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
const props = defineProps({
  embed: { type: Boolean, default: false }, //作为组件嵌入别的地方
  editStatus: { type: String, default: '' }, //作为组件嵌入别的地方
  source: { type: String, default: '' }, //页面来源，不一样的页面会有不一样的操作
  tabName: { type: String, default: '' }, //父组件的tab名称
  processDetail: { type: Object, default: () => ({}) }, //新增预约单时，传入的流程详情信息
  policyDetailInfo: { type: Object, default: () => ({}) }, //新单跟进传递关于保单的详情信息
  policyId: { type: Object, default: () => ({}) } //新单跟进传递的Id
})
// console.log();

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({}) //预约详情总信息
const currentFile = ref(null)
const foldInsurantInfo = ref(false) //健康信息中得受保人信息是否隐藏
const processInfo = ref({
  fnaNo: '暂无',
  status: '未完成',
  createTime: proxy.parseTime(new Date()),
  customerName: userStore.name
})
const editStatus = ref(false) //编辑状态
const execlDialog = ref(false)
const isEmbed = ref(false) //是否作为组件插入
const policyNo = ref('') //新单跟进保单号
const currentPolicyholderInfo = ref({}) //存储下投保人信息，受保人模块要用到
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
      if (customerInfo.value.smoke) {
        customerInfo.value.smoke = Number(customerInfo.value.smoke)
      }
    }
  })
}
// 获取各个流程所需要得字典数据
const getDictsData = async () => {
  if (route.query.source == 'policyList') {
    const params4 = {
      pageNo: 1,
      pageSize: 10,
      policyNo: ''
    }

    const response4 = await signName(params4)
    if (response4.code == 200) {
      response4.data.records = response4.data.records.map(item => {
        // return {
        //   ...item,
        //   label: item.productName,
        //   value: item.additionalProductBizId
        // }
        return item
      })
      dictStore.setSignNameList(response4.data.records)
      console.log('response4', response4.data.records)
    }
    return
  }
  // 获取租户用户列表
  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)
  }
  const params4 = {
    pageNo: 1,
    pageSize: 99999
  }

  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
      }
    })
    dictStore.setBankList(response4.data.records)
  }
  const params5 = {
    pageNo: 1,
    pageSize: 99999
  }
  const response5 = await getUserSaleExpandList(params5)
  if (response5.code == 200) {
    console.log('response5', response5)

    response5.data.records = response5.data.records.map(item => {
      return {
        ...item,
        label: item.realName,
        value: item.userSaleBizId
      }
    })
    dictStore.setUserSaleExpandList(response5.data.records)
  }
  const params6 = {
    pageNo: 1,
    pageSize: 99999,
    projectBizId: userStore.projectInfo.projectBizId,
    tenantBizId: userStore.projectInfo.tenantBizId,
    fieldBizId: 'field_olk1qZe81qHHKXbw',
    fieldValueBizId: 'field_value_yXzTigvgUdRMFpoR'
  }
  const response6 = await secondAdditonalList(params6)
  if (response6.code == 200) {
    response6.data.records = response6.data.records.map(item => {
      return {
        ...item,
        label: item.title,
        value: item.productLaunchBizId
      }
    })
    dictStore.setProductAdditionalList(response6.data.records)
  }
  const params7 = {
    pageNo: 1,
    pageSize: 99999
  }
  const response7 = await getAllSignList(params7)
  if (response7.code == 200) {
    response7.data.records = response7.data.records.map(item => {
      return {
        ...item,
        label: item.realName,
        value: item.userSignBizId
      }
    })
    dictStore.setSignPeopleList(response7.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 = async type => {
  // 提交得时候要拿到各个步骤得表单数据
  // if (appointmentInfoRef.value) {
  //   const result = await appointmentInfoRef.value[0].handleFormValues()
  //   submitAppointmentObj.value.apiAppointmentInfoDto = result
  //   if (!submitAppointmentObj.value.apiAppointmentInfoDto) return
  // }

  // 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()
  }
  return
  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) {
        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('修改预约单成功')
      }
    })
    getAppointmentInfo(idsObj.value.appointmentBizId)
  }
  // 预约暂存
  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' })
      }
    })
  }
}
const handleEdit = () => {
  editStatus.value = !editStatus.value
}
//修改预约数据
if (route.query.appointmentNo && route.query.source == 'appointmentList') {
  processInfo.value = route.query
  idsObj.value.appointmentBizId = route.query.appointmentBizId
  getDictsData()
  // 请求预约单聚合详情
  getAppointmentInfo(idsObj.value.appointmentBizId, true)
}
const pageSource = computed(() => {
  return props.source || route.query.source
})
const tabHight = computed(() => {
  if (pageSource.value == 'fnaList') {
    return 'calc(100vh - 412px)'
  } else if (pageSource.value == 'policyList') {
    return 'calc(100vh - 225px)'
  } else {
    return 'calc(100vh - 276px)'
  }
})
const minHight = computed(() => {
  if (pageSource.value == 'fnaList') {
    return 'calc(100vh - 80px)'
  } else if (pageSource.value == 'policyList') {
    return 'calc(100vh - 84.5px)'
  } else {
    return 'calc(100vh - 325px)'
  }
})

// 预约作为组件在别的地放提交成功后processDetail会改变，所以需要监听
watch(
  () => props.processDetail,
  newVal => {
    idsObj.value = { ...newVal }
  }
)
// 嵌入到了流程详情页面，所以需要监听流程详情的tabName
watch(
  () => props.tabName,
  newVal => {
    if (newVal === 'appointment') {
      isEmbed.value = props.embed
      //代表是新增预约状态
      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'
      })
    }
  }
)
// 获取新单跟进详情数据
const getPolicyDetail = tabName => {
  // 使用 Promise.all 并行发送请求
  Promise.all([getPolicyfollow(route.query.policyBizId), getPolicyInfo(route.query.policyBizId)])
    .then(([followRes, infoRes]) => {
      // 只有当两个请求都成功时才执行后续操作
      if (followRes.code === 200 && infoRes.code === 200) {
        // 合并两个响应数据，infoRes.data 会覆盖 followRes.data 中的同名属性
        appointmentSummeryInfo.value = {
          ...followRes.data,
          ...infoRes.data
        }
        if (route.query.source == 'policyList') {
          appointmentSummeryInfo.value.apiAppointmentInfoDto = JSON.parse(
            JSON.stringify(
              appointmentSummeryInfo.value.apiProductPlanInfoDto.apiProductPlanMainInfoDto
            )
          )
          if (tabName && tabName == 'policyInfo') {
            policyNo.value = appointmentSummeryInfo.value.policyFollowUpdateDto.policyNo
          }
        }
      }
    })
    .catch(error => {
      // 统一错误处理（可选）
      console.error('请求失败:', error)
    })
}
if (route.query.source == 'policyList') {
  idsObj.value.policyBizId = route.query.policyBizId
  // getCustomerInfo(props.policyDetailInfo.customerBizId)
  appointmentSummeryInfo.value = JSON.parse(JSON.stringify(props.policyDetailInfo))
  if (appointmentSummeryInfo.value.apiProductPlanInfoDto) {
    appointmentSummeryInfo.value.apiAppointmentInfoDto = JSON.parse(
      JSON.stringify(appointmentSummeryInfo.value.apiProductPlanInfoDto.apiProductPlanMainInfoDto)
    )
  }
  policyNo.value = route.query.policyNo

  idsObj.value.appointmentBizId = route.query.appointmentBizId
  isEmbed.value = route.query.embed
  getDictsData()
  tabsList.value = [
    {
      label: '预计来佣',
      name: 'expectedCommission',
      id: 1,
      key: 'expectedCommission'
    },
    {
      label: '预计发佣',
      name: 'expectedFortune',
      id: 1,
      key: 'expectedFortune'
    },
    {
      label: '保单信息',
      name: 'policyInfo',
      id: 2,
      key: 'policyInfo'
    },
    {
      label: '保单附件',
      name: 'policyAccessories',
      id: 3,
      key: 'policyAccessories'
    },
    {
      label: '转介人',
      name: 'policyBroker',
      id: 4,
      key: 'policyBroker'
    },
    {
      label: '邮寄信息',
      name: 'policyMailing',
      id: 5,
      key: 'policyMailing'
    },
    {
      label: '核保信息',
      name: 'verifyPolicyInfo',
      id: 6,
      key: 'verifyPolicyInfo'
    },
    // {
    //   label: '新单事项',
    //   name: 'newpolicyTodo',
    //   id: 7,
    //   key: 'newpolicyTodo'
    // },
    {
      label: '产品计划',
      name: 'productPlan',
      id: 8,
      status: '0',
      key: 'planBizId'
    },
    {
      label: '投保人',
      name: 'policyholder',
      id: 9,
      status: '0',
      key: 'policyholderBizId'
    },
    {
      label: '受保人',
      name: 'insurantInfo',
      id: 10,
      status: '0',
      key: 'insurantBizId'
    },
    {
      label: '受益人',
      name: 'beneficiary',
      id: 11,
      status: '0',
      key: 'beneficiaryBizId'
    },
    {
      label: '第二持有人',
      name: 'secondHolder',
      id: 12,
      status: '0',
      key: 'secondHolderBizId'
    },
    {
      label: '健康信息', //后端还没加这个字段
      name: 'questionnaires',
      id: 13,
      status: '0',
      key: 'questionnaireBizId'
    },
    // {
    //   label: '关联FNA',
    //   name: 'fna',
    //   id: 14,
    //   status: '0',
    //   key: 'fnaBizId'
    // },
    {
      label: '转保声明',
      name: 'policyTransfer',
      id: 15,
      status: '0',
      key: 'policyTransfer'
    },
    {
      label: '预约附件', //大提交的时候不用提交了，因为上传文件的时候已经入库了
      name: 'accessories',
      id: 16,
      status: '0',
      key: 'fnaBizId'
    }
  ]
  nextTick(() => {
    activeName.value = 'expectedCommission'
  })
}
// 根据页面来源的不同控制tab项内模块小提交按钮的显示与否，也能证明是修改状态
const showSubmitBtn = computed(() => {
  if (route.query.appointmentNo && route.query.source == 'appointmentList') {
    return true
  } else if (route.query.source == 'policyList') {
    return true
  } else if (route.query.source == 'fnaList' && idsObj.value.appointmentBizId) {
    return true
  } else if (route.query.source == 'fnaList' && !idsObj.value.appointmentBizId) {
    return false
  }
})
if (route.query.appointmentNo && route.query.source == 'appointmentList') {
  editStatus.value = true
} else if (route.query.source == 'policyList') {
  editStatus.value = true
} else if (route.query.source == 'fnaList' && idsObj.value.appointmentBizId) {
  editStatus.value = true
} else if (route.query.source == 'fnaList' && !idsObj.value.appointmentBizId) {
  editStatus.value = false
}
console.log('editStatus.value ', editStatus.value, idsObj.value)

onUnmounted(() => {
  // 彻底重置所有响应式数据
  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); */
}

.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;
        }
      }
    }
  }

  .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>
