<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'delete', 'bookmark']"
      :paper-path="current?.filePath"
      :secret-number="current?.secretNumber"
      @click="onOperationClick"
    >
      <!-- <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>
    </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>
          <p v-if="current" class="absolute mark-score">{{ current.markerScore }}</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="current?.taskId"
          v-model:visible="editScoreVisible"
          v-model:score="modelScore"
          :main-number="current?.mainNumber"
          modal
          :toggle-modal="false"
          :auto-visible="false"
          @submit="onSubmit"
        ></scoring-panel-with-confirm> -->
          <scoring-panel-with-confirm
            :id="current?.taskId"
            v-model:visible="editScoreVisible"
            v-model:score="modelScore"
            :main-number="current?.mainNumber"
            :subject-code="query.subjectCode"
            modal
            :auto-visible="false"
            @submit="onSubmit"
          ></scoring-panel-with-confirm>
        </pane>
        <pane
          max-size="80"
          :size="100 - paneSize"
          class="flex direction-column p-base radius-base fill-blank table-view"
        >
          <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">{{ selfCheckDataDetail?.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' }"
              :memory-column="true"
              @current-change="onCurrentChange"
              @row-dblclick="onDbClick"
            ></base-table>
          </div>
        </pane>
      </splitpanes>
    </div>
  </div>

  <image-preview v-model="previewModalVisible" :url="current?.filePath"></image-preview>
  <mark-history-list
    :id="currentViewHistory?.taskId"
    v-model="visibleHistory"
    :task="currentViewHistory"
  ></mark-history-list>
  <send-back-mark
    :id="current?.taskId"
    v-model="sendBackVisible"
    type="self-check"
    @rejected="onRejected"
  ></send-back-mark>
</template>

<script setup lang="ts" name="QualitySelfCheckDetail">
/** 自查数据详情 */
import { ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElButton, ElMessage } from 'element-plus'
import { add } from '@/utils/common'
import { useSetImgBg } from '@/hooks/useSetImgBg'
import useFetch from '@/hooks/useFetch'
import useMarkHeader from '@/hooks/useMarkHeader'
import useTableCheck from '@/hooks/useTableCheck'
import MarkHeader from '@/components/shared/MarkHeader.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'
import RightButton from '@/components/shared/RightButton.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'
import ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import MarkHistoryList from '@/components/shared/MarkHistoryList.vue'
import SendBackMark from '@/components/shared/SendBackMark.vue'

import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractApiParams, ExtractApiResponse } from '@/api/api'
import type { MarkHeaderInstance, EpTableColumn } from 'global-type'
import { Splitpanes, Pane } from 'splitpanes'
import { setPaneSize } from '@/utils/common'
import useMainStore from '@/store/main'
const mainStore = useMainStore()
const paneSize = computed(() => {
  return mainStore.paneSizeConfig[location.pathname] || 60
})
type RowType = ExtractApiResponse<'getSelfCheckDataDetail'> & { index: number }

const { query } = useRoute()

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

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

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

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

const { fetch: getSelfCheckDataDetail, result: selfCheckDataDetail } = useFetch('getSelfCheckDataDetail')

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

/** 刷新 */
const onRefresh = () => {
  getSelfCheckDataDetail(query as unknown as ExtractApiParams<'getSelfCheckDataDetail'>)
}

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

/** 修改给分 */
const onEditScore = () => {
  editScoreVisible.value = true
}

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

/** 打回成功 */
const onRejected = () => {
  // checkNext()
  nextRow()
}
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 columns: EpTableColumn<RowType>[] = [
  { label: '密号', prop: 'secretNumber' },
  { label: '评卷员', prop: 'markerName' },
  { label: '离差', prop: 'diff' },
  { label: '正式分', prop: 'markerScore' },
  { label: '自查分', prop: 'selfScore' },
  { label: '自查时间', prop: 'markTime', width: 130 },
]
//该接口貌似是返回全量，不需要pageSize
const {
  tableRef,
  tableData,
  current,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
  nextRow,
} = useTableCheck(selfCheckDataDetail)

watch(current, () => {
  if (current.value) {
    useFetch('viewActiveCheck').fetch({ taskId: current.value.taskId })
  }
})

/** 修改给分 */
const { fetch: markSelfCheckData } = useFetch('markSelfCheckData')

const onSubmit = async () => {
  if (current.value) {
    await markSelfCheckData({ taskId: current.value.taskId, scores: modelScore.value })
    // current.value.markerScore = add(...modelScore.value)
    ElMessage.success('修改成功')
    // editScoreVisible.value = false
    nextRow()
  }
}

onRefresh()

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: current?.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>
