<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 :disabled="!current?.taskId" class="m-l-base" size="small" type="primary" @click="onEditScore"
        >修改给分</el-button
      > -->
      <el-button :disabled="!current?.taskId" 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.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="current?.taskId"
          v-model:visible="editScoreVisible"
          v-model:score="modelScore"
          :main-number="current?.mainNumber"
          modal
          :auto-visible="false"
          :toggle-modal="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 p-b-base m-b-base marker-name">
            <span>评卷员</span>
            <span>{{ query.markerName }}</span>
          </div> -->
          <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">{{ pagination.total }}</span>
            </el-button>

            <btn-pagination v-model="currentPage" :pagination="pagination"></btn-pagination>
            <!-- <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> -->
          </div>
          <div class="flex-1 scroll-auto m-t-mini">
            <base-table
              ref="tableRef"
              border
              stripe
              size="small"
              v-bind="pagination"
              height="100%"
              :data="tableData"
              :columns="columns"
              highlight-current-row
              :cell-style="{ padding: '6px 0' }"
              @current-change="onCurrentChange"
              @row-dblclick="onDbClick"
            ></base-table>
          </div>
        </pane>
      </splitpanes>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="current?.filePath"></image-preview>
  <send-back-mark
    :id="current?.taskId"
    v-model="sendBackVisible"
    type="custom-check"
    @rejected="onRejected"
  ></send-back-mark>
  <mark-history-list
    :id="currentViewHistory?.taskId"
    v-model="visibleHistory"
    :task="currentViewHistory"
  ></mark-history-list>
</template>

<script setup lang="tsx" name="AnalysisViewMarked">
// <script setup lang="ts" name="ViewMarkedDetail">
/** 提取阅卷明细 */
import { ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElButton, ElMessage, ElPagination } from 'element-plus'
import { add } from '@/utils/common'
import { useSetImgBg } from '@/hooks/useSetImgBg'
import useFetch from '@/hooks/useFetch'
import useTable from '@/hooks/useTable'
import useTableCheck from '@/hooks/useTableCheck'
import useMarkHeader from '@/hooks/useMarkHeader'
import MarkHeader from '@/components/shared/MarkHeader.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import MarkHistoryList from '@/components/shared/MarkHistoryList.vue'
import RightButton from '@/components/shared/RightButton.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'
import ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import SendBackMark from '@/components/shared/SendBackMark.vue'
import SecNumberStatus from '@/components/common/secNumberStatus.vue'
import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractMultipleApiResponse, 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'
import BtnPagination from '@/components/common/BtnPagination'
type RowType = ExtractMultipleApiResponse<'getPersonalMarkDetail'> & { index: number }
const mainStore = useMainStore()
const paneSize = computed(() => {
  return mainStore.paneSizeConfig[location.pathname] || 60
})
const props = defineProps<{
  markerId: string
}>()

const { query } = useRoute()
/** 打回弹窗 */
const sendBackVisible = ref<boolean>(false)
/** 打回 */
const onSendBack = () => {
  sendBackVisible.value = true
}
/** 打回成功 */
const onRejected = () => {
  // onRefresh()
  ElMessage.success('打回成功')
}
/** 给分板 */
const editScoreVisible = ref<boolean>(true)

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

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

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

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

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

const onEditScore = () => {
  editScoreVisible.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 columns: EpTableColumn<RowType>[] = [
  {
    label: '评卷员',
    prop: 'markerName',
    minWidth: 90,
    formatter(row: any) {
      return (
        <SecNumberStatus
          secretNumber={row.markerName}
          checked={row.checked}
          corrected={row.corrected}
        ></SecNumberStatus>
      )
    },
  },
  {
    label: '密号',
    prop: 'secretNumber',
    minWidth: 110,
  },
  { label: '给分', prop: 'markerScore', minWidth: 70 },
  { label: '客观分', prop: 'objectiveScore', minWidth: 70 },
  { label: '客主比', prop: 'markerRatio', minWidth: 80 },
  { label: '成绩', prop: 'markScore', minWidth: 70 },
  { label: '评卷时间', prop: 'markTime', minWidth: 130 },
]

const { pagination, currentPage, data, fetchTable } = useTable('getPersonalMarkDetail', {
  markerId: props.markerId,
  score: (query.score as string) || '',
  pageSize: 100,
  subjectCode: query.subjectCode as string,
  mainNumber: query.questionMainNumber as string,
})

const queryPosition: any = query.markScore
  ? { markScore: query.markScore }
  : query.markerRatio
  ? { markerRatio: query.markerRatio }
  : null
const {
  tableRef,
  tableData,
  current,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
  nextRow,
} = useTableCheck(data, true, queryPosition)

/** 确定给分 */
const { fetch: updatePersonalMarkDetailScore } = useFetch('updatePersonalMarkDetailScore')

const onSubmit = async () => {
  if (current.value) {
    const scores = JSON.parse(JSON.stringify(modelScore.value))
    await updatePersonalMarkDetailScore({
      taskId: current.value.taskId,
      scores: modelScore.value,
      source: (query.source as string) || '',
    })
    // current.value.markerScore = add(...scores)
    current.value.markScore = add(...scores)
    ElMessage.success('修改成功')
    // editScoreVisible.value = false
    // onRefresh()
    nextRow()
  }
}
// watch(current, () => {
//   modelScore.value = [current.value?.markerScore || 0]
// })
watch(current, () => {
  if (current.value) {
    useFetch('viewActiveCheck').fetch({ taskId: current.value?.taskId })
  }
})
const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: current?.value?.filePath || '',
    rotate: rotate.value,
    scale: scale.value,
  }
})

const { drawing, dataUrl } = useSetImgBg(imgOption, frontColor, setFrontColor)

onRefresh()
</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: 580px;

    .marker-name {
      border-bottom: $OnePixelLine;
    }
    .detail-info-label {
      .detail-info-label-num {
        min-width: 32px;
        height: 24px;
        line-height: 24px;
        background: #00987b;
        border-radius: 4px;
      }
    }
  }
}
</style>
