<template>
  <div class="app-container">
    <!-- <div>
      <el-button type="primary" icon="Back" @click="handleBack" style="margin-bottom: 10px"
        >返回</el-button
      >
    </div> -->

    <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 class="right">
          <el-button
            :disabled="!(processInfo.customerBizId && processInfo.fnaFormBizId)"
            type="success"
            :icon="Check"
            >{{ processInfo.appointmentBizId ? '已预约' : '立即预约' }}</el-button
          >
          <el-button
            :disabled="!(processInfo.customerBizId && processInfo.fnaFormBizId)"
            type="primary"
            plain
            >生成副本</el-button
          >
        </div> -->
      </div>
      <div class="tabsBox">
        <el-tabs v-model="activeName" 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="{ 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"
                :fearthStatus="route.query.type"
                :customerBizId="processInfo.customerBizId"
                @handleSuccess="handleSuccess"
              />
              <div v-if="tab.name === 'fnaform'">
                <FanForm
                  :activeName="activeName"
                  :fearthStatus="route.query.type"
                  :fnaFormBizId="processInfo.fnaFormBizId"
                  :customerBizId="processInfo.customerBizId"
                  :dictTypeLists="dictTypeLists"
                  :customerInfo="customerInfo"
                  @handleSuccess="handleSuccess"
                />
              </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 { onUnmounted } from 'vue'
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, getInsuranceProductList, getAdditionalProductList } 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 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) {
    dictStore.setTenantUserList(response1.data.records)
  }
  const params2 = {
    loginTenantBizId: userStore.projectInfo.tenantBizId,
    pageNo: 1,
    pageSize: 10
  }

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

  const response3 = await getAdditionalProductList(params3)
  if (response3.code == 200) {
    response3.data.records = response3.data.records.map(item => {
      return {
        ...item,
        label: item.productName,
        value: item.additionalProductBizId
      }
    })
    dictStore.setAdditionalProductList(response3.data.records)
  }
  // 请求每个流程中所涉及到的字典值数据
  proxy.useDictLists([
    'csf_employment',
    'sys_no_yes',
    'bx_currency_type',
    'csf_liquid_asset_type',
    'csf_premium_funding_source',
    'csf_customer_type',
    'csf_customer_title',
    'sys_gender',
    'csf_marriage',
    'csf_education',
    'csf_id_type',
    'csf_ap_apply_type',
    'csf_ap_meeting_point',
    'csf_ap_first_issue',
    'csf_ap_dividend',
    'csf_ap_frequency',
    'csf_ap_rel',
    'csf_ap_registration',
    'csf_ap_exercise',
    'csf_ap_risk',
    'csf_ap_movie',
    'csf_ap_game',
    'wj_question_first_category',
    'wj_question_second_category',
    'csf_ap_policy_transfer',
    'md_bank'
  ])
}

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

      // 获取流程详情
      getProcessInfo(data.fnaBizId, status)
    }
  })
}
// 新建流程
// const getAddInfo = () => {
//   addFna({ remark: '' }).then(res => {
//     if (res.code == 200) {
//       // 获取流程详情
//       getProcessInfo(res.data.fnaBizId)
//     }
//   })
// }
// 获取流程详情
function getProcessInfo(fnaBizId, changeTab) {
  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 (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, 'newpolicy')
      } else {
      }
      break
    case 'newpolicy':
      break
    case 'policy':
      break
    default:
      break
  }
}
getDictsData()
</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;
}

.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 - 317px); */
    height: calc(100vh - 275px);
    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;
    }
  }
}
</style>
