<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'delete', 'bookmark']"
      :paper-path="currentReMarkPaper?.filePath"
      @click="onOperationClick"
    >
      <el-button
        class="m-l-base m-r-auto"
        size="small"
        type="primary"
        :disabled="!currentReMarkPaper"
        @click="onConfirmReMark"
      >
        确认
      </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>
        <p v-if="currentReMarkPaper" class="absolute mark-score">{{ currentReMarkPaper.markScore }}</p>
        <right-button class="next-button" @click="checkNext" />
        <div class="flex-1 p-base scroll-auto mark-content-paper img-wrap">
          <img :src="dataUrl" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
        </div>
        <scoring-panel-with-confirm
          :id="currentReMarkPaper?.taskId"
          v-model:visible="scoringPanelVisible"
          v-model:score="modelScore"
          :main-number="currentReMarkPaper?.mainNumber"
          :subject-code="formModel.subjectCode"
          @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="'80px'">
          <template #form-item-search>
            <el-button :loading="loading" 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 m-t-mini">
          <base-table
            ref="tableRef"
            border
            stripe
            size="small"
            height="100%"
            :data="tableData"
            :columns="columns"
            highlight-current-row
            :cell-style="{ padding: '6px 0' }"
            @current-change="onCurrentChange"
            @row-dblclick="onDbClick"
          ></base-table>
        </div>
      </div>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="currentReMarkPaper?.filePath"></image-preview>
  <mark-history-list
    :id="currentViewHistory?.taskId"
    v-model="visibleHistory"
    :task="currentViewHistory"
  ></mark-history-list>
</template>

<script setup lang="ts" name="MarkingRepeat">
/** 重评卷查看 */
import { reactive, ref, computed, watch, nextTick } from 'vue'
import { ElButton, ElMessage } from 'element-plus'
import { add } from '@/utils/common'
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 RightButton from '@/components/shared/RightButton.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'

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

type RowType = ExtractMultipleApiResponse<'getReMarkPaperList'> & { 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 modelScore = ref<number[]>([])

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

/** 预览试卷 */
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,
  standard: onViewStandard,
}

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

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

const formModel = reactive<ExtractApiParams<'getReMarkPaperList'>>({
  mainNumber: dataModel.question,
  confirm: false,
  pageNumber: 1,
  pageSize: 9999999,
  subjectCode: dataModel.subject,
})

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

const { defineColumn, _ } = useForm()

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

const formItems = computed<EpFormItem[]>(() => [
  span10({
    rowKey: 'row-1',
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    labelWidth: '46px',
    slot: { options: subjectList.value, onChange: changeModelValue('subject'), disabled: !isExpert.value },
  }),
  span10({
    rowKey: 'row-1',
    label: '大题',
    prop: 'mainNumber',
    slotType: 'select',
    labelWidth: '46px',
    slot: {
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: !isExpert.value && !isLeader.value,
    },
  }),
  span10({
    rowKey: 'row-2',
    label: '状态',
    labelWidth: '46px',
    prop: 'confirm',
    slotType: 'select',
    slot: {
      options: [
        { label: '已确认', value: true },
        { label: '未确认', value: false },
      ],
    },
  }),
  { rowKey: 'row-1', slotName: 'search', labelWidth: '10px', colProp: { span: 4 } },
])

/** 查询重评卷列表 */
const columns: EpTableColumn[] = [
  { label: '密号', prop: 'secretNumber', minWidth: 100, fixed: 'left' },
  { label: '评卷员', prop: 'markerName', minWidth: 80 },
  { label: '给分', prop: 'markerScore', minWidth: 54 },
  // { label: '重评时间', prop: 'reMarkTime', width: 160 },

  { label: '确认状态', prop: 'confirmName', minWidth: 72 },
  { label: '确认给分', prop: 'confirmScore', minWidth: 72 },
  { label: '客观分', prop: 'objectiveScore', minWidth: 72 },
  { label: '客主比', prop: 'ratio', minWidth: 72 },
  { label: '成绩', prop: 'markScore', minWidth: 72 },
  { label: '重评时间', prop: 'reMarkTime', minWidth: 130 },
]

const { fetch: getReMarkPaperList, result: reMarkPaperList, loading } = useFetch('getReMarkPaperList')

const {
  tableRef,
  tableData,
  current: currentReMarkPaper,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
} = useTableCheck(reMarkPaperList)
watch(currentReMarkPaper, () => {
  if (currentReMarkPaper.value) {
    modelScore.value = JSON.parse(JSON.stringify(currentReMarkPaper.value.markScores || []))
    if (currentReMarkPaper.value) {
      useFetch('viewActiveCheck').fetch({ taskId: currentReMarkPaper.value?.taskId })
    }
  }
})
const onSearch = async () => {
  getReMarkPaperList(formModel)
}

const { fetch: confirmReMarkPaper } = useFetch('confirmReMarkPaper')

/** 确认重评 */
const onConfirmReMark = async () => {
  if (currentReMarkPaper.value?.id) {
    await confirmReMarkPaper({ id: currentReMarkPaper.value.id })
    await onSearch()
  }
}

/** 给分 */
const { fetch: markReMarkPaper } = useFetch('markReMarkPaper')

const onSubmit = async () => {
  try {
    if (currentReMarkPaper.value) {
      // const scores = JSON.parse(JSON.stringify(modelScore.value))
      await markReMarkPaper({ id: currentReMarkPaper.value.id, scores: modelScore.value })
      // currentReMarkPaper.value.markerScore = add(...scores)
      ElMessage.success('修改成功')
      onSearch()
    }
  } catch (error) {
    console.error(error)
  }
  modelScore.value = []
  scoringPanelVisible.value = true
}

onOptionInit(onSearch)

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

const { drawing, dataUrl } = useSetImgBg(imgOption, frontColor, setFrontColor)
</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;
    width: 35%;
    .detail-info-label {
      .detail-info-label-num {
        min-width: 32px;
        height: 24px;
        line-height: 24px;
        background: #00987b;
        border-radius: 4px;
      }
    }
  }
}
</style>
