<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">
          <div v-if="appointmentSummeryInfo.status == '2'">
            <el-button
              v-if="pageSource !== 'policyList' && idsObj.appointmentBizId"
              type="warning"
              :icon="Edit"
              @click="handleCancel('appoint')"
              :disabled="submitLoading"
              >取消预约</el-button
            >
          </div>
          <div v-else-if="appointmentSummeryInfo.status !== '2'">
            <el-button
              v-if="pageSource !== 'policyList' && editStatus"
              type="primary"
              :icon="Edit"
              @click="handleEdit"
              >编辑</el-button
            >

            <el-button
              type="primary"
              v-if="!editStatus"
              @click="handleSubmit('editStorage')"
              :disabled="submitLoading"
              :loading="submitLoading"
              >暂存</el-button
            >
            <el-button
              v-if="!editStatus"
              type="success"
              :icon="Check"
              @click="handleSubmit('submit')"
              :disabled="submitLoading"
              :loading="submitLoading"
              >提交</el-button
            >
            <el-button
              v-if="
                pageSource !== 'policyList' &&
                appointmentSummeryInfo.status == '1' &&
                idsObj.appointmentBizId
              "
              type="warning"
              :icon="Edit"
              @click="handleCancel('apply')"
              :disabled="submitLoading"
              >取消申请</el-button
            >
          </div>

          <el-button
            style="margin-left: 10px"
            v-if="idsObj.appointmentBizId"
            type="primary"
            @click="assetVerification"
            >投保人资产验证</el-button
          >
          <el-button v-if="idsObj.appointmentBizId" type="primary" @click="assetVerification"
            >投保人收支验证</el-button
          >
        </div>
      </div>
      <div class="tabsBox">
        <el-row v-if="isEmbed">
          <el-col>
            <div class="topButtonBox">
              <!-- <el-button
                v-if="!idsObj.appointmentBizId"
                type="primary"
                icon="Plus"
                @click="execlDialog = true"
                >导入</el-button
              > -->
              <el-button
                v-if="pageSource !== 'policyList' && idsObj.appointmentBizId"
                type="primary"
                :icon="Edit"
                @click="handleEdit"
                >编辑</el-button
              >

              <el-button
                v-if="pageSource !== 'policyList'"
                type="success"
                :icon="Check"
                @click="handleSubmit('submit')"
                :disabled="submitLoading"
                :loading="submitLoading"
                >提交</el-button
              >
              <el-button
                type="primary"
                plain
                v-if="!idsObj.appointmentBizId && source == 'fnaList'"
                @click="handleSubmit('storage')"
                :disabled="submitLoading"
                :loading="submitLoading"
                >暂存</el-button
              >
              <el-button
                style="margin-left: 10px"
                v-if="idsObj.appointmentBizId"
                type="primary"
                @click="assetVerification"
                >投保人资产验证</el-button
              >
              <el-button v-if="idsObj.appointmentBizId" type="primary" @click="assetVerification"
                >投保人收支验证</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"
                  ref="appointmentInfoRef"
                  :tabIndex="tabsList.findIndex(t => t.name === 'appointmentInfo')"
                  anchorContainer=".appointmentTabPaneBox"
                  :fatherTabName="tabName"
                  :editStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                  :isExportAppointment="isExportAppointment"
                />
              </div>
              <div v-if="tab.name === 'productPlan'">
                <ProductPlan
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiProductPlanInfoDto="appointmentSummeryInfo.apiProductPlanInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  ref="productPlanRef"
                  @policyEditSuccess="getPolicyDetail"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  :tabIndex="tabsList.findIndex(t => t.name === 'productPlan')"
                  anchorContainer=".appointmentTabPaneBox"
                  :fatherTabName="tabName"
                  :editStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                  :isExportAppointment="isExportAppointment"
                />
              </div>
              <!-- 投保人 -->
              <div v-if="tab.name === 'policyholder'">
                <Customer
                  :activeName="activeName"
                  :fatherTabName="tabName"
                  :fatherStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                  :tabIndex="tabsList.findIndex(t => t.name === 'policyholder')"
                  anchorContainer=".appointmentTabPaneBox"
                  tabSource="policyholder"
                  ref="policyHolderInfoRef"
                  :fatherEditStatus="editStatus"
                  :customerInfo="customerInfo"
                  :apiPolicyholderInfoDto="appointmentSummeryInfo.apiPolicyholderInfoDto"
                  :idsObj="idsObj"
                  :customerBizId="props.processDetail.customerBizId"
                  :isExportAppointment="isExportAppointment"
                />
              </div>
              <!-- 受保人 -->
              <div v-if="tab.name === 'insurantInfo'">
                <!-- anchorContainer=".appointmentTabPaneBox" -->
                <Customer
                  :activeName="activeName"
                  :fatherTabName="tabName"
                  :fatherStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                  :tabIndex="tabsList.findIndex(t => t.name === 'insurantInfo')"
                  anchorContainer=".appointmentTabPaneBox"
                  tabSource="insurantInfo"
                  ref="insuredInfoRef"
                  :fatherEditStatus="editStatus"
                  :idsObj="idsObj"
                  :customerBizId="props.processDetail.customerBizId"
                  :customerInfo="customerInfo"
                  :apiInsurantInfoDto="appointmentSummeryInfo.apiInsurantInfoDto"
                  :isExportAppointment="isExportAppointment"
                />
              </div>
              <div v-if="tab.name === 'secondHolder'">
                <SecondHolderInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiSecondHolderInfoDto="appointmentSummeryInfo.apiSecondHolderInfoDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  :customerInfo="customerInfo"
                  ref="secondHolderInfoRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                  :tabIndex="tabsList.findIndex(t => t.name === 'secondHolder')"
                  anchorContainer=".appointmentTabPaneBox"
                  :fatherTabName="tabName"
                  :editStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                  :isExportAppointment="isExportAppointment"
                />
              </div>
              <div v-if="tab.name === 'beneficiary'">
                <BeneficiaryInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiBeneficiaryInfoFzDto="appointmentSummeryInfo.apiBeneficiaryInfoFzDto"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  ref="beneficiaryInfoRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                  :tabIndex="tabsList.findIndex(t => t.name === 'beneficiary')"
                  anchorContainer=".appointmentTabPaneBox"
                  :fatherTabName="tabName"
                  :editStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                  :isExportAppointment="isExportAppointment"
                />
              </div>
              <div v-if="tab.name === 'questionnaires'">
                <HealthInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :appointmentStatus="appointmentSummeryInfo.status"
                  ref="questionnairesInfoRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  :foldInsurantInfo="foldInsurantInfo"
                  :tabIndex="tabsList.findIndex(t => t.name === 'questionnaires')"
                  anchorContainer=".appointmentTabPaneBox"
                  :editStatus="editStatus"
                  :affixOffset="pageSource == 'fnaList' ? 360 : 250"
                />
              </div>
              <div v-if="tab.name === 'fna'">
                <FnaInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :pageSource="pageSource"
                />
              </div>
              <div v-if="tab.name === 'policyTransfer'">
                <PolicyTransferInfo
                  :activeName="activeName"
                  :formStatus="formStatus"
                  :idsObj="idsObj"
                  :apiAppointmentInfoDto="appointmentSummeryInfo.apiAppointmentInfoDto"
                  ref="policyTransferRef"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  @policyEditSuccess="getPolicyDetail"
                />
              </div>
              <div v-if="tab.name === 'accessories'">
                <FileUpload
                  :activeName="activeName"
                  :idsObj="idsObj"
                  :pageSource="pageSource"
                  :showSubmitBtn="showSubmitBtn"
                  ref="appointmentAccessoriesRef"
                />
              </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 === '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>
    <!-- 导入预约-->

    <CommonDialog
      dialogTitle="导入预约"
      cancleText="关闭"
      dialogWidth="50%"
      :openDialog="execlDialog"
      :showClose="true"
      @close="execlDialog = false"
      :showAction="false"
    >
      <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" :loading="exprotLoading">导入</el-button>
          </el-upload>
        </div>
      </div>
    </CommonDialog>
  </div>
</template>
<script setup name="AppointmentEdit">
import CommonDialog from '@/components/commonDialog'
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,
  appointmentEditStorage,
  appointmentEditStatus
} from '@/api/sign/appointment'
import { getPolicyfollow, getPolicyInfo, signName } from '@/api/sign/underwritingMain'
import {
  listTenantUser,
  getAdditionalProductList,
  getBankList,
  getUserSaleExpandList,
  secondAdditonalList,
  getAllSignList,
  uploadMaterialList
} 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
})
const submitLoading = ref(false)
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 appointmentAccessoriesRef = 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 exprotLoading = ref(false) //导入预约loading
const isExportAppointment = ref(false) //是否导入预约信息
const processInfo = ref({
  fnaNo: '暂无',
  status: '未完成',
  createTime: proxy.parseTime(new Date()),
  customerName: userStore.name
})
const editStatus = ref(null) //编辑状态
const execlDialog = ref(false)
const isEmbed = ref(false) //是否作为组件插入
const policyNo = ref('') //新单跟进保单号

const fileTableList = 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'
  }
])

const assetVerification = () => {
  proxy.$message.warning('此功能等待开放')
}
// 取消操作
const handleCancel = type => {
  let obj = {
    oprType: type == 'apply' ? 1 : 2, //操作类型 1-取消申请 2-取消预约
    appointmentBizId: idsObj.value.appointmentBizId, //预约信息主表唯一业务ID
    status: appointmentSummeryInfo.value.status //预约状态
  }
  proxy.$modal
    .confirm(`确认取消${type == 'apply' ? '申请' : '预约'}`)
    .then(function () {
      return appointmentEditStatus(obj)
    })
    .then(res => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('已成功取消')
        getAppointmentInfo(idsObj.value.appointmentBizId)
      }
    })
    .catch(() => {})
}
// 获取默认附件信息
const getFileList = () => {
  try {
    uploadMaterialList({ objectType: 'appointment' }).then(response => {
      fileTableList.value = response.data.map(item => {
        return {
          materialBizId: item.materialBizId,
          fileBizIdList: []
        }
      })
    })
  } catch (error) {
    fileTableList.value = []
    proxy.$message.error('附件列表获取失败')
  }
}
// 获取字典数据
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 []
  }
}

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)
    exprotLoading.value = true
    isExportAppointment.value = false
    const res = await uploadExcel(formData)
    if (res.code === 200) {
      appointmentSummeryInfo.value = res.data
      if (
        res.data.apiAppointmentInfoDto.isSecond == '0' ||
        res.data.apiAppointmentInfoDto.isSecond
      ) {
        appointmentSummeryInfo.value.apiSecondHolderInfoDto.isSecond =
          res.data.apiAppointmentInfoDto.isSecond
      }

      isExportAppointment.value = true
      proxy.$message.success('预约导入成功！！')
      console.log('导入预约信息', appointmentSummeryInfo.value)
      exprotLoading.value = false
      execlDialog.value = false
    }
  } catch (error) {
    exprotLoading.value = false
    proxy.$message.error(error.message)
  }

  return false // 阻止自动上传
}

const execlUpload = () => {
  // exprotLoading.value = true
  // let data = {
  //   // appointmentBizId: idsObj.value.appointmentBizId,
  //   file: currentFile.value
  // }
  // try {
  //   if (currentFile.value) {
  //     uploadExcel(data).then(res => {
  //       if (res.code == 200) {
  //         proxy.$message.success('预约导入成功')
  //         execlDialog.value = false
  //         exprotLoading.value = false
  //       }
  //     })
  //   }
  // } catch (error) {
  //   proxy.$message.error(error.message)
  //   exprotLoading.value = false
  // }
}
// 获取预约详情
function getAppointmentInfo(appointmentBizId, changeTab) {
  getAppointmentDetail(appointmentBizId).then(res => {
    if (res.code == 200) {
      editStatus.value = true
      //因为是否第二持有人放在了预约主体里，所以需要单独处理
      appointmentSummeryInfo.value = res.data
      if (
        res.data.apiAppointmentInfoDto.isSecond == '0' ||
        res.data.apiAppointmentInfoDto.isSecond
      ) {
        appointmentSummeryInfo.value.apiSecondHolderInfoDto.isSecond =
          res.data.apiAppointmentInfoDto.isSecond
      }

      let options = fetchDictData('csf_ap_status')
      options.forEach(item => {
        if (item.value == appointmentSummeryInfo.value.status) {
          processInfo.value.status = item.label
        }
      })
      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
      })
      dictStore.setSignNameList(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 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)
  }
}

// 获取下拉框所需要的数据
const getDictsLabelData = async () => {
  await proxy.useDictLists1([
    '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',
    'oss_data_type',
    'oss_data_person'
  ])
}
// Tab切换前的验证
const beforeTabLeave = async (activeTabName, oldTabName) => {
  foldInsurantInfo.value = false
  // 获取受保人数据
  let insuredData = null
  if (insuredInfoRef.value) {
    insuredData = await insuredInfoRef.value[0].getInsuredForm()
    // 健康信息得展示内容要根据受保人与投保人得关系展示
    if (activeTabName == 'questionnaires') {
      // 编辑状态下
      if (idsObj.value.appointmentBizId) {
        // 已经点过受保人这个tab
        if (insuredData && insuredData.policyholderRel && insuredData.policyholderRel == 'MYSELF') {
          foldInsurantInfo.value = true
        } else if (
          !insuredData &&
          appointmentSummeryInfo.value.apiInsurantInfoDto.policyholderRel == 'MYSELF'
        ) {
          foldInsurantInfo.value = true
        } else {
          foldInsurantInfo.value = false
        }
      } else {
        // 新增状态下
        if (!insuredData) {
          proxy.$message.error('请完善受保人信息')
          foldInsurantInfo.value = false
          return false
        }
        // 已经点过受保人这个tab
        if (insuredData && insuredData.policyholderRel && insuredData.policyholderRel == 'MYSELF') {
          foldInsurantInfo.value = true
        } else {
          foldInsurantInfo.value = false
        }
      }
    }
    return true
  }
}

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 =
      await productPlanRef.value[0].handleSubmitForm()

    if (!submitAppointmentObj.value.apiProductPlanInfoDto && isExportAppointment.value) {
      proxy.$message.error('请确认产品计划信息')
      return
    }
    if (!submitAppointmentObj.value.apiProductPlanInfoDto) {
      proxy.$message.error('请完善产品计划信息')
      return
    }
  }

  // 获取投保人form
  if (policyHolderInfoRef.value) {
    submitAppointmentObj.value.apiPolicyholderInfoDto =
      await policyHolderInfoRef.value[0].handleFormValues('policyHolderInfoRef')
    console.log(submitAppointmentObj.value.apiPolicyholderInfoDto)

    if (!submitAppointmentObj.value.apiPolicyholderInfoDto && isExportAppointment.value) {
      proxy.$message.error('请确认投保人信息')
      return
    }
    if (!submitAppointmentObj.value.apiPolicyholderInfoDto) {
      proxy.$message.error('请确认投保人信息')
      return
    }
  }

  // 获取受保人form
  if (insuredInfoRef.value) {
    submitAppointmentObj.value.apiInsurantInfoDto =
      await insuredInfoRef.value[0].handleFormValues('insuredInfoRef')

    console.log('受保人', submitAppointmentObj.value.apiInsurantInfoDto)
    if (!submitAppointmentObj.value.apiInsurantInfoDto && isExportAppointment.value) {
      proxy.$message.error('请确认受保人信息')
      return
    }
    if (!submitAppointmentObj.value.apiInsurantInfoDto) {
      proxy.$message.error('请完善受保人信息')
      return
    }
  }
  if (beneficiaryInfoRef.value) {
    submitAppointmentObj.value.apiBeneficiaryInfoFzDto =
      await beneficiaryInfoRef.value[0].handleFormValues()
    if (!submitAppointmentObj.value.apiBeneficiaryInfoFzDto && isExportAppointment.value) {
      proxy.$message.error('请确认受益人信息')
      return
    }
    if (!submitAppointmentObj.value.apiBeneficiaryInfoFzDto) {
      proxy.$message.error('请完善受益人信息')
      return
    }
  }
  if (secondHolderInfoRef.value) {
    submitAppointmentObj.value.apiSecondHolderInfoDto =
      await secondHolderInfoRef.value[0].handleFormValues()
    if (!submitAppointmentObj.value.apiSecondHolderInfoDto && isExportAppointment.value) {
      proxy.$message.error('请确认第二持有人信息')
      return
    }
    if (!submitAppointmentObj.value.apiSecondHolderInfoDto) {
      proxy.$message.error('请完善第二持有人信息')
      return
    } else {
      submitAppointmentObj.value.apiAppointmentInfoDto.isSecond =
        submitAppointmentObj.value.apiSecondHolderInfoDto.isSecond
    }
  }

  if (questionnairesInfoRef.value) {
    submitAppointmentObj.value.apiAnswerSaveRequest =
      await questionnairesInfoRef.value[0].handleFormValues()
    if (!submitAppointmentObj.value.apiAnswerSaveRequest) {
      submitAppointmentObj.value.apiAnswerSaveRequest = null
    }
  }
  if (appointmentAccessoriesRef.value && !idsObj.value.appointmentBizId) {
    submitAppointmentObj.value.materialDtoList =
      appointmentAccessoriesRef.value[0].handleFormValues()
    if (submitAppointmentObj.value.materialDtoList.length == 0) {
      submitAppointmentObj.value.materialDtoList = fileTableList.value
    }
  }
  console.log('大提交', submitAppointmentObj.value)

  // 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
    console.log('大提交', submitAppointmentObj.value)
    // return
    if (type == 'submit') {
      submitLoading.value = true
      // 新增预约单
      addAppointment(submitAppointmentObj.value).then(res => {
        if (res.code == 200) {
          submitLoading.value = false
          proxy.$message.success('预约成功')
          editStatus.value = false
          emit('handleSuccess', {
            tab: 'appointment',
            type: 'add'
          })
        }
      })
    }
  }
  // 代表修改预约单 因为编辑暂存也会有预约id
  if (idsObj.value.appointmentBizId && type == 'submit') {
    // 已生成行程单的方式预约提交
    if (route.query.appointmentType == '2') {
      submitAppointmentObj.value.source = 2
    }
    submitLoading.value = true
    // 编辑预约单
    editAppointmentDetail(submitAppointmentObj.value).then(res => {
      if (res.code == 200) {
        submitLoading.value = false
        editStatus.value = true
        getAppointmentInfo(idsObj.value.appointmentBizId)
        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
    submitLoading.value = true
    // 暂存预约单
    storageAppointment(submitAppointmentObj.value).then(res => {
      if (res.code == 200) {
        submitLoading.value = false
        proxy.$message.success('预约暂存成功')
        router.push({ path: '/sign/appointment' })
      }
    })
  }
  // 编辑状态下预约暂存
  if (type == 'editStorage') {
    submitLoading.value = true
    // 暂存预约单
    appointmentEditStorage(submitAppointmentObj.value).then(res => {
      if (res.code == 200) {
        submitLoading.value = false
        proxy.$message.success('预约暂存提交成功')
        editStatus.value = true
        getAppointmentInfo(idsObj.value.appointmentBizId)
      }
    })
  }
}
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()
  ;(async () => {
    await getDictsLabelData()
    // 字典加载完成后再请求详情
    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 - 400px)'
  }
})

// 预约作为组件在别的地放提交成功后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'
          },
          {
            label: '健康信息',
            name: 'questionnaires',
            id: 7,
            status: '0',
            key: 'questionnaireBizId'
          },
          {
            label: '附件', //大提交的时候不用提交了，因为上传文件的时候已经入库了
            name: 'accessories',
            id: 10,
            status: '0',
            key: 'fnaBizId'
          }
        ]

        nextTick(() => {
          activeName.value = 'appointmentInfo'
        })
      } else {
        activeName.value = ''
        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)
    })
}
// 根据页面来源的不同控制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
  console.log('route.query', route.query)
} else if (route.query.source == 'policyList') {
  editStatus.value = true
} else if (route.query.source == 'fnaList' && route.query.appointmentBizId) {
  idsObj.value.appointmentBizId = route.query.appointmentBizId
  getAppointmentInfo(route.query.appointmentBizId)
  editStatus.value = true
} else if (route.query.source == 'fnaList' && !route.query.appointmentBizId) {
  editStatus.value = false
}
getFileList()
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
})
</script>
<style lang="scss" scoped>
:deep(.el-card) {
  border: none !important;
}
:deep(.el-input-group__append),
:deep(.el-input-group__prepend) {
  background-color: #fff !important;
}
.noembed-container {
  padding: 10px 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;
            }
          }
        }
      }
    }
    .right {
      display: flex;
      align-items: center;
    }
  }
  .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;
    position: relative;
  }

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