<script setup name='handleDuringExamine'>
import { ref, onMounted, reactive, getCurrentInstance, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FlowRecord from '../components/flowRecord.vue'
import AuditDialog from '../components/auditDialog.vue'
import ProjectInfo from '@/pages/projectStoreManage/projectStore/projectDetail/components/projectInfo.vue'
import { handler, progressDetail, projectDetail } from '@/http/apis/toDoCenter/todoList'
import { storeToRefs } from 'pinia'
import store from '@/store'
import FinalInfo from '@/pages/projectStoreManage/projectStore/projectDetail/components/finalInfo.vue'
import DelayApplyInfo from '@/pages/projectStoreManage/projectStore/projectDetail/components/delayApplyInfo.vue'
import WantReadInfo from '@/pages/projectStoreManage/projectStore/projectDetail/components/wantReadInfo.vue'
import SjFlowRecord from '@/pages/projectStoreManage/projectStore/projectDetail/components/sjFlowRecord.vue'
import ChangeInfoDialog from '@/pages/toDoCenter/handleDuringExamine/components/changeInfoDialog.vue'
import { dictionary } from '@/http/apis/projectCollection/projectCollectionEnter'
const
  userInfo = storeToRefs(store.userStore).userInfo || {},
  { proxy } = getCurrentInstance(),
  route = useRoute(),
  router = useRouter(),
  // 获取审核详情
  lastData = ref(), // 当前审核人节点
  preData = ref(), // 上一个审核人节点
  flowData = ref({
    processProgressVo: {
      progressInfo: []
    }
  }),
  getFlowData = async (taskId) => {
    const res = await progressDetail({ ...route.query, taskId: taskId || route.query.taskId })
    if (res.data.status === '被撤回') {
      router.go(-1)
      return
    }
    flowData.value = {
      ...res.data,
      processProgressVo: {
        ...res.data.processProgressVo,
        progressInfo: changeProgressInfo(res.data.processProgressVo.progressInfo)
      }
    }
    lastData.value = getLastData(flowData.value.processProgressVo.progressInfo)
    preData.value = getPreData(flowData.value.processProgressVo.progressInfo)
  },
  changeProgressInfo = (data) => {
    data.forEach(res => {
      if (res.children) {
        const nodeIds = []
        const newChildren = []
        res.children.forEach(child => {
          if (!nodeIds.includes(child.nodeId)) {
            nodeIds.push(child.nodeId)
            newChildren.push({
              nodeId: child.nodeId,
              approvalMode: child.approvalMode,
              name: child.name,
              nodeType: child.nodeType,
              list: [{ ...child }],
              userIds: [child.userId]
            })
          } else {
            newChildren.find(i => i.nodeId === child.nodeId).list.push(child)
            newChildren.find(i => i.nodeId === child.nodeId).userIds.push(child.userId)
          }
        })

        res.children = newChildren
      } else {
        res['userIds'] = [res.userId]
      }
    })
    return data
  },
  // 并行分支处理
  // getChildren = (data) => {
  //   const nodeIds = []
  //   const newChildren = []
  //   data.forEach(child => {
  //     if (!nodeIds.includes(child.nodeId)) {
  //       nodeIds.push(child.nodeId)
  //       newChildren.push({
  //         nodeId: child.nodeId,
  //         approvalMode: child.approvalMode,
  //         name: child.name,
  //         nodeType: child.nodeType,
  //         list: [{ ...child }],
  //         userIds: [child.userId]
  //       })
  //     } else {
  //       newChildren.find(i => i.nodeId === child.nodeId).list.push(child)
  //       newChildren.find(i => i.nodeId === child.nodeId).userIds.push(child.userId)
  //     }
  //   })
  //   return newChildren
  // },
  // changeProgressInfo1 = (data) => {
  //   const newData = []
  //   const startTimes = []
  //   data.forEach(res => {
  //     if (res.nodeType === 'ROOT') {
  //       newData.push({
  //         ...res,
  //         userIds: [res.userId]
  //       })
  //     } else {
  //       if (!startTimes.includes(res.startTime)) {
  //         startTimes.push(res.startTime)
  //         newData.push({
  //           startTime: res.startTime,
  //           parallelChildren: [{ ...res, children: res.children?.length ? getChildren(res.children) : [] }]
  //         })
  //       } else {
  //         newData.find(i => i.nodeType !== 'ROOT' && i.startTime === res.startTime).parallelChildren.push({
  //           ...res,
  //           children: res.children?.length ? getChildren(res.children) : []
  //         })
  //       }
  //     }
  //   })
  //   return newData
  // },
  // 获取最后一个审批节点
  getLastData = (res) => {
    const data = res.map(i => {
      return {
        ...i,
        children: i.children ? i.children.filter(r => r.nodeType !== 'CC') : undefined
      }
    })
    return data.slice(-1)[0]?.children?.slice(-1)[0] || data.slice(-1)[0]
  },
  // 获取上一个审核人节点
  getPreData = (res) => {
    const data = res.map(i => {
      return {
        ...i,
        children: i.children ? i.children.filter(r => r.nodeType !== 'CC') : undefined
      }
    })
    if (data.slice(-1)[0] && data.slice(-1)[0].children && data.slice(-1)[0].children.length > 1) {
      return data.slice(-1)[0].children.slice(-2, -1)[0]
    } else {
      if (data.slice(-2, -1)[0]?.children?.length) {
        return data.slice(-2, -1)[0].children.slice(-1)[0]
      } else {
        return data.slice(-2, -1)[0]
      }
    }
  },
  // 审核弹窗
  dialogData = reactive({
    visible: false,
    title: undefined,
    taskId: undefined,
    action: undefined
  }),
  showDialog = async (title, action) => {
    dialogData.visible = true
    dialogData.title = title
    dialogData.taskId = route.query.taskId
    // dialogData.taskId = lastData.value?.list?.find(i => i.userId === userInfo.value.employeeCode).taskId || lastData.value.taskId
    dialogData.action = action
    dialogData.constructionSuggestions = flowData.value.constructionSuggestions
    dialogData.projectCode = detailData.value.projectCode
  },
  close = () => {
    dialogData.visible = false
  },
  // 撤回
  withdraw = () => {
    proxy.$messageBox
      .confirm('是否撤回该意见?', '提示！', {
        type: 'warning'
      })
      .then(async () => {
        const res = await handler({
          instanceId: route.query.instanceId,
          projectId: route.query.projectId,
          projectCode: detailData.value.projectCode,
          action: 'WITHDRAW',
          taskId: route.query.taskId
        })
        if (res.data === 'TASKID_ERROR') {
          proxy.$message.warning('当前审批任务有变动，请返回待我处理列表！')
          router.push({ name: 'waitMeToHandle' })
        } else {
          proxy.$message.success('撤回成功！')
          if (res.data) {
            router.push({
              query: {
                ...route.query,
                taskId: res.data
              }
            })
          }
          await nextTick()
          reload(res.data)
        }
      })
  },
  // 获取撤回的taskId
  getPreDataTaskId = () => {
    let taskId = preData.value && preData.value?.list?.find(i => i.userId === userInfo.value.employeeCode)?.taskId || preData.value.taskId
    if (taskId === 'root') {
      const children = flowData.value.processProgressVo.progressInfo?.[1]?.children
      if (children[0]?.approvalMode === 'AND') {
        const data = children[0].list.filter(i => i.result && i.userId === userInfo.value.employeeCode)
        taskId = data?.length && data[0].taskId || 'root'
      }
    }
    return taskId
  },
  isWithDraw = () => {
  // 部门联合审批流程不能撤回发起
    return !(flowData.value.processProgressVo.processDefName === '部门联合审批流程' && getPreDataTaskId() === 'root') && flowData.value.canWithdraw
  },
  // 项目详情
  detailData = ref({}),
  getDetail = async () => {
    const res = await projectDetail(route.query.projectId)
    detailData.value = res.data
    detailData.value.baseHistorProjs = res.data?.baseHistorProjId?.split('；').map((i, k) => {
      return {
        baseProjId: i,
        baseProjName: res.data?.baseHistorProjName.split('；')[k],
        baseProjSetYear: res.data?.baseHistorProjYear.split('；')[k]
      }
    }) || []
  },
  // 重新加载
  reload = (taskId) => {
    getDetail()
    getFlowData(taskId)
    loading.value = false
  },
  // 去盖章并通过页
  toSealAndPass = () => {
    router.push({ name: 'stamp', query: { projectId: route.query.projectId, instanceId: route.query.instanceId, taskId: route.query.taskId, fileId: detailData.value.pretrialFileId, instName: flowData.value?.processProgressVo?.processDefName, projectCode: detailData.value.projectCode }})
  },
  loading = ref(true),
  // 省级联审
  flowTabActiveName = ref('1'),
  handleFlowTabChange = (val) => {
    flowTabActiveName.value = val
  },
  // 变更信息
  changeInfoDialogData = reactive({
    visible: false,
    id: route.query.projectId
  }),
  showChangeDialog = () => {
    changeInfoDialogData.visible = true
  },
  dictionaryList = ref([])
onMounted(async () => {
  reload()
  dictionaryList.value = (await dictionary()).data
  await store.countStore.setCountStore()
})
</script>
<template>
  <div v-loading="loading" class="footerPage">
    <el-card
      class="mb-16"
      shadow="never"
    >
      <div class="card-header relative">
        <div class="flex justify-between">
          <div class="flex-1">
            <p class="font-bold">{{ detailData.projectName }}的{{ flowData.processProgressVo.processDefName }}</p>
            <div class="mt-8 search">
              <el-form label-suffix=":">
                <el-row :gutter="24">
                  <el-col :span="8">
                    <el-form-item label="发起人">{{ flowData.processProgressVo.progressInfo.find(i=>i.nodeId==='root')?.user.userName }}</el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="主管单位">{{ flowData.processProgressVo.progressInfo.find(i=>i.nodeId==='root')?.user.orgName }}</el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="发起时间">{{ flowData.processProgressVo.startTime }}</el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
          <svg-icon
            :name="`${flowData?.status==='审核中'?'underReview':flowData?.status==='审核通过'?'beApproved':flowData?.status==='被驳回'?'beRejected':flowData?.status==='被撤回'?'beWithdraw':flowData?.status==='被退回'?'beBack':''}`"
            style="width:160px;height: 132px;right:-20px"
            class="absolute top-2/4 -translate-y-1/2"
          />
        </div>
      </div>
    </el-card>
    <el-alert
      v-if="flowData.isChange"
      type="info"
      show-icon
      style="margin-bottom: 16px"
      :closable="false"
    >
      <template #title>
        <p>温馨提示：该流程为复审流程，<a @click="showChangeDialog">点击查看</a> 该项目调整的信息以及审核意见</p>
      </template>
    </el-alert>
    <el-card v-if="detailData?.id&&flowData.processProgressVo.processDefName==='申请延期审批流程'" class="mb-16">
      <delay-apply-info
        :detail-data="detailData"
      />
    </el-card>
    <el-card v-else-if="detailData?.id&&flowData.processProgressVo.processDefName==='申请借阅审批流程'" class="mb-16">
      <want-read-info
        :detail-data="detailData"
      />
    </el-card>
    <el-card v-else-if="detailData?.id&&flowData.processProgressVo.processDefName==='验收申报审批流程'" shadow="never" class="mb-16">
      <final-info :detail-data="detailData" />
    </el-card>
    <project-info
      v-else
      :detail-data="detailData"
      :dictionary-list="dictionaryList"
      class="mb-16"
    />
    <el-card
      :class="`relative pb-32 flowCard ${detailData.area==='市本级'&&detailData.declareAmount>=1000&&flowData.processProgressVo.processDefName==='重大项目联审确认流程'?'tab-card':''}`"
      shadow="never"
    >
      <template #header>
        <el-tabs v-if="detailData.area==='市本级'&&detailData.declareAmount>=1000&&flowData.processProgressVo.processDefName==='重大项目联审确认流程'" v-model="flowTabActiveName" @tab-change="handleFlowTabChange">
          <el-tab-pane label="流程记录" name="1" />
          <el-tab-pane label="省级部门联审流程记录" name="2" />
        </el-tabs>
        <span v-else>流程记录</span>
      </template>
      <flow-record v-if="flowTabActiveName==='1'" :flow-data="flowData.processProgressVo.progressInfo" />
      <el-form v-else-if="flowTabActiveName==='2'" label-suffix=":">
        <sj-flow-record :flow-data="detailData.sjlsResult?JSON.parse(detailData.sjlsResult):[]" />
      </el-form>
    </el-card>
    <div class="footer">
      <div
        v-if="flowData?.status==='审核中'&&route.name==='handleDuringExamine'"
        class="flex justify-between absolute bottom-0 botBtn"
      >
        <div>
          <p v-if="detailData.area==='市本级'&&detailData.declareAmount>=1000&&flowData.processProgressVo.processDefName==='重大项目联审确认流程'" class="text-12 font-bold">根据联审意见，该项目的建设方案通过情况为：</p>
          <div v-if="flowData.isHighLine&&userInfo.regionCode==='330500'&&detailData.areaCode!=='330500'&&flowData.processProgressVo.processDefName==='建设方案审批流程'&&flowData.canPass" class="flex items-center">
            <el-button
              v-if="flowData.canPass"
              type="primary"
              @click="showDialog('通过','PASS')"
            >意见流转</el-button>
            <el-button @click="router.go(-1)">返回</el-button>
          </div>
          <div v-else class="flex items-center">
            <el-button
              v-if="flowData.canPass"
              type="primary"
              @click="showDialog('通过','PASS')"
            >通过</el-button>
            <el-button
              v-if="flowData.canSeal"
              type="primary"
              @click="toSealAndPass"
            >盖章并通过</el-button>
            <el-button
              v-if="flowData.canReject"
              plain
              type="danger"
              @click="showDialog('驳回','REJECT')"
            >驳回
            </el-button>
            <el-button @click="router.go(-1)">返回</el-button>
            <el-dropdown
              v-if="((flowData.canPass||flowData.canReject||flowData.canSeal)&&(flowData.processProgressVo.processDefName!=='申请延期审批流程')&&flowData.processProgressVo.processDefName!=='申请借阅审批流程')||isWithDraw()"
              size="small"
              type="primary"
              class="ml-6"
            >
              <span class="el-dropdown-link">
                <span class="flex items-center more">
                  <svg-icon name="moreIcon" class="mr-8" />
                  <span>更多</span>
                </span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="isWithDraw()">
                    <el-button
                      plain
                      type="primary"
                      @click="withdraw"
                    >撤回</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="(flowData.canPass||flowData.canReject||flowData.canSeal)&&flowData.processProgressVo.processDefName!=='申请延期审批流程'&&flowData.processProgressVo.processDefName!=='申请借阅审批流程'">
                    <el-button
                      plain
                      type="danger"
                      @click="showDialog('退回','BACK')"
                    >退回</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      <div
        v-else
        class="flex justify-center absolute bottom-0 botBtn"
      >
        <el-button @click="router.go(-1)">返回</el-button>
        <el-button
          v-if="isWithDraw()"
          plain
          type="primary"
          @click="withdraw"
        >撤回</el-button>
      </div>
    </div>
  </div>
  <audit-dialog
    :visible="dialogData.visible"
    :title="dialogData.title"
    :action="dialogData.action"
    :task-id="dialogData.taskId"
    :construction-suggestions="dialogData.constructionSuggestions"
    :project-code="dialogData.projectCode"
    @close="close"
    @reload="reload"
  />
  <change-info-dialog :id="changeInfoDialogData.id" :visible="changeInfoDialogData.visible" @close="changeInfoDialogData.visible=false" />
</template>
<style lang='less' scoped>
.flowCard{
  .botBtn{
    bottom: 0;
    left: 0;
    right: 0;
    border:1px solid #D8DADF;
    height: 56px;
    padding: 0 24px;
    align-items: center;
    .more{
      height: 32px;
      padding: 5px;
      border-radius: 2px;
      &:hover{
        background: #F0F2F5;
      }
    }
  }
}
</style>
