<script name="scoreDetail" setup>
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
import {
  exportScore,
  selfAppasialGetNotSealedPdf,
  templateDetail
} from '@/http/apis/performanceEvaluation/unitSelfEvaluation'
import { useRoute, useRouter } from 'vue-router'
import { proDetail } from '@/http/apis/projectStoreManage/projectStore'
import Accessory from '@/components/accessory/index.vue'

import store from '@/store'
import { detail } from '@/http/apis/performanceEvaluation/projectReform'
import useExportExc from '@/utils/useExportExc'
import { progressDetail } from '@/http/apis/toDoCenter/todoList'
import AuditDialog from '@/pages/toDoCenter/components/auditDialog.vue'
import FlowRecord from '@/pages/toDoCenter/components/flowRecord.vue'
import { getPdfHtmlStr } from '@/pages/performanceEvaluation/unitSelfEvaluation/scoreDetail/htmlStr'
import { templateTypeList } from '@/http/apis/performanceEvaluation/indicatorTemplate'
import { downFileById } from '@/http/apis/commonApi'
const
  route = useRoute(),
  activeName = ref('1'),
  { statusOptions } = store.dictStore.globalDicts || {},
  columns = ref([]),
  initColums = () => {
    columns.value = [
      {
        label: '一级指标',
        key: 'oneName',
        prop: 'oneName'
      },
      {
        label: '二级指标',
        key: 'twoName',
        prop: 'twoName'
      },
      {
        label: '三级指标',
        key: 'name',
        prop: 'name'
      },
      {
        label: '指标细则',
        key: 'indexDetail',
        prop: 'indexDetail'
      },
      {
        label: '评分细则',
        key: 'gradeDetail',
        prop: 'gradeDetail'
      },
      {
        label: '佐证材料',
        key: 'supportMaterial',
        prop: 'supportMaterial'
      },
      {
        label: '指标分值',
        key: 'indexScore',
        prop: 'indexScore',
        width: 85
      },
      {
        label: '自评依据',
        key: 'selfBasis',
        slot: 'selfBasis',
        width: 200
      },
      {
        label: '自评得分',
        key: 'selfScore',
        slot: 'selfScore',
        width: 85
      }
    ]
  },
  objectSpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex
  }) => {
    if (columnIndex === 0) {
      if (row.isFirstOne) {
        return {
          rowspan: row.oneRows,
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
    if (columnIndex === 1) {
      if (row.isFirstTwo) {
        return {
          rowspan: row.twoRows,
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
  },
  tableData = ref([]),
  loading = ref(true),
  htmlStr = ref(),
  templateDetailData = ref(),
  getDetail = async () => {
    loading.value = true
    tableData.value = []
    const res = await templateDetail(route.query.projectCode)
    const data1 = getData(res.data.templateDetails)
    const data2 = getData(res.data.additionalIndexDetails)
    htmlStr.value = getPdfHtmlStr(projectDetailData.value?.projectName, templateTypeListData.value?.find(i => i.id === projectDetailData.value.templateType)?.name, projectDetailData.value.projectYear, res.data?.selfAppraisalTotalScore, data1, data2)
    templateDetailData.value = res.data
    tableData.value = [...data1, ...data2]
    if (activeName.value !== '1') {
      initColums()
      getColumn()
    }
    loading.value = false
  },
  getColumn = () => {
    if (activeName.value === '2') {
      tableData.value[0].appraisalType2List?.forEach((data, index) => {
        columns.value.push({
          label: `${data.appraisalEmployeeName}（复评）`,
          key: 'review',
          children: [
            {
              label: '复评依据',
              key: `reviewDesc`,
              slot: `reviewDesc`,
              columnKey: index + '',
              width: 200
            },
            {
              label: '复评得分',
              key: `reviewScore`,
              slot: `reviewScore`,
              columnKey: index + '',
              width: 85
            }
          ]
        })
      })
    } else if (activeName.value === '3') {
      tableData.value[0].appraisalType3List?.forEach((data, index) => {
        columns.value.push({
          label: `${data.appraisalEmployeeName}（核查）`,
          key: 'review',
          children: [
            {
              label: '核查依据',
              key: 'checkDesc',
              slot: 'checkDesc',
              columnKey: index + '',
              width: 200
            },
            {
              label: '核查得分',
              key: 'checkScore',
              slot: 'checkScore',
              columnKey: index + '',
              width: 85
            }
          ]
        })
      })
    } else if (activeName.value === '4') {
      columns.value = [
        {
          label: '一级指标',
          key: 'oneName',
          prop: 'oneName'
        },
        {
          label: '二级指标',
          key: 'twoName',
          prop: 'twoName'
        },
        {
          label: '三级指标',
          key: 'name',
          prop: 'name'
        },
        {
          label: '指标细则',
          key: 'indexDetail',
          prop: 'indexDetail'
        },
        {
          label: '评分细则',
          key: 'gradeDetail',
          prop: 'gradeDetail'
        },
        {
          label: '佐证材料',
          key: 'supportMaterial',
          prop: 'supportMaterial'
        },
        {
          label: '指标分值',
          key: 'indexScore',
          prop: 'indexScore',
          width: 85
        },
        {
          label: '复核得分',
          key: 'reReviewScore',
          slot: 'reReviewScore',
          width: 85
        },
        {
          label: '复核说明',
          key: 'reReviewDesc',
          slot: 'reReviewDesc',
          width: 200
        }
      ]
    }
  },
  getData = (data) => {
    const list = []
    data.forEach((one, oneIndex) => {
      let oneRows = 0
      one.children.forEach((two, twoIndex) => {
        let twoRows = 0 // 二级指标数量
        two.children.forEach((three, threeIndex) => {
          list.push({
            oneId: one.templateId,
            oneName: one.name,
            twoId: two.templateId,
            twoName: two.name,
            isFirstOne: oneRows === 0,
            isFirstTwo: twoRows === 0,
            appraisalType1List: three.selfAppraisalScoreInfo?.filter(i => i.appraisalType === 1) || [],
            appraisalType2List: three.reAppraisalScoreInfo && Object.values(three.reAppraisalScoreInfo).reduce((arr, cur) => arr.concat((cur), [])) || [],
            appraisalType3List: three.verifyScoreInfo && Object.values(three.verifyScoreInfo).reduce((arr, cur) => arr.concat((cur), [])) || [],
            appraisalType4List: three.rectifyAuditScoreInfo?.length && three.rectifyAuditScoreInfo || [],
            oneRows,
            twoRows,
            ...three,
            threeId: three.templateId
          })
          oneRows++
          twoRows++
        })
        list.forEach(i => {
          if (i.twoId === two.templateId) {
            i.twoRows = twoRows
          }
        })
      })
      list.forEach(i => {
        if (i.oneId === one.templateId) {
          i.oneRows = oneRows
        }
      })
    })
    return list
  },
  projectDetailData = ref({}),
  getProjectDetail = async () => {
    const res = await proDetail(route.query.projectCode)
    projectDetailData.value = res.data
    getDetail()
  },
  tabChange = (val) => {
    activeName.value = val
    initColums()
    getColumn()
    if (val === '4') {
      getRectifyDetail()
    }
  },
  rectifyDetailData = ref({}),
  getRectifyDetail = async () => {
    const res = await detail(route.query.appraisalId, route.query.projectCode)
    rectifyDetailData.value = res.data
  },
  // 导出
  { exportLoading, exportData } = useExportExc(),
  scoreExport = () => {
    exportData(() => exportScore(activeName.value, { projectCode: route.query.projectCode, appraisalId: route.query.appraisalId }))
  },
  // 审核
  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)
      }
    }
  },
  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
  },
  // 去盖章并通过页
  router = useRouter(),
  toSealAndPass = async () => {
    const res = await selfAppasialGetNotSealedPdf({ projectCode: route.query.projectCode, appraisalId: route.query.appraisalId, html: htmlStr.value })
    router.push({ name: 'selfScoreStamp', query: { projectId: route.query.projectId, projectCode: route.query.projectCode, appraisalId: route.query.appraisalId, instanceId: route.query.instanceId, taskId: route.query.taskId, fileId: res.data.fileId, isCommit: res.data.isCommit, instName: flowData.value?.processProgressVo?.processDefName }})
  },
  // 审核弹窗
  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.action = action
    dialogData.constructionSuggestions = flowData.value.constructionSuggestions
    dialogData.projectCode = route.query.projectCode
  },
  close = () => {
    dialogData.visible = false
  },
  // 重新加载
  reload = (taskId) => {
    getProjectDetail()
    getFlowData(taskId)
    loading.value = false
  },
  templateTypeListData = ref(),
  { proxy } = getCurrentInstance(),
  scoreExportPdf = async () => {
    const file = templateDetailData.value.selfAppraisalPdf && JSON.parse(templateDetailData.value.selfAppraisalPdf)[0] || undefined
    if (!file?.id) {
      proxy.$message.warning('盖章文件不存在！')
      return
    }
    const res = await downFileById({ fileId: file.id })
    const url = URL.createObjectURL(res)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.download = file.originalFileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }
onMounted(async () => {
  const res = await templateTypeList()
  templateTypeListData.value = res.data
  initColums()
  getProjectDetail()
  route.query.instanceId && getFlowData(route.query.taskId)
})
</script>

<template>
  <div class="footerPage">
    <el-card class="mb-16">
      <div class="card-header">
        <div class="flex justify-between items-center">
          <div class="flex-1">
            <p class="font-bold">{{ projectDetailData?.projectName||'-' }}</p>
            <div class="mt-8 search">
              <el-form label-suffix=":">
                <el-row :gutter="24">
                  <el-col :span="6">
                    <el-form-item label="申报单位">{{ projectDetailData?.buildOrgName||'-' }}</el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="项目状态">{{ statusOptions[projectDetailData?.status]?.name||'-' }}</el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="批复金额">{{ projectDetailData?.approvalAmount }}万元</el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="预算年度">{{ projectDetailData?.projectYear||'-' }}</el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
          <el-button v-if="$route.name==='applicationMarkDetail'" type="primary" icon="Download">下载分析报告</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="mb-16">
      <div class="flex justify-between items-center">
        <div class="flex">
          <p>自评总分：<span class="font-bold text-18">{{ templateDetailData?.selfAppraisalTotalScore }}</span></p>
          <p v-if="$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreDetail'" class="ml-16">复评总分：<span class="font-bold text-18">{{ templateDetailData?.reAppraisalTotalScore.split(',').join('、') }}</span></p>
          <p v-if="$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreDetail'&&$route.name!=='reviewScoreDetail'" class="ml-16">核查总分：<span class="font-bold text-18">{{ templateDetailData?.verifyTotalScore.split(',').join('、') }}</span></p>
        </div>
        <div v-if="($route.name==='selfScoreSureDetail'||$route.name==='selfScoreDetail')&&flowData.status==='审核通过'" class="flex items-center justify-end">
          <el-button
            type="primary"
            plain
            @click="scoreExportPdf"
          >导出</el-button>
        </div>
        <div v-if="$route.name!=='selfScoreSureDetail'&&$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreDetail'" class="flex items-center justify-end">
          <el-button
            type="primary"
            plain
            :loading="exportLoading"
            @click="scoreExport"
          >导出</el-button>
        </div>
      </div>
    </el-card>
    <el-card v-loading="loading" class="tab-card">
      <!--   自评详情和自评审核确认详情不展示tab-->
      <template v-if="$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreSureDetail'&&$route.name!=='selfScoreDetail'" #header>
        <el-tabs v-model="activeName" @tab-change="tabChange">
          <el-tab-pane label="自评详情" name="1" />
          <el-tab-pane v-if="$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreDetail'" label="复评详情" name="2" />
          <el-tab-pane v-if="$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreDetail'&&$route.name!=='reviewScoreDetail'" label="核查详情" name="3" />
          <el-tab-pane v-if="$route.name!=='unitSelfScoreDetail'&&$route.name!=='selfScoreDetail'&&$route.name!=='reviewScoreDetail'&&$route.name!=='checkScoreDetail'" label="整改详情" name="4" />
        </el-tabs>
      </template>
      <div v-if="activeName==='4'" class="mb-16">
        <el-descriptions
          title="整改意见"
          :column="2"
          border
          class="mb-16"
        >
          <el-descriptions-item span="2" label="整改意见">{{ rectifyDetailData?.rectifyOpinion }}</el-descriptions-item>
          <el-descriptions-item label="提交人">{{ rectifyDetailData.rectifyResSubEmployee?.username }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ rectifyDetailData?.rectifyResSubTime }}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          title="整改情况"
          :column="2"
          border
          class="mb-16"
        >
          <el-descriptions-item span="2" label="整改结果说明">{{ rectifyDetailData?.rectifyResult }}</el-descriptions-item>
          <el-descriptions-item label="相关材料" span="2">
            <p v-for="(file,fileIndex) in rectifyDetailData.rectifyResultAppendix&&JSON.parse(rectifyDetailData.rectifyResultAppendix)" :key="fileIndex" class="mb-4">
              <accessory :file-name="file.originalFileName" :file-id="file.id" />
            </p>
          </el-descriptions-item>
          <el-descriptions-item label="提交人">{{ rectifyDetailData?.rectifySubmitEmployee?.username }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ rectifyDetailData?.rectifySubmitTime }}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          title="审核"
          :column="2"
          border
          class="mb-16"
        >
          <el-descriptions-item span="2" label="审核结果">{{ rectifyDetailData?.rectifyStatusName }}</el-descriptions-item>
          <el-descriptions-item label="审核意见">{{ rectifyDetailData?.rectifyAuditOpinion }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <h4 v-if="activeName==='4'" class="mb-16 font-bold">最终评分</h4>
      <table-list
        :stripe="false"
        :border="true"
        :pagination="false"
        :data="tableData"
        :span-method="objectSpanMethod"
        :column="columns"
      >
        <template #selfBasis="{scope}">
          <template v-if="scope.row.appraisalType1List?.length">
            <p>{{ scope.row.appraisalType1List[0].appraisalBasis||'-' }}</p>
            <p v-for="(file,fileIndex) in scope.row.appraisalType1List?.[0]?.appraisalBasisAppendix&&JSON.parse(scope.row.appraisalType1List[0].appraisalBasisAppendix)" :key="fileIndex" class="mb-4">
              <accessory :file-name="file.originalFileName" :file-id="file.id" />
            </p>
          </template>
          <span v-else>-</span>
        </template>
        <template #selfScore="{scope}">
          <div v-if="scope.row.appraisalType1List?.length">
            {{ scope.row.appraisalType1List[0].appraisalScore }}
          </div>
          <span v-else>-</span>
        </template>
        <template #reviewDesc="{scope}">
          <template v-if="scope.row.appraisalType2List?.length">
            <p>{{ scope.row.appraisalType2List[scope.column.columnKey].appraisalBasis||'-' }}</p>
            <p v-for="(file,fileIndex) in scope.row.appraisalType2List[scope.column.columnKey]?.appraisalBasisAppendix&&JSON.parse(scope.row.appraisalType2List[0].appraisalBasisAppendix)" :key="fileIndex" class="mb-4">
              <accessory :file-name="file.originalFileName" :file-id="file.id" />
            </p>
          </template>
          <span v-else>-</span>
        </template>
        <template #reviewScore="{scope}">
          <div v-if="scope.row.appraisalType2List?.length">
            {{ scope.row.appraisalType2List[scope.column.columnKey].appraisalScore }}
          </div>
          <span v-else>-</span>
        </template>
        <template #checkDesc="{scope}">
          <template v-if="scope.row.appraisalType3List?.length">
            <p>{{ scope.row.appraisalType3List[scope.column.columnKey].appraisalBasis||'-' }}</p>
            <p v-for="(file,fileIndex) in scope.row.appraisalType3List[scope.column.columnKey]?.appraisalBasisAppendix&&JSON.parse(scope.row.appraisalType3List[0].appraisalBasisAppendix)" :key="fileIndex" class="mb-4">
              <accessory :file-name="file.originalFileName" :file-id="file.id" />
            </p>
          </template>
          <span v-else>-</span>
        </template>
        <template #checkScore="{scope}">
          <div v-if="scope.row.appraisalType3List?.length">
            {{ scope.row.appraisalType3List[scope.column.columnKey].appraisalScore }}
          </div>
          <span v-else>-</span>
        </template>
        <template #reReviewScore="{scope}">
          <div v-if="scope.row.appraisalType4List?.length">
            {{ scope.row.appraisalType4List[0].appraisalScore }}
          </div>
          <span v-else>-</span>
        </template>
        <template #reReviewDesc="{scope}">
          <template v-if="scope.row.appraisalType4List?.length">
            <p>{{ scope.row.appraisalType4List[0].appraisalBasis||'-' }}</p>
            <p v-for="(file,fileIndex) in scope.row.appraisalType4List?.[0]?.appraisalBasisAppendix&&JSON.parse(scope.row.appraisalType4List[0].appraisalBasisAppendix)" :key="fileIndex" class="mb-4">
              <accessory :file-name="file.originalFileName" :file-id="file.id" />
            </p>
          </template>
          <span v-else>-</span>
        </template>
      </table-list>
    </el-card>
    <el-card
      v-if="$route.name==='selfScoreSureDetail'||$route.name==='selfScoreDetail'"
      header="流程记录"
      shadow="never"
      class="mt-16"
    >
      <flow-record :flow-data="flowData.processProgressVo.progressInfo" />
    </el-card>
    <div v-if="$route.name==='selfScoreSureDetail'" class="footer">
      <div class="flex items-center botBtn">
        <el-button @click="router.go(-1)">返回</el-button>
        <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>
      </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"
    :is-performance="true"
    @close="close"
    @reload="reload"
  />
</template>
