<template>
  <div class="flex direction-column full">
    <div class="flex items-center p-extra-small fill-blank header-view">
      <el-button class="m-r-auto" size="small" plain @click="back()">返回</el-button>
      <message :paper-path="current?.filePath"></message>
      <user-info></user-info>
    </div>
    <div class="flex fill-blank detail-info">
      <div class="flex-1 flex p-base detail-info-chart">
        <div class="flex-1">
          <vue-echarts :options="markerSubjectiveChartsOption"></vue-echarts>
        </div>
        <div class="flex-1 m-l-base">
          <vue-echarts :options="markerObjectiveChartsOption"></vue-echarts>
        </div>
      </div>
      <div class="flex direction-column flex-1 p-extra-small">
        <div class="flex items-center justify-between detail-info-table-header">
          <el-button custom-1 size="small" class="detail-info-label">
            <span class="">{{ dataType }}试卷总数:</span>
            <span class="m-l-extra-small detail-info-label-num">{{ total }}</span>
          </el-button>
          <el-pagination
            v-bind="pagination"
            v-model:current-page="currentPage"
            size="small"
            class="m-t-unset"
            background
            right
            :hide-on-single-page="false"
          ></el-pagination>
        </div>
        <div class="flex-1 scroll-auto">
          <base-table
            ref="tableRef"
            size="small"
            height="100%"
            :data="tableData"
            :columns="tableColumn"
            highlight-current-row
            @current-change="onCurrentChange"
          >
            <template #empty> 暂无数据 </template>
          </base-table>
        </div>
      </div>
    </div>
    <div class="flex-1 p-base flex overflow-hidden">
      <div class="flex direction-column flex-1 radius-base fill-blank relative paper-view">
        <div class="flex-1 p-extra-small scroll-auto">
          <img :src="current?.filePath" alt="" class="paper-img" />
        </div>
        <span class="preview" @click="onPreview">
          <svg-icon name="preview"></svg-icon>
        </span>
        <scoring-panel-with-confirm-vue
          :id="current?.taskId"
          v-model:visible="scoringPanelVisible"
          v-model:score="modelScore"
          :main-number="current?.mainNumber"
          @submit="onSubmit"
        ></scoring-panel-with-confirm-vue>
      </div>
      <div class="radius-base p-extra-small fill-blank m-l-base overflow-auto paper-mark-record">
        <mark-history-list :id="current?.taskId" :model-value="true" :modal="false"></mark-history-list>
      </div>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="current?.filePath"></image-preview>
</template>

<script setup lang="ts" name="GroupMonitoringDetail">
/** 小组监控数据详情 */
import { reactive, ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElButton, ElPagination } from 'element-plus'
import useFetch from '@/hooks/useFetch'
import useTable from '@/hooks/useTable'
import useTableCheck from '@/hooks/useTableCheck'
import VueEcharts from 'vue-echarts'
import BaseTable from '@/components/element/BaseTable.vue'
import Message from '@/components/shared/message/Message.vue'
import UserInfo from '@/components/shared/UserInfo.vue'
import ScoringPanelWithConfirmVue from '@/components/shared/ScoringPanelWithConfirm.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'
import MarkHistoryList from '@/components/shared/MarkHistoryList.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'

import type { EChartsOption } from 'echarts'
import type { ExtractMultipleApiResponse, ExtractApiResponse } from '@/api/api'
import type { EpTableColumn } from 'global-type'

const { back } = useRouter()
const { query } = useRoute()

/** 给分板 */
const scoringPanelVisible = ref<boolean>(true)

/** 图片预览 */
const previewModalVisible = ref<boolean>(false)

/** 分数 */
const modelScore = ref<number[]>([])

/** 类型 */
const dataType = computed(() => {
  return query.operateType === 'VIEW' ? '已浏览' : '已给分'
})

/** 预览试卷 */
const onPreview = () => {
  previewModalVisible.value = true
}

/** 抽查详情列表 */
const { pagination, currentPage, total, data } = useTable(
  'getGroupMonitorDetail',
  {
    operateType: query.operateType as 'VIEW' | 'MARK',
    headerId: query.headerId as string,
  },
  { pageSize: 4 }
)

const { tableRef, current, onCurrentChange, tableData } = useTableCheck(data)

/** 抽查详情表格配置 */
const tableColumn: EpTableColumn<ExtractMultipleApiResponse<'getGroupMonitorDetail'>>[] = [
  { label: '密号', prop: 'secretNumber' },
  { label: '评卷员', prop: 'markerName' },
  { label: '给分', prop: 'markerScore' },
  { label: '组长给分', prop: 'headerScore' },
  { label: '客观分', prop: 'objectiveScore' },
  { label: '客主比', prop: 'headerRatio' },
  { label: '分档', prop: 'scoreLevel' },
  { label: '评卷时间', prop: 'markTime' },
]

const { fetch: getStatisticObjectiveByMarker, result: objectiveByMarker } = useFetch('getStatisticObjectiveByMarker')
const { fetch: getStatisticSubjectiveByMarker, result: subjectiveByMarker } = useFetch('getStatisticSubjectiveByMarker')

watch(
  [current],
  () => {
    if (current.value?.markerId) {
      getStatisticObjectiveByMarker({
        markerId: current.value.markerId,
        startTime: '',
        endTime: '',
      })
      getStatisticSubjectiveByMarker({
        markerId: current.value.markerId,
        startTime: '',
        endTime: '',
      })
    }
  },
  { immediate: true, deep: true }
)

type StatisticObjectiveByMarker = ExtractApiResponse<'getStatisticObjectiveByMarker'>

type StatisticObjectiveByMarkerValues = StatisticObjectiveByMarker['segmentsByAll']

const getXAxisData = <K extends keyof ExtractArrayValue<StatisticObjectiveByMarkerValues>>(
  field: K,
  data?: StatisticObjectiveByMarkerValues
) => {
  if (!data) {
    return []
  }
  const getValue = (key: K, item: ExtractArrayValue<StatisticObjectiveByMarkerValues>) => {
    return item[key]
  }
  return data?.map((v) => getValue(field, v))
}

const markerSubjectiveChartsOption = computed<EChartsOption>(() => {
  return {
    legend: {
      right: 0,
      itemWidth: 14,
      data: ['评卷员主观分布', '小组主观分布', '题组主观分布'],
    },
    xAxis: {
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: {
        align: 'right',
      },
      data: getXAxisData('scoreStart', subjectiveByMarker?.value?.segmentsByAll),
    },
    yAxis: [
      {
        type: 'value',
      },
      {
        type: 'value',
        axisLabel: {
          formatter: `{value}%`,
        },
        splitLine: { show: false },
      },
    ],
    series: [
      {
        name: '评卷员主观分布',
        type: 'line',
        itemStyle: {
          color: '#3AD500',
        },
        data: getXAxisData('rate', subjectiveByMarker?.value?.segmentsByUser),
      },
      {
        name: '小组主观分布',
        type: 'line',
        itemStyle: {
          color: '#0064FF',
        },
        data: getXAxisData('rate', subjectiveByMarker?.value?.segmentsByGroup),
      },
      {
        name: '题组主观分布',
        type: 'line',
        itemStyle: {
          color: '#008000',
        },
        data: getXAxisData('rate', subjectiveByMarker?.value?.segmentsByAll),
      },
    ],
  }
})

const markerObjectiveChartsOption = computed<EChartsOption>(() => {
  return {
    legend: {
      right: 0,
      itemWidth: 14,
      data: ['评卷员客观分布', '小组客观分布', '题组客观分布'],
    },
    xAxis: {
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: {
        align: 'right',
      },
      data: getXAxisData('scoreStart', objectiveByMarker?.value?.segmentsByAll),
    },
    yAxis: [
      {
        type: 'value',
      },
      {
        type: 'value',
        axisLabel: {
          formatter: `{value}%`,
        },
        splitLine: { show: false },
      },
    ],
    series: [
      {
        name: '评卷员客观分布',
        type: 'line',
        itemStyle: {
          color: '#3AD500',
        },
        data: getXAxisData('rate', objectiveByMarker?.value?.segmentsByUser),
      },
      {
        name: '小组客观分布',
        type: 'line',
        itemStyle: {
          color: '#0064FF',
        },
        data: getXAxisData('rate', objectiveByMarker?.value?.segmentsByGroup),
      },
      {
        name: '题组客观分布',
        type: 'line',
        itemStyle: {
          color: '#008000',
        },
        data: getXAxisData('rate', objectiveByMarker?.value?.segmentsByAll),
      },
    ],
  }
})

const onSubmit = async () => {
  try {
    if (!current.value?.taskId) {
      return
    }
    await useFetch('markMonitorDetailTask').fetch({ taskId: current.value.taskId, scores: modelScore.value })
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped lang="scss">
.header-view {
  border-bottom: $OnePixelLine;
}
.detail-info {
  height: 280px;
  .detail-info-chart {
    border-right: $OnePixelLine;
  }
  .detail-info-label {
    .detail-info-label-num {
      min-width: 32px;
      height: 24px;
      line-height: 24px;
      background: #00987b;
      border-radius: 4px;
    }
  }
}
.paper-view {
  .preview {
    position: absolute;
    cursor: pointer;
    top: 10px;
    right: 20px;
    font-size: 24px;
  }
}
.paper-mark-record {
  width: 340px;
}
</style>
