<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>
      <!-- <div class="m-r-small m-l-small rt">
        <lock-entry></lock-entry>
      </div>
      <message class="m-r-small m-l-small rt" :paper-path="current?.filePath" :in-layout="true"></message>
      <div class="m-r-small m-l-small rt">
        <user-info></user-info>
      </div> -->

      <div class="data-item">
        <user-info></user-info>
      </div>
      <div class="data-item">
        <div class="icon-item">
          <lock-entry />
        </div>
        <div class="icon-item">
          <message :paper-path="current?.filePath" :secret-number="current?.secretNumber"></message>
        </div>
      </div>
    </div>
    <div class="flex fill-blank detail-info">
      <div class="flex p-base detail-info-chart" style="width: 64%">
        <div style="width: 50%">
          <vue-echarts class="full" :option="markerSubjectiveChartsOption"></vue-echarts>
        </div>
        <div class="flex-1 m-l-base">
          <vue-echarts class="full" :option="markerObjectiveChartsOption"></vue-echarts>
        </div>
      </div>
      <div class="flex direction-column p-extra-small" style="width: 36%">
        <div class="flex items-center justify-between detail-info-table-header m-b-mini">
          <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
            :pager-count="3"
            small
          ></el-pagination>
        </div>
        <div class="flex-1 scroll-auto">
          <base-table
            ref="tableRef"
            border
            stripe
            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-t-base flex overflow-hidden">
      <div class="flex direction-column flex-1 overflow-hidden radius-base fill-blank relative paper-view">
        <div ref="imgWrap" class="flex-1 p-extra-small scroll-auto img-wrap">
          <img :src="current?.filePath" alt="" class="paper-img relative" />
          <p v-if="current" class="absolute mark-score">{{ current.headerScore ?? current.markerScore }}</p>
        </div>
        <span class="preview" @click="onPreview">
          <svg-icon name="preview"></svg-icon>
        </span>
        <scoring-panel-with-confirm
          :id="current?.taskId"
          v-model:visible="scoringPanelVisible"
          v-model:score="modelScore"
          :main-number="current?.mainNumber"
          :subject-code="current?.subjectCode || ''"
          @submit="onSubmit"
        ></scoring-panel-with-confirm>
      </div>
      <div class="radius-base p-extra-small fill-blank m-l-base overflow-auto paper-mark-record">
        <mark-history-list
          :id="current?.taskId"
          height="100%"
          :model-value="true"
          :modal="false"
          :task="current"
        ></mark-history-list>
      </div>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="current?.filePath"></image-preview>
</template>

<script setup lang="ts" name="AnalysisGroupDetail">
/** 小组监控数据详情 */
import { 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 ScoringPanelWithConfirm 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 LockEntry from '@/components/common/LockEntry.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 imgWrap = ref()
/** 给分板 */
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, fetchTable } = useTable(
  'getGroupMonitorDetail',
  {
    operateType: query.operateType as 'VIEW' | 'MARK',
    headerId: query.headerId as string,
    subjectCode: query.subjectCode,
    mainNumber: query.questionMainNumber,
  },
  { pageSize: 4 }
)

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

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

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: '',
      })
      if (imgWrap.value) {
        imgWrap.value.scrollTop = 0
      }
    }
    if (current.value) {
      useFetch('viewActiveCheck').fetch({ taskId: current.value?.taskId })
    }
  },
  { 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 {
    title: { text: '主观分布' },
    grid: {
      bottom: 30,
      right: 0,
    },
    legend: {
      itemWidth: 14,
      data: ['评卷员', '小组', '题组'],
      right: 10,
      top: 2,
    },
    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: true },
      },
    ],
    series: [
      {
        name: '评卷员',
        type: 'line',
        itemStyle: {
          // color: '#3AD500',
          color: '#8ED14B',
        },
        data: getXAxisData('rate', subjectiveByMarker?.value?.segmentsByUser),
      },
      {
        name: '小组',
        type: 'line',
        itemStyle: {
          // color: '#0064FF',
          color: '#3B99D4',
        },
        data: getXAxisData('rate', subjectiveByMarker?.value?.segmentsByGroup),
      },
      {
        name: '题组',
        type: 'line',
        itemStyle: {
          // color: '#008000',
          color: '#ff0000',
        },
        data: getXAxisData('rate', subjectiveByMarker?.value?.segmentsByAll),
      },
    ],
  }
})

const markerObjectiveChartsOption = computed<EChartsOption>(() => {
  return {
    title: { text: '客观分布' },
    grid: {
      bottom: 30,
      right: 0,
    },
    legend: {
      itemWidth: 14,
      data: ['评卷员', '小组', '题组'],
      right: 10,
      top: 2,
    },
    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: true },
      },
    ],
    series: [
      {
        name: '评卷员',
        type: 'line',
        itemStyle: {
          // color: '#3AD500',
          color: '#8ED14B',
        },
        data: getXAxisData('rate', objectiveByMarker?.value?.segmentsByUser),
      },
      {
        name: '小组',
        type: 'line',
        itemStyle: {
          // color: '#0064FF',
          color: '#3B99D4',
        },
        data: getXAxisData('rate', objectiveByMarker?.value?.segmentsByGroup),
      },
      {
        name: '题组',
        type: 'line',
        itemStyle: {
          // color: '#008000',
          color: '#ff0000',
        },
        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 })
    await useFetch('updatePersonalMarkDetailScore').fetch({
      taskId: current.value.taskId,
      scores: modelScore.value,
      source: (query.source as string) || '',
    })
    fetchTable()
  } catch (error) {
    console.error(error)
  }
}

fetchTable()
</script>

<style scoped lang="scss">
.mark-score {
  color: red;
  font-size: 50px;
  left: 30px;
  top: 20px;
}

.header-view {
  background-color: #333;
  height: 60px;
  ::v-deep(.data-item) {
    // padding-left: 20px;
    padding-left: 15px;
    padding-right: 15px;
    position: relative;
    height: 100%;
    display: flex;
    align-items: center;
    color: #8a8a8a;
    .icon-item {
      // width: 45px;
      padding: 0 10px;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
    }
    &:first-child {
      margin-left: auto;
    }
    &:not(:last-child) {
      &:after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        width: 1px;
        height: 100%;
        background-color: #464646;
      }
    }
    &.is-last:after {
      width: 0;
    }
    .main-ques-info {
      text-align: center;
      font-weight: bold;
      color: $color--primary;
      margin-bottom: 5px;
      max-width: 130px;
    }
  }
}
// .header-view {
//   border-bottom: $OnePixelLine;
//   :deep(p.tip) {
//     color: #8a8a8a;
//     font-size: 12px;
//   }
//   .rt {
//     color: #666;
//   }
// }
.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 {
  .paper-img {
    max-width: 100%;
  }
  .preview {
    position: absolute;
    cursor: pointer;
    top: 20px;
    right: 25px;
    font-size: 38px;
  }
}
.paper-mark-record {
  width: 390px;
}
</style>
