<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" style="padding-bottom: 10px">
      <base-form
        ref="formRef"
        :key="formKey"
        size="small"
        :label-width="'100px'"
        :disabled="loading"
        :model="model"
        :rules="rules"
        :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
          :max-height="tableMaxHeight"
          border
          stripe
          size="small"
          :columns="columns"
          :data="trainingMonitor?.data"
          :row-class-name="rowClassName"
          @selection-change="onSectionChange"
          @row-dblclick="onDbClick"
        >
        </base-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="TrainingMonitoring">
/** 培训监控 */
import { computed, onBeforeUnmount, onBeforeMount, ref, watch } 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 ImgWaitingCheck from '../../../assets/images/daishen.png'
import type { ExtractApiResponse } from '@/api/api'
import type { EpTableColumn } from 'global-type'

type TableDataType = ExtractArrayValue<ExtractApiResponse<'getTrainingMonitor'>['data']>
const tableMaxHeight = ref(400)
onBeforeMount(() => {
  tableMaxHeight.value = window.innerHeight - 210
})
const { push } = useRouter()

const { diffShow, model, items, rules, formRef, elFormRef, onOptionInit } = useFormFilter()
const formKey = ref(Date.now() + '')
watch(rules, () => {
  formKey.value = Date.now() + ''
})
/** 培训监控列表 */
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 rowClassName = (obj: any) => {
  if (!obj.row.markerId) {
    return 'fixed-row'
  }
}
const columns = computed<EpTableColumn<TableDataType>[]>(() => {
  const standardScores = trainingMonitor?.value?.data?.[0]?.scoreList
  const cols: EpTableColumn<TableDataType>[] =
    trainingMonitor?.value?.header?.map((h, i) => {
      // console.log('hhhh', h, typeof h)
      return {
        label: `${h}`,
        // width: 12 * (h + '' || '').length + 25,
        minWidth: 50,
        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
      },
      width: 60,
      fixed: 'left',
    },
    { label: '评卷员', prop: 'markerName', minWidth: 110, fixed: 'left' },
    {
      label: '状态',
      prop: 'status',
      width: 120,
      fixed: 'left',
      formatter(row: any) {
        let cls =
          row.status == 'Sample A'
            ? 'sample-a'
            : row.status == 'Sample B'
            ? 'sample-b'
            : row.status == 'Pass A'
            ? 'pass-a'
            : row.status == 'Pass B'
            ? 'pass-b'
            : row.status == '强制考核'
            ? 'qzkh'
            : row.status === '正评'
            ? 'zp'
            : 'normal'
        return (
          <div class={cls + ' status-box'}>
            {row.status}
            {row.needAudit ? <img class="wait-check" src={ImgWaitingCheck} /> : null}
          </div>
        )
      },
    },
    { label: '平均分', prop: 'avg', minWidth: 80 },
    { label: '标准差', prop: 'std', minWidth: 80 },
    { label: '相关系数', prop: 'xyRelate', minWidth: 80 },
    { label: '差异份数', prop: 'diffCount', minWidth: 80 },
    ...cols,
  ]
})

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

/** 刷新按钮 */
async function onSearch() {
  try {
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      const { diffShow, ...params } = model || {}
      const dataType = model.markStage
      getTrainingMonitor(params).then(() => {
        currentDataType = dataType
      })
    }
  } catch (error) {
    console.error(error)
  }
}

/** 通过/不通过 */
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,
        stage: row.queryStage,
        markerId: row.markerId,
        forceGroupMarkerId: row.forceGroupMarkerId,
      },
    })
  }
}

onOptionInit(onSearch)
// let timer: any = setInterval(() => {
//   onSearch()
// }, 30000)
// onBeforeUnmount(() => {
//   clearInterval(timer)
//   timer = null
// })
</script>

<style scoped lang="scss">
.training-monitoring-view {
  :deep(.el-form-item--small) {
    margin-bottom: 10px;
  }
  :deep(.el-table) {
    .cell {
      overflow: visible;
    }
    .fixed-row {
      display: table-row;
      position: sticky;
      position: '-webkit-sticky';
      top: 0;
      width: 100%;
      z-index: 3;
    }
    .status-box {
      height: 24px;
      padding: 6px 10px;
      text-align: center;
      border-radius: 12px;
      // background: #eee;
      line-height: 1 !important;
      font-size: 12px;
      font-weight: bold;
      position: relative;
      .wait-check {
        position: absolute;
        right: -1px;
        top: -5px;
        width: 10px;
        height: 10px;
        z-index: 1;
      }
      &.sample-a {
        background: #d6f3ff;
        color: #0086d9;
      }
      &.sample-b {
        background: #e8e4ff;
        color: #605ca2;
      }
      &.pass-a {
        background: #fdf0cc;
        color: #e26100;
      }
      &.pass-b {
        background: #ffe0cc;
        color: #9f4f26;
      }
      &.qzkh {
        background: #ffd8d8;
        color: #844141;
      }
      &.zp {
        background: #ccf1ea;
        color: #307864;
      }
    }
  }
}
</style>
