<template>
  <div class="flex direction-column full training-monitoring-view">
    <div class="p-l-base p-r-base p-t-medium-base fill-blank filter-form">
      <base-form ref="formRef" size="small" :label-width="useVW(100)" :disabled="loading" :model="model" :items="items">
        <template #form-item-operation>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </template>
      </base-form>
    </div>
    <div class="flex-1 p-base">
      <div class="radius-base p-base fill-blank">
        <div class="flex items m-b-base">
          <el-button
            size="small"
            :disabled="!hasSelected"
            :loading="putSampleIng || putAssessIng"
            type="primary"
            @click="onAssessPass(true)"
          >
            考核通过
          </el-button>
          <el-button
            size="small"
            :disabled="!hasSelected"
            :loading="putSampleIng || putAssessIng"
            type="primary"
            plain
            @click="onAssessPass(false)"
          >
            考核不通过
          </el-button>
          <!-- <el-button size="small" type="primary" custom-1 @click="viewPaper(false)">查看试卷</el-button> -->
        </div>
        <base-table
          :columns="columns"
          :data="trainingMonitor?.data"
          @selection-change="onSectionChange"
          @row-dblclick="onDbClick"
        >
        </base-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="TrainingMonitoring">
/** 培训监控 */
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElMessage } from 'element-plus'
import { minus, isDefine } from '@/utils/common'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import useVW from '@/hooks/useVW'
import useFetch from '@/hooks/useFetch'
import useSection from '@/hooks/useSection'
import useFormFilter from './hooks/useFormFilter'

import type { ExtractApiResponse } from '@/api/api'
import type { EpTableColumn } from 'global-type'

type TableDataType = ExtractArrayValue<ExtractApiResponse<'getTrainingMonitor'>['data']>

const { push } = useRouter()

const { diffShow, model, items, onOptionInit } = useFormFilter()

/** 培训监控列表 */
const { fetch: getTrainingMonitor, result: trainingMonitor, loading } = useFetch('getTrainingMonitor')
/** 培训卷审核 */
const { fetch: putSampleMonitorPass, loading: putSampleIng } = useFetch('putSampleMonitorPass')
/** 强制考核卷审核 */
const { fetch: putAssessMonitorPass, loading: putAssessIng } = useFetch('putAssessMonitorPass')

const { hasSelected, selectedList, onSectionChange } = useSection<TableDataType>()

const columns = computed<EpTableColumn<TableDataType>[]>(() => {
  const standardScores = trainingMonitor?.value?.data?.[0]?.scoreList
  const cols: EpTableColumn<TableDataType>[] =
    trainingMonitor?.value?.header?.map((h, i) => ({
      label: `${h}`,
      formatter(row) {
        if (!row.markerId) {
          return `${row.scoreList[i]}`
        }
        const score = row.scoreList[i]
        const standardScore = standardScores[i]
        const diff = isDefine(score) ? minus(score, standardScore) : ''
        return <span style={{ color: diff ? '#f00' : 'inherit' }}>{diffShow.value ? diff : score}</span>
      },
    })) || []
  return [
    {
      type: 'selection',
      selectable(row) {
        return !!row.markerId
      },
    },
    { label: '评卷员', prop: 'markerName' },
    { label: '状态', prop: 'status' },
    { label: '平均分', prop: 'avg' },
    { label: '标准差', prop: 'std' },
    { label: '相关系数', prop: 'xyRelate' },
    { label: '差异份数', prop: 'diffCount' },
    ...cols,
  ]
})

let currentDataType: TableDataType['stage'] = 'SAMPLE_A'

/** 刷新按钮 */
function onSearch() {
  const { diffShow, ...params } = model || {}
  const dataType = model.markStage
  getTrainingMonitor(params).then(() => {
    currentDataType = dataType
  })
}

/** 通过/不通过 */
const onAssessPass = async (pass: boolean) => {
  if (!hasSelected.value) {
    return ElMessage.warning('未勾选考核人员')
  }
  if (currentDataType === 'FORCE') {
    const forceGroupMarkerIds: number[] = selectedList.map((d) => d.forceGroupMarkerId)
    await putAssessMonitorPass({ forceGroupMarkerIds, pass })
  } else {
    const markerIds = selectedList.map((d) => d.markerId)
    await putSampleMonitorPass({ markerIds, markStage: currentDataType, pass })
  }
  onSearch()
}

/** 双击跳转详情 */
const onDbClick = (row: TableDataType) => {
  if (row.markerId) {
    push({
      name: 'TrainingDetail',
      query: {
        stage: row.stage,
        markerId: row.markerId,
        forceGroupMarkerId: row.forceGroupMarkerId,
      },
    })
  }
}

onOptionInit(onSearch)
</script>

<style scoped lang="scss">
.training-monitoring {
}
</style>
