<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'delete']"
      :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" size="small" type="primary" @click="onSendBack"
        >打回</el-button
      >
      <!-- <el-button
        custom-1
        class="m-l-base m-r-auto"
        size="small"
        type="success"
        :disabled="!tableData?.length"
        @click="multToggle"
        >{{ isMult ? '取消多选' : '多选' }}</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>
          <!-- <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="current" class="absolute question-info">
              {{ current.mainNumber + '-' + current.mainName }}
            </p>
            <p v-if="current" class="absolute mark-score">
              {{ current.markScore }}
            </p>
          </div>
          <!-- <scoring-panel-with-confirm
          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
            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">{{ pagination.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"
              v-loading="loading"
              border
              stripe
              size="small"
              height="100%"
              v-bind="pagination"
              :highlight-current-row="!isMult"
              :data="tableData"
              :columns="columns"
              :cell-style="{ padding: '6px 0' }"
              :memory-column="true"
              @current-change="onCurrentChange"
              @row-dblclick="onDbClick"
              @selection-change="handleSelectionChange"
            ></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="rejectIds" v-model="sendBackVisible" type="custom-check" @rejected="onRejected"></send-back-mark>

  <base-dialog v-model="setExpertPaperVisible" title="设置专家卷" :footer="false" :width="540">
    <base-form size="small" :model="setExpertModel" :items="items" :label-width="'130px'">
      <template v-if="paperTableData.length > 0" #form-item-paperTable>
        <base-table
          ref="tableRef"
          v-loading="paperLoading"
          style="width: 240px"
          border
          stripe
          size="small"
          :data="paperTableData"
          :columns="[
            { label: '密号', prop: 'secretNumber', width: 120 },
            { label: '分数', prop: 'score' },
          ]"
          max-height="120"
          :cell-style="{ padding: '3px 0' }"
          :header-cell-style="{ padding: '3px 0' }"
        ></base-table>
      </template>
      <template #form-item-confirm>
        <confirm-button
          class="m-t-base"
          @confirm="onConfirmSetExpert"
          @cancel="setExpertPaperVisible = false"
        ></confirm-button>
      </template>
    </base-form>
  </base-dialog>
</template>

<script setup lang="tsx" name="MarkingInquiryResult">
/** 自定义查询结果 */
import { ref, computed, watch, reactive, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElButton, ElPagination, ElMessage } 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 useVW from '@/hooks/useVW'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseDialog from '@/components/element/BaseDialog.vue'
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 } from '@/api/api'
import type { MarkHeaderInstance, EpTableColumn, EpFormItem } 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 isMult = ref(false)
const multipleSelection = ref<any>([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
const mainStore = useMainStore()
const paneSize = computed(() => {
  return mainStore.paneSizeConfig[location.pathname] || 60
})
type RowType = ExtractMultipleApiResponse<'getCustomQueryTasks'> & { index: number }
const { fetch: getExpertAssessList, result: rfSampleList, loading: paperLoading } = useFetch('getExpertAssessList')
const paperTableData = computed<any>(() => {
  return rfSampleList.value?.result || []
})
const { query } = useRoute()
/** 打回弹窗 */
const sendBackVisible = ref<boolean>(false)
/** 打回 */
const onSendBack = () => {
  sendBackVisible.value = true
}
/** 打回成功 */
const onRejected = () => {
  // onRefresh()
  ElMessage.success('打回成功')
  // fetchTable()
}

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

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

/** 设置专家卷 */
const setExpertPaperVisible = 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 onBookmark = () => {
  setExpertPaperVisible.value = true
}

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

const onEditScore = () => {
  editScoreVisible.value = true
  modelScore.value = current.value.markScores
}

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,
  bookmark: onBookmark,
}

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

const columns: any = computed(() => {
  let cols: any = [
    {
      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: 90 },
    { label: '评卷员给分', prop: 'markerScore', minWidth: 108, sortable: true },
    { label: '组长给分', prop: 'headerScore', minWidth: 94, sortable: true },
    { label: '客观分', prop: 'objectiveScore', minWidth: 90, sortable: true },
    { label: '客主比', prop: 'ratio', minWidth: 90, sortable: true },
    { label: '成绩', prop: 'markScore', minWidth: 90, sortable: true },
    { label: '评卷时间', prop: 'markTime', minWidth: 130 },
    { label: '抽查次数', prop: 'customCheckNumber', minWidth: 94, sortable: true },
  ]
  if (isMult.value) {
    cols.unshift({
      type: 'selection',
      width: 55,
    })
  }
  return cols
})

const transTime = (str: any) => {
  if (str.indexOf('-') > -1) {
    return str
  } else {
    return `${str.slice(0, 4)}-${str.slice(4, 6)}-${str.slice(6, 8)} ${str.slice(8, 10)}:${str.slice(
      10,
      12
    )}:${str.slice(12, 14)}`
  }
}

const transformQuery = (query: Record<string, string>) => {
  let params: Record<string, string> = {}

  for (let k in query) {
    params[k] = ['true', 'false'].includes(query[k]) ? new Function(`return ${query[k]}`)() : query[k]
  }
  if (params.timeStart) {
    params.timeStart = transTime(params.timeStart)
  }
  if (params.timeEnd) {
    params.timeEnd = transTime(params.timeEnd)
  }
  return params
}

const { pagination, currentPage, data, fetchTable, loading } = useTable(
  'getCustomQueryTasks',
  transformQuery(query as Record<string, string>),
  { pageSize: 100 }
)

const {
  tableRef,
  tableData,
  current,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
  nextRow,
  elTableRef,
} = useTableCheck(data, true, null, false, isMult)

watch(current, () => {
  if (current.value) {
    useFetch('viewCustomQuery')
      .fetch({ taskId: current.value.taskId })
      .then(() => {
        if (!current.value.checked) {
          current.value.checked = true
        }
        current.value.customCheckNumber = (current.value.customCheckNumber || 0) + 1
      })
    // modelScore.value = [current.value?.headerScore ?? (current.value?.markerScore || 0)]
    modelScore.value = current.value?.markScores || []
  }
})

type SetExpertModel = {
  paperType: ExtractApiParams<'updateCustomPaperType'>['paperType']
  forceGroupNumber?: 'A' | 'B' | number
}

const setExpertModel = reactive<SetExpertModel>({
  paperType: 'FORCE',
  forceGroupNumber: 'A',
})

watch([() => setExpertModel.forceGroupNumber, setExpertPaperVisible], () => {
  if (setExpertModel.forceGroupNumber !== 'A' && setExpertModel.forceGroupNumber !== 'B' && setExpertPaperVisible.value)
    getExpertAssessList({
      subjectCode: query.subjectCode as string,
      mainNumber: query.mainNumber as string,
      pageNumber: 1,
      pageSize: 9999999,
      forceGroupNumber: setExpertModel.forceGroupNumber as any,
    })
})

const items = computed<EpFormItem[]>(() => {
  let paperTypeItems: EpFormItem[] = [
    {
      label: '当前试卷设置为',
      prop: 'paperType',
      slotType: 'radio',
      slot: {
        options: [
          { label: 'FORCE', slotLabel: '考核卷' },
          { label: 'RF', slotLabel: '样卷' },
          { label: 'STANDARD', slotLabel: '标准卷' },
        ],
      },
    },
  ]
  let forceGroupNumberItems: EpFormItem[] = [
    {
      label: '培训卷组',
      prop: 'forceGroupNumber',
      slotType: 'radio',
      slot: {
        options: [{ label: 'A' }, { label: 'B' }],
      },
    },
    {
      label: '强制考核卷组',
      prop: 'forceGroupNumber',
      slotType: 'radio',
      slot: {
        options: [
          // { label: 'A' },
          // { label: 'B' },
          ...Array.from({ length: 10 }).map((_, index) => ({ label: `${index + 1}` })),
        ],
      },
    },
    {
      label: '',
      slotName: 'paperTable',
    },
  ]
  return paperTypeItems
    .concat(setExpertModel.paperType === 'FORCE' ? forceGroupNumberItems : [])
    .concat({ slotName: 'confirm' })
})

const getPaperTypeAndGroupNumber = (
  params: SetExpertModel
): { paperType: ExpertPickType; forceGroupNumber?: number } => {
  if (['RF', 'STANDARD'].includes(params.paperType)) {
    return {
      paperType: params.paperType,
      forceGroupNumber: void 0,
    }
  } else if (params.forceGroupNumber === 'A' || params.forceGroupNumber === 'B') {
    return {
      paperType: params.forceGroupNumber === 'A' ? 'SAMPLE_A' : 'SAMPLE_B',
      forceGroupNumber: void 0,
    }
  } else {
    return {
      paperType: 'FORCE',
      forceGroupNumber: params.forceGroupNumber,
    }
  }
}

/** 确定设置专家卷 */
const onConfirmSetExpert = async () => {
  if (!current.value) {
    return
  }
  try {
    await useFetch('updateCustomPaperType').fetch({
      taskId: current.value.taskId,
      ...getPaperTypeAndGroupNumber(setExpertModel),
    })
    setExpertPaperVisible.value = false
  } catch (error) {
    console.error(error)
  }
}

/** 确定给分 */
const onSubmit = async () => {
  if (current.value) {
    const scores = JSON.parse(JSON.stringify(modelScore.value))

    let res: any = await useFetch('updateCustomPaperScore').fetch({
      taskId: current.value.taskId,
      scores: modelScore.value,
    })

    current.value.markScore = current.value.headerScore = add(...scores)
    current.value.markScores = scores
    current.value.checked = res.checked
    current.value.corrected = res.corrected
    current.value.headerScore = res.headerScore
    current.value.objectiveScore = res.objectiveScore
    current.value.ratio = res.ratio
    current.value.markTime = res.markTime
    current.value.markerScore = res.markerScore
    // onRefresh()
    ElMessage.success('修改成功')
    // editScoreVisible.value = false
    nextRow()
  }
}

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

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

onRefresh()

const multToggle = () => {
  isMult.value = !isMult.value
  editScoreVisible.value = !isMult.value
  if (!isMult.value && tableData.value?.length && current.value) {
    nextTick(() => {
      let index = tableData.value.findIndex((task: any) => task.taskId == current.value?.taskId)
      elTableRef?.value?.setCurrentRow(tableData.value[index == -1 ? 0 : index])
    })
  }
  if (isMult.value) {
    elTableRef?.value?.clearSelection()
  }
}
const rejectIds = computed(() => {
  return isMult.value ? multipleSelection.value.map((item: any) => item.taskId) : [current.value?.taskId]
})
</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%;
      }
    }
  }
  // @media (max-width: 10000px) {
  //   .table-view {
  //     .detail-info-label {
  //       width: 200px !important;
  //     }
  //   }
  // }
  .table-view {
    // width: 620px;
    .detail-info-label {
      .detail-info-label-num {
        min-width: 32px;
        height: 24px;
        line-height: 24px;
        background: #00987b;
        border-radius: 4px;
      }
    }
  }
}
</style>
