<template>
  <div class="flex direction-column full">
    <mark-header :exclude-operations="excludeOperations" :paper-path="currentTask?.url" @click="onOperationClick">
      <span class="data-item">
        已评: {{ markStatus?.personCount || 0 }} /
        {{ minus(markStatus?.totalCount || 0, markStatus?.markedCount || 0) }}
      </span>
      <span v-show="currentTask" class="data-item">密号: {{ currentTask?.secretNumber }}</span>
      <span v-show="currentTask" class="data-item">{{ currentTask?.mainNumber }}-{{ currentTask?.mainTitle }}</span>
      <span class="data-item">
        <current-time></current-time>
      </span>
    </mark-header>
    <div class="flex-1 overflow-hidden p-base mark-container">
      <div
        class="p-base radius-base full fill-blank scroll-auto mark-content"
        :style="{ 'background-color': backgroundColor }"
      >
        <span v-if="currentTask" class="mark-status">
          <img :src="statusIcon" alt="" />
        </span>
        <span class="preview" @click="onPreview">
          <svg-icon name="preview"></svg-icon>
        </span>
        <div :class="{ 'text-center': center }">
          <img :src="dataUrl" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
        </div>
      </div>
    </div>
    <scoring-panel-with-confirm
      :id="currentTask?.taskId"
      v-model:visible="scoringPanelVisible"
      v-model:score="modelScore"
      :main-number="currentTask?.mainNumber"
      @submit="onSubmit"
    ></scoring-panel-with-confirm>
  </div>
  <base-dialog v-model="problemVisible" unless :width="useVW(260)" center>
    <el-radio-group v-model="problemClass">
      <el-radio-button label="problem">问题卷</el-radio-button>
      <el-radio-button label="similar">雷同卷</el-radio-button>
    </el-radio-group>

    <div class="m-t-base problem-pane">
      <el-radio-group v-show="problemClass === 'problem'" v-model="problemType" class="full-w">
        <div class="full-w">
          <el-radio label="OVERSTEP">跨套</el-radio>
        </div>
        <div class="full-w">
          <el-radio label="DIM">扫描图片不清晰</el-radio>
        </div>
      </el-radio-group>
      <el-radio v-show="problemClass === 'similar'" model-value="similar" label="similar">提交雷同</el-radio>
    </div>
    <template #footer>
      <div class="flex items-center justify-between">
        <el-button class="confirm-button" type="primary" @click="onConfirmSubmitProblem">确定</el-button>
        <el-button class="confirm-button" plain @click="problemVisible = false">取消</el-button>
      </div>
    </template>
  </base-dialog>
  <remark-list-modal v-model="remarkModalVisible" @task-change="historyTaskChange"></remark-list-modal>
  <image-preview v-model="previewModalVisible" :url="currentTask?.url"></image-preview>
</template>

<script setup lang="ts" name="MarkingMark">
/** 阅卷-正式评卷 */
import { computed, nextTick, ref, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElRadioGroup, ElRadioButton, ElRadio, ElMessage } from 'element-plus'
import { minus } from '@/utils/common'
import { useSetImgBg } from '@/hooks/useSetImgBg'
import useFetch from '@/hooks/useFetch'
import useVW from '@/hooks/useVW'
import useSpentTime from '@/hooks/useSpentTime'
import useMarkHeader from '@/hooks/useMarkHeader'
import BaseDialog from '@/components/element/BaseDialog.vue'
import MarkHeader from '@/components/shared/MarkHeader.vue'
import ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'
import RemarkListModal from '@/components/shared/RemarkListModal.vue'
import CurrentTime from '@/components/shared/CurrentTime.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'

import MarkingStatus from '@/assets/images/status-marking.png'
import ReMarkingStatus from '@/assets/images/status-remarking.png'
import SampleAStatus from '@/assets/images/status-sample-a.png'
import SampleBStatus from '@/assets/images/status-sample-b.png'

import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractApiResponse } from '@/api/api'
import type { MarkHeaderInstance } from 'global-type'

const { push, replace } = useRouter()

const { getSpentTime, resume } = useSpentTime()

const CACHE_NUM = 2

type TaskType = ExtractArrayValue<ExtractApiResponse<'getMarkingTask'>>['taskType'] | 'default' | 'remarking'

const markStatusIcon: Partial<Record<TaskType, string>> = {
  FORMAL: MarkingStatus,
  remarking: ReMarkingStatus,
  SAMPLE_A: SampleAStatus,
  SAMPLE_B: SampleBStatus,
  default: MarkingStatus,
}

const currentTaskType = ref<TaskType>('FORMAL')

const statusIcon = computed(() => {
  return markStatusIcon[currentTaskType.value] || markStatusIcon.default
})

const {
  rotate,
  scale,
  center,
  frontColor,
  backgroundColor,
  onScaleChange,
  onCenter,
  onRotate,
  setBackgroundColor,
  setFrontColor,
  onViewSample,
  onViewStandard,
} = useMarkHeader()

type HistoryTaskType = ExtractArrayValue<ExtractApiResponse<'getMarkHistory'>>
type FormalTaskType = ExtractArrayValue<ExtractApiResponse<'getMarkingTask'>>

type TaskInfoType = FormalTaskType | HistoryTaskType

let currentTaskPool: ExtractApiResponse<'getMarkingTask'> = []

const currentTask = ref<TaskInfoType>()

type excludeOperationTypes = InstanceType<typeof MarkHeader>['$props']['excludeOperations']

const excludeOperations = computed<excludeOperationTypes>(() => {
  if (!currentTask.value?.taskType) {
    return ['delete', 'bookmark']
  }
  const isSampleType = ['SAMPLE_A', 'SAMPLE_B'].includes(currentTask.value.taskType)
  return ['delete', 'bookmark'].concat(isSampleType ? ['problem'] : []) as excludeOperationTypes
})

const { fetch: getMarkingTask, loading } = useFetch('getMarkingTask')
const { fetch: submitMarkTask, loading: submitting } = useFetch('submitMarkTask')
const { fetch: getMarkStatus, result: markStatus } = useFetch('getMarkStatus')

const historyTaskChange = (task: HistoryTaskType) => {
  currentTask.value = task
  currentTaskType.value = 'remarking'
  nextTick(() => {
    modelScore.value = task.markerScores
  })
}

const setCurrentTask = () => {
  currentTask.value = currentTaskPool.shift()
  currentTaskType.value =
    currentTask.value && markStatusIcon[currentTask.value.taskType] ? currentTask.value.taskType : 'FORMAL'
}

let refreshTimer: number | null = null

onBeforeUnmount(() => {
  if (refreshTimer) {
    clearTimeout(refreshTimer)
    refreshTimer = null
  }
})

const refreshTaskPool = (force = false, isRefresh = false) => {
  if (refreshTimer) {
    clearTimeout(refreshTimer)
  }
  refreshTimer = window.setTimeout(
    () => {
      if (currentTaskPool.length < (isRefresh ? Number.MAX_SAFE_INTEGER : CACHE_NUM)) {
        getMarkingTask().then((result) => {
          if (result?.length) {
            currentTaskPool[isRefresh ? 'unshift' : 'push'](...result)
          }
          if (currentTaskPool?.length && !currentTask.value) {
            setCurrentTask()
          }
          refreshTaskPool()
        })
      }
    },
    force ? 0 : 5000
  )
}

/**
 * @param force 即时更新任务
 * @param isRefresh 是否有插队任务
 */
const getNextTask = (force = false, isRefresh = false) => {
  setCurrentTask()
  refreshTaskPool(force, isRefresh)
}

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

/** 回评弹窗 */
const remarkModalVisible = ref<boolean>(false)

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

/** 问题卷弹窗 */
const problemVisible = ref<boolean>(false)
/** 问题卷 | 雷同卷   */
const problemClass = ref<'problem' | 'similar'>('problem')
/** 问题卷类型 */
const problemType = ref<ProblemType>('OVERSTEP')

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

/** 提交评卷 */
const onSubmit: InstanceType<typeof ScoringPanelWithConfirm>['onSubmit'] = async ({ question, scores, totalScore }) => {
  try {
    if (!currentTask.value?.taskId) {
      scoringPanelVisible.value = true
      return
    }

    const spentTime = getSpentTime()

    const current = currentTask.value as FormalTaskType
    if (current.minMarkTime && current.minMarkTime * 1000 > spentTime) {
      scoringPanelVisible.value = true
      return ElMessage.warning('阅卷速度过快')
    }
    const submitResult = await submitMarkTask({
      spentTime,
      markScore: totalScore,
      markScores: scores,
      problem: false,
      taskId: currentTask.value.taskId,
      taskType: currentTask.value.taskType,
    })
    await getNextTask(true, submitResult?.refresh)
  } catch (error) {
    console.error(error)
    scoringPanelVisible.value = true
  }
}

const onSubmitSimilar = async () => {
  if (!currentTask.value) {
    return
  }
  const markHistory = await useFetch('getMarkHistory').fetch()
  if (!markHistory.length) {
    return ElMessage.warning('暂无评卷记录')
  }
  return push({
    name: 'SubmitSimilar',
    params: { taskId: currentTask.value.taskId },
    query: {
      secretNumber: currentTask.value.secretNumber,
    },
  })
}

const onSubmitProblem = async () => {
  if (!currentTask.value) {
    return
  }
  const submitResult = await submitMarkTask({
    markScore: 0,
    markScores: [],
    spentTime: getSpentTime(),
    problem: true,
    problemType: problemType.value,
    taskId: currentTask.value.taskId,
    taskType: currentTask.value.taskType,
  })
  await getNextTask(true, submitResult?.refresh)
}

/** 提交问题卷 & 雷同卷 */
const onConfirmSubmitProblem = async () => {
  try {
    if (!currentTask.value) {
      return
    }
    problemVisible.value = false
    if (problemClass.value === 'similar') {
      await onSubmitSimilar()
    } else {
      await onSubmitProblem()
    }
  } catch (error) {
    console.error(error)
  }
}

/** 返回 */
const onBack = () => {
  /** 回评时返回到正评, 否则返回到评卷员主页 */
  if (currentTaskType.value === 'remarking') {
    getNextTask()
  } else {
    replace({
      name: 'MarkingNav',
    })
  }
}

/** 刷新 */
const onRefresh = () => {
  getMarkStatus()

  useFetch('clearCachedTasks')
    .fetch()
    .then(() => getNextTask(true))
}

/** 回评 */
const onRemark = () => {
  remarkModalVisible.value = true
}

/** 设置问题卷 */
const onSetProblem = () => {
  problemVisible.value = true
}

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

type OperationClick = MarkHeaderInstance['onClick']

type OperationType = Parameters<Exclude<OperationClick, undefined>>[0]['type']

const operationHandles: Partial<Record<OperationType, (...args: any) => void>> = {
  back: onBack,
  'scale-change': onScaleChange,
  center: onCenter,
  rotate: onRotate,
  'front-color': setFrontColor,
  'background-color': setBackgroundColor,
  refresh: onRefresh,
  remark: onRemark,
  problem: onSetProblem,
  example: onViewSample,
  standard: onViewStandard,
}

const onOperationClick: OperationClick = ({ type, value }) => {
  operationHandles[type]?.(value)
}

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentTask?.value?.url,
    immediate: true,
    rotate: rotate.value,
    scale: scale.value,
  }
})

const { drawing, dataUrl } = useSetImgBg(imgOption)

watch(currentTask, () => {
  getMarkStatus()
  resume()
})

onRefresh()
</script>

<style scoped lang="scss">
.mark-container {
  .mark-content {
    position: relative;

    .mark-status {
      display: inline-block;
      width: 24px;
      position: sticky;
      cursor: pointer;
      top: 0;
      left: 0;
      img {
        max-width: 100%;
      }
    }
    .preview {
      position: sticky;
      cursor: pointer;
      top: 0;
      left: 888px;
      font-size: 24px;
    }
  }
}
</style>
