<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'delete', 'bookmark']"
      :paper-path="currentSystemCheckPaper?.filePath"
      :secret-number="currentSystemCheckPaper?.secretNumber"
      @click="onOperationClick"
    >
      <template v-if="!hideHeaderButtons">
        <!-- <el-button class="m-l-base" size="small" type="primary" @click="onEditScore">修改给分</el-button> -->
        <el-button class="m-l-base m-r-auto" size="small" type="primary" @click="onSendBack">打回</el-button>
      </template>
    </mark-header>
    <div class="flex flex-1 overflow-hidden p-base mark-container">
      <splitpanes class="default-theme" style="height: 100%" @resize="setPaneSize">
        <pane
          max-size="80"
          :size="paneSize"
          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-wrap">
            <img :src="dataUrl" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
            <p v-if="currentSystemCheckPaper" class="absolute mark-score">
              {{ currentSystemCheckPaper.headerScore ?? currentSystemCheckPaper.markerScore }}
            </p>
          </div>
          <!-- <scoring-panel-with-confirm
          :id="currentSystemCheckPaper?.taskId"
          v-model:visible="scoringPanelVisible"
          v-model:score="modelScore"
          modal
          :toggle-modal="false"
          :auto-visible="false"
          :main-number="currentSystemCheckPaper?.mainNumber"
          @submit="onSubmit"
        ></scoring-panel-with-confirm> -->
          <scoring-panel-with-confirm
            :id="currentSystemCheckPaper?.taskId"
            v-model:visible="scoringPanelVisible"
            v-model:score="modelScore"
            modal
            :auto-visible="false"
            :main-number="currentSystemCheckPaper?.mainNumber"
            :subject-code="formModel.subjectCode"
            @submit="onSubmit"
          ></scoring-panel-with-confirm>
        </pane>
        <pane
          v-loading="loading"
          max-size="80"
          :size="100 - paneSize"
          class="flex direction-column p-base radius-base fill-blank table-view"
        >
          <base-form size="small" :model="formModel" :items="formItems" :label-width="'52px'">
            <template #form-item-search>
              <el-button :loading="loading" type="primary" @click="onSearch">查询</el-button>
            </template>
          </base-form>
          <div class="flex items-center justify-between detail-info-table-header">
            <el-button custom-1 size="small" class="detail-info-label">
              <span class="">系统抽查卷: 共</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> -->
            <btn-pagination v-model="currentPage" :pagination="pagination"></btn-pagination>
          </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' }"
              :memory-column="true"
              @current-change="onCurrentChange"
              @row-dblclick="onDbClick"
            ></base-table>
          </div>
        </pane>
      </splitpanes>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="currentSystemCheckPaper?.filePath"></image-preview>

  <mark-history-list
    :id="currentViewHistory?.taskId"
    v-model="visibleHistory"
    :task="currentViewHistory"
  ></mark-history-list>
  <send-back-mark
    :id="currentSystemCheckPaper?.id"
    v-model="sendBackVisible"
    type="system-check"
    @rejected="onRejected"
  ></send-back-mark>
</template>

<script setup lang="tsx" name="SystemCheck">
/** 系统抽查卷 */
import { reactive, ref, computed, watch } from 'vue'
import { ElButton, ElPagination, 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 useTable from '@/hooks/useTable'

import useTableCheck from '@/hooks/useTableCheck'
import MarkHeader from '@/components/shared/MarkHeader.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 ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'
import SecNumberStatus from '@/components/common/secNumberStatus.vue'

import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractApiParams } from '@/api/api'
import type { MarkHeaderInstance, EpFormItem, EpTableColumn } from 'global-type'
import { Splitpanes, Pane } from 'splitpanes'
import { setPaneSize } from '@/utils/common'
import useMainStore from '@/store/main'
import BtnPagination from '@/components/common/BtnPagination.vue'
const mainStore = useMainStore()
const paneSize = computed(() => {
  return mainStore.paneSizeConfig[location.pathname] || 60
})
const {
  rotate,
  scale,
  center,
  frontColor,
  backgroundColor,
  onBack,
  onScaleChange,
  onCenter,
  onRotate,
  setBackgroundColor,
  setFrontColor,
  onViewStandard,
} = useMarkHeader()

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

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

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

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

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

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

/** 修改给分 */
const onEditScore = () => {
  scoringPanelVisible.value = true
  modelScore.value = currentSystemCheckPaper.value.markScores
}

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

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

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, isLeader, isExpert } = useOptions([
  'subject',
  'question',
])

const formModel = reactive<any>({
  mainNumber: dataModel.question,
  status: 'INITIAL',
  level: '',
  // pageNumber: 1,
  // pageSize: 9999999,
  subjectCode: dataModel.subject,
})

const hideHeaderButtons = computed(() => {
  return formModel.status === 'REJECT'
})

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: '50px',
    slot: { options: subjectList.value, onChange: changeModelValue('subject'), disabled: !isExpert.value },
  }),
  span10({
    rowKey: 'row-1',
    label: '大题',
    prop: 'mainNumber',
    slotType: 'select',
    labelWidth: '50px',
    slot: {
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: !isExpert.value && !isLeader.value,
    },
  }),
  span10({
    rowKey: 'row-2',
    label: '档次',
    prop: 'level',
    slotType: 'select',
    labelWidth: '50px',
    slot: {
      // options: [{ label: '全部', value: '' }, ...[1, 2, 3, 4, 5].map((n) => ({ label: n, value: `LEVEL_${n}` }))],
      // options: [
      //   { label: '全部', value: '' },
      //   ...['0', '2', '5', '8', '11', '14'].map((n) => ({ label: n, value: `LEVEL_${n}` })),
      // ],
      options: [{ label: '全部', value: '' }, ...(levelOptions.value || []).map((n: any) => ({ label: n, value: n }))],
    },
  }),
  { rowKey: 'row-1', slotName: 'search', labelWidth: '10px', colProp: { span: 4 } },
  span10({
    rowKey: 'row-2',
    label: '类型',
    prop: 'status',
    slotType: 'select',
    labelWidth: '50px',
    slot: {
      options: [
        { label: '未浏览', value: 'INITIAL' },
        { label: '已浏览', value: 'VIEWED' },
        { label: '已给分', value: 'GRADED' },
        { label: '已打回', value: 'REJECT' },
      ],
    },
  }),
])

/** 系统抽查卷列表 */

const columns: EpTableColumn[] = [
  {
    label: '密号',
    prop: 'secretNumber',
    minWidth: 110,
    fixed: 'left',
    formatter(row: any) {
      return (
        <SecNumberStatus
          secretNumber={row.secretNumber}
          checked={row.checked}
          corrected={row.corrected}
        ></SecNumberStatus>
      )
    },
  },
  { label: '评卷员', prop: 'markerName', minWidth: 80 },
  { label: '评卷员给分', prop: 'markerScore', minWidth: 108, sortable: true },
  { label: '组长给分', prop: 'headerScore', minWidth: 94, sortable: true },
  // { label: '评卷时间', prop: 'markTime', width: 160 },
  { label: '客观分', prop: 'objectiveScore', minWidth: 90, sortable: true },
  { label: '客主比', prop: 'ratio', minWidth: 90, sortable: true },
  { label: '成绩', prop: 'markScore', minWidth: 90, sortable: true },
  { label: '抽查次数', prop: 'checkCount', minWidth: 94, sortable: true },
  { label: '评卷时间', prop: 'markTime', minWidth: 130 },
]

// const { fetch: getSystemSpotList, result: systemSpotList, loading } = useFetch('getSystemSpotList')
const { fetch: getSystemCheckLevel, result: levelOptions } = useFetch('getSystemCheckLevel')
getSystemCheckLevel()

const { pagination, currentPage, data, fetchTable, loading, total } = useTable('getSystemSpotList', formModel, {
  pageSize: 100,
})
const {
  tableRef,
  tableData,
  current: currentSystemCheckPaper,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
  nextRow,
  // } = useTableCheck(systemSpotList)
} = useTableCheck(data)

watch(currentSystemCheckPaper, () => {
  if (currentSystemCheckPaper.value) {
    useFetch('viewSystemSpotPaper')
      .fetch({ id: currentSystemCheckPaper.value.id })
      .then(() => {
        if (!currentSystemCheckPaper.value.checked) {
          currentSystemCheckPaper.value.checked = true
        }
        currentSystemCheckPaper.value.checkCount = (currentSystemCheckPaper.value.checkCount || 0) + 1
      })
    // modelScore.value = [currentSystemCheckPaper.value?.headerScore ?? (currentSystemCheckPaper.value?.markScore || 0)]
    modelScore.value = currentSystemCheckPaper.value?.markScores || []
  }
})

const onSearch = async () => {
  // getSystemSpotList(formModel)
  currentPage.value = 1
}

/** 系统抽查卷打分 */
const { fetch: markSystemSpotPaper } = useFetch('markSystemSpotPaper')

const onSubmit = async () => {
  if (currentSystemCheckPaper.value) {
    const scores = JSON.parse(JSON.stringify(modelScore.value))
    let res: any = await markSystemSpotPaper({ id: currentSystemCheckPaper.value.id, scores: modelScore.value })
    currentSystemCheckPaper.value.markScore = currentSystemCheckPaper.value.headerScore = add(...scores)
    currentSystemCheckPaper.value.markScores = scores
    currentSystemCheckPaper.value.checked = res.checked
    currentSystemCheckPaper.value.corrected = res.corrected
    currentSystemCheckPaper.value.objectiveScore = res.objectiveScore
    currentSystemCheckPaper.value.ratio = res.ratio
    currentSystemCheckPaper.value.markerScore = res.markerScore
    ElMessage.success('修改成功')
    // scoringPanelVisible.value = false
    // onSearch()
    // fetchTable()
    nextRow()
  }
}

onOptionInit(onSearch)

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentSystemCheckPaper?.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: 20px;
      right: 25px;
      font-size: 38px;
    }
    .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>
