<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'delete', 'bookmark']"
      :paper-path="currentProblem?.filePath"
      @click="onOperationClick"
    >
      <el-button class="m-l-base m-r-auto" size="small" type="primary" @click="onSendBack">打回</el-button>
    </mark-header>
    <div class="flex flex-1 overflow-hidden p-base mark-container">
      <div
        class="flex flex-1 direction-column radius-base fill-blank mark-content"
        :class="{ 'text-center': center }"
        :style="{ 'background-color': backgroundColor }"
      >
        <span class="preview" @click="onPreview">
          <svg-icon name="preview"></svg-icon>
        </span>
        <right-button class="next-button" @click="checkNext" />
        <div class="flex-1 p-base scroll-auto mark-content-paper">
          <img :src="dataUrl" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
        </div>
        <scoring-panel-with-confirm
          :id="currentProblem?.taskId"
          v-model:visible="scoringPanelVisible"
          v-model:score="modelScore"
          :main-number="currentProblem?.mainNumber"
          @submit="onSubmit"
        ></scoring-panel-with-confirm>
      </div>
      <div class="flex direction-column p-base radius-base fill-blank m-l-base table-view">
        <base-form size="small" :model="formModel" :items="formItems" :label-width="useVW(78)">
          <template #form-item-search>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </template>
        </base-form>
        <div>
          <el-button custom-1 size="small" class="detail-info-label">
            <span class="">问题卷: 共</span>
            <span class="m-l-extra-small detail-info-label-num">{{ tableData.length }}</span>
          </el-button>
        </div>
        <div class="flex-1 scroll-auto">
          <base-table
            ref="tableRef"
            size="small"
            height="100%"
            :data="tableData"
            :columns="columns"
            highlight-current-row
            @current-change="onCurrentChange"
            @row-dblclick="onDbClick"
          ></base-table>
        </div>
      </div>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="currentProblem?.filePath"></image-preview>
  <mark-history-list :id="currentViewHistory?.taskId" v-model="visibleHistory"></mark-history-list>
  <send-back-mark :id="currentProblem?.id" v-model="sendBackVisible" @rejected="onRejected"></send-back-mark>
</template>

<script setup lang="ts" name="MarkingProblem">
/** 问题卷查看 */
import { reactive, ref, computed, watch } from 'vue'
import { ElButton } from 'element-plus'
import { useSetImgBg } from '@/hooks/useSetImgBg'
import useVW from '@/hooks/useVW'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import useMarkHeader from '@/hooks/useMarkHeader'
import useTableCheck from '@/hooks/useTableCheck'
import MarkHeader from '@/components/shared/MarkHeader.vue'
import ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import MarkHistoryList from '@/components/shared/MarkHistoryList.vue'
import SendBackMark from '@/components/shared/SendBackMark.vue'
import RightButton from '@/components/shared/RightButton.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'

import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractApiParams, ExtractApiResponse, ExtractMultipleApiResponse } from '@/api/api'
import type { MarkHeaderInstance, EpFormItem, EpTableColumn } from 'global-type'

type RowType = ExtractMultipleApiResponse<'getProblemHistory'> & { index: number }

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

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

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

/** 打回弹窗 */
const sendBackVisible = ref<boolean>(false)

const modelScore = ref<number[]>([])

/** 刷新 */
const onRefresh = () => {
  onSearch()
}

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

/** 打回 */
const onSendBack = () => {
  sendBackVisible.value = true
}

/** 打回成功 */
const onRejected = () => {
  checkNext()
}

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,
  standard: onViewStandard,
}

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

const { mainQuestionList, dataModel, changeModelValue, onOptionInit } = useOptions(['question'])

const formModel = reactive<ExtractApiParams<'getProblemHistory'>>({
  mainNumber: dataModel.question,
  problemType: '',
  status: 'INITIAL',
  pageNumber: 1,
  pageSize: 9999999,
})

watch(dataModel, () => {
  formModel.mainNumber = dataModel.question
})

const { defineColumn, _ } = useForm()

const span10 = defineColumn(_, '', { span: 10 })

const formItems = computed<EpFormItem[]>(() => [
  span10({
    rowKey: 'row-1',
    label: '大题',
    prop: 'mainNumber',
    slotType: 'select',
    slot: { options: mainQuestionList.value, onChange: changeModelValue('question'), disabled: true },
  }),
  span10({
    rowKey: 'row-1',
    label: '状态',
    prop: 'status',
    slotType: 'select',
    slot: {
      options: [
        { label: '未处理', value: 'INITIAL' },
        { label: '已处理', value: 'PROCESSED' },
        { label: '全部', value: '' },
      ],
    },
  }),
  { rowKey: 'row-1', slotName: 'search', labelWidth: '10px', colProp: { span: 4 } },
  span10({
    rowKey: 'row-2',
    label: '问题类型',
    prop: 'problemType',
    slotType: 'select',
    slot: {
      options: [
        { label: '跨套', value: 'OVERSTEP' },
        { label: '扫描不清晰', value: 'DIM' },
        { label: '全部', value: '' },
      ],
    },
  }),
])

/** 查询问题卷列表 */
const columns: EpTableColumn[] = [
  { label: '密号', prop: 'secretNumber', width: 45 },
  { label: '提交人', prop: 'markerName', width: 60 },
  { label: '问题类型', prop: 'problemTypeName', width: 45 },
  { label: '客观分', prop: 'objectiveScore', width: 45 },
  { label: '主观分', prop: 'markScore', width: 45 },
  { label: '客主比', prop: 'markRatio', width: 45 },
  { label: '评卷时间', prop: 'markTime', width: 45 },
  { label: '处理人', prop: 'headerName', width: 45 },
  { label: '处理时间', prop: 'solveTime', width: 45 },
]

const { fetch: getProblemHistory, result: problemHistory } = useFetch('getProblemHistory')

const {
  tableRef,
  tableData,
  current: currentProblem,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
} = useTableCheck(problemHistory)

watch(currentProblem, () => {
  if (currentProblem.value) {
    useFetch('viewProblemPaper').fetch({ id: currentProblem.value.id })
  }
})

const onSearch = async () => {
  getProblemHistory(formModel)
}

/** 问题卷打分 */
const { fetch: markProblemPaper } = useFetch('markProblemPaper')

const onSubmit = async () => {
  if (currentProblem.value) {
    await markProblemPaper({ id: currentProblem.value.id, scores: modelScore.value })
    await onSearch()
  }
}

onOptionInit(onSearch)

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

const { drawing, dataUrl } = useSetImgBg(imgOption)
</script>

<style scoped lang="scss">
.mark-container {
  .mark-content {
    position: relative;
    .preview {
      position: absolute;
      cursor: pointer;
      top: 10px;
      right: 20px;
      font-size: 24px;
    }
    .next-button {
      position: absolute;
      right: -20px;
      top: 300px;
    }
    .mark-content-paper {
      img {
        max-width: 100%;
      }
    }
  }
  .table-view {
    width: 480px;
    .detail-info-label {
      .detail-info-label-num {
        min-width: 32px;
        height: 24px;
        line-height: 24px;
        background: #00987b;
        border-radius: 4px;
      }
    }
  }
}
</style>
