<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="cardHeader">
        <div class="left">
          <img class="iconBox" src="@/assets/images/icon1.png" alt="" />
          <div class="rightBox">
            <div class="num">{{ processInfo.fnaNo || '--' }}</div>
            <div class="bottom">
              <div class="status">{{ processInfo.status || '--' }}</div>
              <div class="time">
                <span class="iconfont icon-yanqiweiwancheng"></span>
                <span
                  >{{ parseTime(processInfo.createTime) }} 由{{
                    processInfo.customerName || '--'
                  }}创建</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="tabsBox">
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          :before-leave="beforeTabLeave"
          ref="tabPaneRef"
        >
          <el-tab-pane
            v-for="(tab, tIndex) in tabsList"
            :key="tab.name"
            :label="tab.label"
            :name="tab.name"
          >
            <!-- 注意tabPaneBox这个类名与子组件的锚点定位相关，不能轻易改动 -->
            <div :class="{ tabPaneBox: activeName !== 'appointment' }">
              <div v-if="tab.name === 'overview'" class="overviewBox">
                <div
                  class="oneItem"
                  v-for="item in tabsList.filter(item => item.id !== -1 && item.status)"
                  :key="item.id"
                  @click="handleStep(item)"
                >
                  <div
                    class="circle"
                    :class="{
                      finfishCircle: item.status == '1',
                      unFinishCircle: item.status == '0'
                    }"
                  >
                    <el-icon v-if="item.status == '1'"><Check /></el-icon>
                    <span v-else>{{ item.id }}</span>
                  </div>
                  <div
                    class="title"
                    :class="{
                      finfishTitle: item.status == '1',
                      unFinishTitle: item.status == '0'
                    }"
                  >
                    {{ item.label }}
                  </div>
                  <div
                    class="status"
                    :class="{
                      finfishStatus: item.status == '1',
                      unFinishStatus: item.status == '0'
                    }"
                  >
                    {{ item.status == '1' ? '已完成' : '未完成' }}
                  </div>
                  <div class="operation">
                    <el-icon class="editIcon" v-if="item.status == '0'"><EditPen /></el-icon>
                    <div
                      :class="{
                        finfishOperation: item.status == '1',
                        unFinishOperation: item.status == '0'
                      }"
                    >
                      {{ item.status == '1' ? '点击查看详情' : '去填写' }}
                    </div>
                  </div>
                </div>
              </div>
              <Customer
                v-if="tab.name === 'customer'"
                :activeName="activeName"
                :customerBizId="processInfo.customerBizId"
                @handleSuccess="handleSuccess"
                :tabIndex="tabsList.findIndex(t => t.name === 'customer')"
                anchorContainer=".tabPaneBox"
                tabSource="customer"
              />
              <div v-if="tab.name === 'fnaform'">
                <FanForm
                  :activeName="activeName"
                  :fnaFormBizId="processInfo.fnaFormBizId"
                  :customerBizId="processInfo.customerBizId"
                  :dictTypeLists="dictTypeLists"
                  :customerInfo="customerInfo"
                  @handleSuccess="handleSuccess"
                  :tabIndex="tabsList.findIndex(t => t.name === 'fnaform')"
                  anchorContainer=".tabPaneBox"
                  tabSource="fnaform"
                />
              </div>
              <div v-if="tab.name === 'appointment'">
                <AppointmentEdit
                  :embed="true"
                  editStatus="add"
                  :tabName="activeName"
                  :processDetail="processInfo"
                  @handleSuccess="handleSuccess"
                  source="fnaList"
                />
              </div>
              <div v-if="tab.name === 'newpolicy'">关联新单内容</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>
<script setup name="FnaEdit">
import { processUserName } from '@/utils/common'
import AppointmentEdit from '@/views/sign/appointment/appointmentEdit'
import useUserStore from '@/store/modules/user'
import useDictStore from '@/store/modules/dict'
import { addFna, getProcessDetail, updateProcess, getCustomerDetail } from '@/api/sign/fna'
import {
  listTenantUser,
  getAdditionalProductList,
  getBankList,
  getUserSaleExpandList,
  secondAdditonalList,
  getAllSignList,
  getAllTeam,
  getInsuranceCompany
} from '@/api/common'
import Customer from './components/customer'
import FanForm from './components/fanForm'

import { Check } from '@element-plus/icons-vue'
import { ref } from 'vue'
const userStore = useUserStore()
const dictStore = useDictStore()
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const activeName = ref('overview')
const processInfo = ref({
  fnaNo: '--',
  status: '未保存',
  createTime: proxy.parseTime(new Date()),
  customerName: userStore.name
}) // 流程详情信息
const updateStatus = ref(false)
const dictTypeLists = ref([])
const customerInfo = ref({})
const tabPaneRef = ref(null)
const tabsList = ref([
  {
    label: '总览',
    name: 'overview',
    id: -1
  },
  {
    label: '客户资料',
    name: 'customer',
    id: 1,
    status: '0',
    key: 'customerBizId'
  },
  {
    label: 'FNAform',
    name: 'fnaform',
    id: 2,
    status: '0',
    key: 'fnaFormBizId'
  },
  {
    label: '关联预约',
    name: 'appointment',
    id: 3,
    status: '0',
    key: 'appointmentBizId'
  }
  // {
  //   label: '关联新单',
  //   name: 'newpolicy',
  //   id: 4,
  //   status: '0',
  //   key: 'policyBizld'
  // }
  // {
  //   label: '关联保单',
  //   name: 'policy',
  //   id: 5,
  //   status: '0',
  //   key: 'policyNo'
  // }
])

const { csf_fna_status } = proxy.useDict('csf_fna_status')
// 获取各个流程所需要得字典数据
const getDictsData = async () => {
  // 获取租户用户列表
  const params1 = {
    tenantBizId: userStore.projectInfo.tenantBizId,
    pageNo: 1,
    pageSize: 10
  }
  const response1 = await listTenantUser(params1)
  if (response1.code == 200) {
    let result = processUserName(response1.data.records)
    result = result.map(item => {
      return {
        value: item.userBizId,
        label: item.showName
      }
    })
    dictStore.setTenantUserList(result)
  }
  const params2 = {
    loginTenantBizId: userStore.projectInfo.tenantBizId,
    pageNo: 1,
    pageSize: 10
  }

  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) {
    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 params8 = {
    pageNo: 1,
    pageSize: 99999
  }
  const response8 = await getAllTeam(params8)
  if (response8.code == 200) {
    response8.data.records = response8.data.records.map(item => {
      return {
        ...item,
        label: item.teamName,
        value: item.teamBizId
      }
    })
    dictStore.setAllTeaList(response8.data.records)
  }
  const params9 = {
    pageNo: 1,
    pageSize: 99999
  }
  const response9 = await getInsuranceCompany(params9)
  if (response9.code == 200) {
    response9.data.records = response9.data.records.map(item => {
      return {
        ...item,
        label: item.fullName,
        value: item.insuranceCompanyBizId
      }
    })
    dictStore.setAllInsuranceCompanyList(response9.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',
    'wj_question_first_category',
    'wj_question_second_category',
    'csf_ap_policy_transfer',
    'md_bank',
    'csf_property_type',
    'oss_data_type',
    'oss_data_person'
  ])
}

// 更新流程
const processUpdate = (data, status) => {
  updateProcess(data).then(res => {
    if (res.code == 200) {
      updateStatus.value = false
      console.log('更新流程', res)

      // 获取流程详情
      getProcessInfo(data.fnaBizId, status)
    }
  })
}

// 获取流程详情
function getProcessInfo(fnaBizId, changeTab, currentTab) {
  getProcessDetail(fnaBizId).then(res => {
    if (res.code == 200) {
      processInfo.value = res.data
      tabsList.value.forEach(item => {
        if (res.data[item.key] && item.status) {
          item.status = '1'
        } else {
          item.status = '0'
        }
      })
      csf_fna_status._object.csf_fna_status.forEach(item => {
        if (item.value == res.data.status) {
          processInfo.value.status = item.label
        }
      })
      if (currentTab == 'appointment' && changeTab == 'appointment') {
        router.push({ path: '/sign/appointment' })
      } else if (changeTab) {
        activeName.value = changeTab
      }
    }
  })
}
// Tab切换前的验证
const beforeTabLeave = (activeTabName, oldTabName) => {
  if (processInfo.value.customerBizId) {
    // getCustomerInfo(processInfo.value.customerBizId)
  }
  // 如果切换到总览，始终允许
  if (activeTabName === 'overview' || activeTabName === 'customer') {
    return true
  }

  // 获取当前要切换到的tab
  const targetTab = tabsList.value.find(tab => tab.name === activeTabName)
  // 如果目标tab不存在，阻止切换
  if (!targetTab) {
    return false
  }
  // 检查前一项状态
  const prevTabIndex = tabsList.value.findIndex(tab => tab.name === activeTabName) - 1
  if (prevTabIndex >= 0) {
    const prevTab = tabsList.value[prevTabIndex]
    // 如果前一项存在且未完成，阻止切换
    if (prevTab.status === '0') {
      proxy.$modal.confirm(`请先填写${prevTab.label}`, { showCancel: '0', title: '填写提示' })
      return false
    }
  }

  return true
}

// 处理步骤点击
const handleStep = item => {
  // 总览页可以直接切换
  if (item.id === -1 || item.name === 'customer') {
    activeName.value = item.name
    return
  }
  // 检查前一项状态
  const prevTabIndex = tabsList.value.findIndex(tab => tab.id === item.id) - 1
  if (prevTabIndex >= 0) {
    const prevTab = tabsList.value[prevTabIndex]

    // 如果前一项存在且未完成，阻止切换
    if (prevTab.status === '0') {
      proxy.$modal.confirm(`请先填写${prevTab.label}`, { showCancel: false })
      return
    }
  }

  // 允许切换
  activeName.value = item.name
}
const handleBack = () => {
  router.go(-1)
}

if (route.query.type == 'add') {
  // getAddInfo()
} else if (route.query.type == 'edit') {
  setTimeout(() => {
    getProcessInfo(route.query.fnaBizId)
  }, 100)
}
// 获取客户详情
function getCustomerInfo(customerBizId) {
  getCustomerDetail(customerBizId).then(async res => {
    if (res.code == 200) {
      customerInfo.value = res.data
    }
  })
}
const handleSuccess = info => {
  switch (info.tab) {
    case 'customer':
      if (info.type == 'add') {
        //客户提交成功，更新流程
        processUpdate({ fnaBizId: info.fnaBizId, customerBizId: info.customerBizId }, 'fnaform')
      } else {
        processUpdate({ fnaBizId: processInfo.value.fnaBizId, customerBizId: info.customerBizId })
      }
      getCustomerInfo(info.customerBizId)
      break
    case 'fnaform':
      if (info.type == 'add') {
        //客户提交成功，更新流程
        processUpdate(
          {
            fnaBizId: processInfo.value.fnaBizId,
            customerBizId: info.customerBizId,
            fnaFormBizId: info.fnaFormBizId
          },
          'appointment'
        )
      } else {
        processUpdate({
          fnaBizId: processInfo.value.fnaBizId,
          customerBizId: info.customerBizId,
          fnaFormBizId: info.fnaFormBizId
        })
      }
      break
    case 'appointment':
      if (info.type == 'add') {
        getProcessInfo(processInfo.value.fnaBizId, 'appointment', 'appointment')
      } else {
      }
      break
    case 'newpolicy':
      break
    case 'policy':
      break
    default:
      break
  }
}
getDictsData()
</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;
}

.app-container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 84.5px);
  padding: 20px;
  background-color: #f2f3f5;
  .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 {
    .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;
        }
      }
    }
  }

  .tabPaneBox {
    height: calc(100vh - 280px);
    overflow-y: auto;
    padding-right: 10px;
    position: relative;
  }

  /* 确保滚动区域有正确的滚动行为 */
  .tabPaneBox {
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
  }

  /* 隐藏滚动条但保留功能 */
  .tabPaneBox::-webkit-scrollbar {
    width: 6px;
  }

  .tabPaneBox::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  .tabPaneBox::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  .tabPaneBox::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
  .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;
    }
  }
}
</style>
