<template>
  <div class="flex direction-column full mark-page">
    <mark-header
      :exclude-operations="excludeOperations"
      :paper-path="currentTask?.url"
      :secret-number="currentTask?.secretNumber"
      @click="onOperationClick"
    >
      <div class="data-item">
        <!-- 已评: {{ markStatus?.personCount || 0 }} /
        {{ minus(markStatus?.totalCount || 0, markStatus?.markedCount || 0) }} -->
        <div>
          <p>
            今日：{{ markStatus?.personDayCount }}
            {{ mainStore.myUserInfo?.markDayCount ? `/ ${mainStore.myUserInfo?.markDayCount}` : '' }}
          </p>
          <p class="m-t-mini">累计：{{ markStatus?.personCount }}</p>
        </div>
      </div>
      <!-- <span v-show="currentTask" class="data-item">密号: {{ currentTask?.secretNumber }}</span> -->
      <div v-show="currentTask" class="data-item">
        <div>
          <p class="main-ques-info truncate">{{ currentTask?.mainNumber }}-{{ currentTask?.mainTitle }}</p>
          <p>密号: {{ currentTask?.secretNumber }}</p>
        </div>
      </div>
      <div class="data-item">
        <current-time></current-time>
      </div>
    </mark-header>
    <div class="flex flex-1 overflow-hidden p-base mark-container">
      <div v-if="!enableRemark && !currentTask" class="waiting flex flex-1 justify-center items-center">
        等待组长审核
      </div>
      <div
        v-else-if="!!currentTask"
        v-loading="imgLoading"
        class="flex flex-1 direction-column radius-base full fill-blank mark-content"
        :style="{ 'background-color': backgroundColor }"
      >
        <span class="mark-status">
          <img :src="statusIcon" alt="" />
        </span>
        <span class="preview" :style="{ left: previewLeft }" @click="onPreview">
          <svg-icon name="preview"></svg-icon>
        </span>
        <div ref="imgWrap" :class="{ 'text-center': center }" class="img-wrap scroll-auto">
          <img
            ref="paperImg"
            :src="dataUrl"
            alt=""
            class="paper-img"
            :style="{ 'background-color': frontColor, maxWidth: '100%' }"
            @load="imgLoaded"
          />
        </div>
        <scoring-panel-with-confirm
          v-if="currentTask && dataUrl && !imgLoading"
          :id="currentTask?.taskId"
          v-model:visible="scoringPanelVisible"
          v-model:score="modelScore"
          :main-number="currentTask?.mainNumber"
          :subject-code="mainStore.myUserInfo?.subjectCode"
          :large="true"
          @submit="onSubmit"
        ></scoring-panel-with-confirm>
      </div>
      <remark-box
        v-if="remarkModalVisible"
        ref="remarkBoxRef"
        :img-option="imgOption"
        @task-change="historyTaskChange"
        @back="historyBack"
        @close="historyClose"
      ></remark-box>
    </div>
  </div>
  <base-dialog v-model="problemVisible" unless :width="280" center>
    <el-radio-group v-model="problemClass">
      <el-radio-button label="problem">问题卷</el-radio-button>
      <el-radio-button label="similar">雷同卷</el-radio-button>
    </el-radio-group>

    <div class="m-t-base problem-pane" style="height: 80px">
      <el-radio-group v-show="problemClass === 'problem'" v-model="problemType" class="full-w">
        <div class="full-w">
          <el-radio label="OVERSTEP">跨套</el-radio>
        </div>
        <div class="full-w">
          <el-radio label="DIM">扫描图片不清晰</el-radio>
        </div>
      </el-radio-group>
      <!-- <el-radio v-show="problemClass === 'similar'" model-value="similar" label="similar">提交雷同</el-radio> -->
      <el-radio v-show="problemClass === 'similar'" v-model="similarType" label="similar">提交雷同</el-radio>
    </div>
    <template #footer>
      <div class="flex items-center justify-between">
        <el-button class="confirm-button" type="primary" @click="onConfirmSubmitProblem">确定</el-button>
        <el-button class="confirm-button" plain @click="problemVisible = false">取消</el-button>
      </div>
    </template>
  </base-dialog>
  <!-- <remark-list-modal v-model="remarkModalVisible" @task-change="historyTaskChange"></remark-list-modal> -->
  <!-- <image-preview v-if="currentTask" v-model="previewModalVisible" :url="currentTask?.url"></image-preview> -->
  <image-preview v-if="currentTask" v-model="previewModalVisible" :url="currentTask?.url"></image-preview>
  <el-dialog
    v-model="showRejectReason"
    :title="`打回试卷（${rejectTask?.secretNumber}）`"
    width="500px"
    :close-on-click-modal="false"
  >
    <div>
      <span style="font-size: 14px; font-weight: bold; color: #333">原因：</span
      ><span style="font-size: 14px">{{ rejectTask?.rejectReason }}</span>
    </div>
    <div class="m-t-base">
      <span style="font-size: 14px; font-weight: bold; color: #333">说明：</span
      ><span style="font-size: 14px">{{ rejectTask?.rejectDes }}</span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="showRejectReason = false"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="MarkingMark">
/** 阅卷-正式评卷 */
import { computed, nextTick, ref, watch, onBeforeUnmount, unref } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElRadioGroup, ElRadioButton, ElRadio, ElMessage, ElDialog } from 'element-plus'
import { minus } from '@/utils/common'
import { useSetImgBg } from '@/hooks/useSetImgBg'
import useFetch from '@/hooks/useFetch'
import useVW from '@/hooks/useVW'
import useSpentTime from '@/hooks/useSpentTime'
import useMarkHeader from '@/hooks/useMarkHeader'
import BaseDialog from '@/components/element/BaseDialog.vue'
import MarkHeader from '@/components/shared/MarkHeader.vue'
import ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'
import RemarkListModal from '@/components/shared/RemarkListModal.vue'
import CurrentTime from '@/components/shared/CurrentTime.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'
import bus from '@/utils/bus'
import useMainLayoutStore from '@/store/layout'
import useMainStore from '@/store/main'
import MarkingStatus from '@/assets/images/status-marking.png'
import ReMarkingStatus from '@/assets/images/status-remarking.png'
import SampleAStatus from '@/assets/images/status-sample-a.png'
import SampleBStatus from '@/assets/images/status-sample-b.png'
import RemarkBox from './remark-box.vue'
import { preloadImg } from '@/utils/common'
import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractApiResponse } from '@/api/api'
import type { MarkHeaderInstance } from 'global-type'
const mainLayoutStore = useMainLayoutStore()
const mainStore = useMainStore()
const { push, replace } = useRouter()
const imgWrap = ref()
const { getSpentTime, resume } = useSpentTime()
const remarkBoxKey = ref<any>(Date.now() + '')
const CACHE_NUM = 2

type TaskType = ExtractArrayValue<ExtractApiResponse<'getMarkingTask'>>['taskType'] | 'default' | 'remarking'

const markStatusIcon: Partial<Record<TaskType, string>> = {
  FORMAL: MarkingStatus,
  remarking: ReMarkingStatus,
  SAMPLE_A: SampleAStatus,
  SAMPLE_B: SampleBStatus,
  default: MarkingStatus,
}
const paperImg = ref()
const currentTaskType = ref<TaskType>('FORMAL')

const statusIcon = computed(() => {
  return markStatusIcon[currentTaskType.value] || markStatusIcon.default
})
const enableRemark = ref(true)
const {
  rotate,
  scale,
  center,
  frontColor,
  backgroundColor,
  onScaleChange,
  onCenter,
  onRotate,
  setBackgroundColor,
  setFrontColor,
  onViewSample,
  onViewStandard,
} = useMarkHeader()

type HistoryTaskType = ExtractArrayValue<ExtractApiResponse<'getMarkHistory'>>
type FormalTaskType = ExtractArrayValue<ExtractApiResponse<'getMarkingTask'>>

type TaskInfoType = FormalTaskType | HistoryTaskType

// let currentTaskPool: ExtractApiResponse<'getMarkingTask'> = []
let currentTaskPool: any = []

const currentTask = ref<TaskInfoType & { dataUrl?: any }>()

type excludeOperationTypes = InstanceType<typeof MarkHeader>['$props']['excludeOperations']

const excludeOperations = computed<excludeOperationTypes>(() => {
  if (!currentTask.value?.taskType) {
    return ['delete', 'bookmark']
  }
  const isSampleType = ['SAMPLE_A', 'SAMPLE_B'].includes(currentTask.value.taskType)
  // return ['delete', 'bookmark'].concat(isSampleType ? ['problem'] : []) as excludeOperationTypes
  return ['delete', 'bookmark']
})

const { fetch: getMarkingTask, loading } = useFetch('getMarkingTask')
const { fetch: submitMarkTask, loading: submitting } = useFetch('submitMarkTask')
const { fetch: getMarkStatus, result: markStatus } = useFetch('getMarkStatus')

const historyTaskChange = (task: any) => {
  let saveTargetTask = unref(currentTask)
  console.log('saveTargetTask:', saveTargetTask)
  if (currentTaskType.value != 'remarking' && saveTargetTask) {
    currentTaskPool.unshift(saveTargetTask)
    handleTaskPool()
  }
  currentTask.value = task
  currentTaskType.value = 'remarking'
  nextTick(() => {
    modelScore.value = task.markerScores
  })
}
const historyBack = () => {
  setCurrentTask()
  remarkModalVisible.value = false
}
const historyClose = () => {
  remarkModalVisible.value = false
}
const setCurrentTask = () => {
  currentTask.value = currentTaskPool.shift()
  currentTaskType.value =
    currentTask.value && markStatusIcon[currentTask.value.taskType] ? currentTask.value.taskType : 'FORMAL'
}

let refreshTimer: number | null = null

onBeforeUnmount(() => {
  if (refreshTimer) {
    clearTimeout(refreshTimer)
    refreshTimer = null
  }
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})

const refreshTaskPool = (force = false, isRefresh = false, hasLimit = false) => {
  if (refreshTimer) {
    clearTimeout(refreshTimer)
  }
  refreshTimer = window.setTimeout(
    () => {
      if (currentTaskPool.length < (isRefresh ? Number.MAX_SAFE_INTEGER : CACHE_NUM)) {
        // if (currentTaskPool.length < Number.MAX_SAFE_INTEGER) {
        getMarkingTask().then((result: any) => {
          if (result?.length) {
            // currentTaskPool[isRefresh ? 'unshift' : 'push'](...result)
            // result[1] && (result[1].url = '/file/sample_b/1/1/1/SAMPA-14.jpg')
            // result[1] && (result[1].url = 'http://127.0.0.1:9991/break-test.jpg')
            if (hasLimit) {
              result = result.filter((item: any) => {
                return item.taskType === 'FORCE'
              })
            }
            if (isRefresh) {
              if ((result[0] as any).taskType === 'FORCE') {
                currentTaskPool = currentTaskPool.filter((item: any) => {
                  return item.taskType === 'FORCE' || !!item.markerId
                })
                currentTaskPool.unshift(...result)
              } else {
                currentTaskPool.unshift(...result)
              }
            } else {
              currentTaskPool.push(...result)
            }
            handleTaskPool()
          }
          if (currentTaskPool?.length && !currentTask.value) {
            setCurrentTask()
          }
          refreshTaskPool(false, false, hasLimit)
        })
      }
    },
    force ? 0 : 5000
  )
}

/**
 * @param force 即时更新任务
 * @param isRefresh 是否有插队任务
 */
const getNextTask = (force = false, isRefresh = false, hasLimit = false) => {
  // if (isRefresh) {
  //   if (currentTaskPool.length && !!currentTaskPool[0].markerId) {
  //     setCurrentTask()
  //   }
  // } else {
  setCurrentTask()
  // }

  refreshTaskPool(force, isRefresh, !!hasLimit)
}

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

/** 回评弹窗 */
const remarkModalVisible = ref<boolean>(false)

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

/** 问题卷弹窗 */
const problemVisible = ref<boolean>(false)
/** 问题卷 | 雷同卷   */
const problemClass = ref<'problem' | 'similar'>('problem')
/** 问题卷类型 */
// const problemType = ref<ProblemType>('OVERSTEP')
const problemType = ref<any>('')
const similarType = ref<any>('')
watch(problemVisible, () => {
  if (problemVisible.value) {
    problemClass.value = 'problem'
    problemType.value = ''
    similarType.value = ''
  }
})
/** 分数列表 */
const modelScore = ref<number[]>([])
const remarkBoxRef = ref()
/** 提交评卷 */
const onSubmit: InstanceType<typeof ScoringPanelWithConfirm>['onSubmit'] = async ({ question, scores, totalScore }) => {
  try {
    if (!currentTask.value?.taskId) {
      return
    }

    const spentTime = getSpentTime()

    const current = currentTask.value as FormalTaskType
    if (current.minMarkTime && current.minMarkTime * 1000 > spentTime) {
      scoringPanelVisible.value = true
      return ElMessage.warning('阅卷速度过快')
    }
    const submitResult = await submitMarkTask({
      spentTime,
      markScore: totalScore,
      markScores: scores,
      problem: false,
      taskId: currentTask.value.taskId,
      taskType: currentTask.value.taskType,
    })
    mainStore.setMarkerPausedLimit(submitResult?.markerPausedLimit || 0)
    let bool = await checkMarkStatus()
    // if (!bool) {
    //   return false
    // }
    if (remarkModalVisible.value) {
      remarkBoxRef.value?.updateRow(totalScore)
      let nextHistoryTask = remarkBoxRef.value?.getNextRow()
      if (nextHistoryTask) {
        historyTaskChange(nextHistoryTask)
      } else {
        if (nextHistoryTask === false) {
          //说明回评列表是空的，当前依然处于正评，走正常的正评逻辑，且关闭回评列表
          remarkModalVisible.value = false
          await getNextTask(true, submitResult?.refresh, !bool)
        }
      }
    } else {
      await getNextTask(true, submitResult?.refresh, !bool)
    }
  } catch (error) {
    console.error(error)
    scoringPanelVisible.value = true
  }
}

const onSubmitSimilar = async () => {
  if (!currentTask.value) {
    return
  }
  const markHistory = await useFetch('getMarkHistory').fetch()
  if (!markHistory.markHistoryList.length) {
    return ElMessage.warning('暂无评卷记录')
  }
  return push({
    name: 'SubmitSimilar',
    params: { taskId: currentTask.value.taskId },
    query: {
      secretNumber: currentTask.value.secretNumber,
    },
  })
}

const onSubmitProblem = async () => {
  if (!currentTask.value) {
    return
  }
  const submitResult = await submitMarkTask({
    markScore: 0,
    markScores: [],
    spentTime: getSpentTime(),
    problem: true,
    problemType: problemType.value,
    taskId: currentTask.value.taskId,
    taskType: currentTask.value.taskType,
  })
  let bool = await checkMarkStatus()
  // if (!bool) {
  //   return false
  // }
  // await getNextTask(true, submitResult?.refresh, !bool)
  if (remarkModalVisible.value) {
    let nextHistoryTask = remarkBoxRef.value?.getNextRow()
    if (nextHistoryTask) {
      historyTaskChange(nextHistoryTask)
    } else {
      if (nextHistoryTask === false) {
        //说明回评列表是空的，当前依然处于正评，走正常的正评逻辑，且关闭回评列表
        remarkModalVisible.value = false
        await getNextTask(true, submitResult?.refresh, !bool)
      }
    }
  } else {
    await getNextTask(true, submitResult?.refresh, !bool)
  }
}

/** 提交问题卷 & 雷同卷 */
const onConfirmSubmitProblem = async () => {
  if (problemClass.value === 'problem' && !problemType.value) {
    ElMessage.error('请选择问题卷类型')
    return
  }
  if (problemClass.value === 'similar' && !similarType.value) {
    ElMessage.error('请选择雷同卷类型')
    return
  }
  try {
    if (!currentTask.value) {
      return
    }
    if (currentTask.value.taskType !== 'FORMAL') {
      ElMessage.error('该试卷类型不能提交问题卷')
      return
    }
    problemVisible.value = false
    if (problemClass.value === 'similar') {
      await onSubmitSimilar()
    } else {
      await onSubmitProblem()
    }
  } catch (error) {
    console.error(error)
  }
}

/** 返回 */
const onBack = () => {
  /** 回评时返回到正评, 否则返回到评卷员主页 */
  // if (currentTaskType.value === 'remarking') {
  //   getNextTask()
  // } else {
  replace({
    name: 'MarkingNav',
  })
  // }
}
const clearTaskView = () => {
  currentTaskPool = currentTaskPool.filter((item: any) => {
    return item.taskType === 'FORCE'
  })
  handleTaskPool()
  currentTask.value = undefined
}
const checkMarkStatus = async (): Promise<boolean> => {
  if (currentTask.value?.taskType === 'FORCE') {
    return true
  }
  // let myUserInfo: any = await useFetch('getMyUserInfo').fetch()
  let myUserInfo: any = (await mainStore.getMyUserInfo()) || {}
  //markDayCount表示该用户当天的任务量限制，markTotalCount表示该用户总任务量限制
  const { markDayCount, markTotalCount } = myUserInfo
  let res: any = await getMarkStatus()
  if (!!markTotalCount && res.personCount >= markTotalCount) {
    ElMessage.success(`任务量${markTotalCount}已完成`)
    clearTaskView()
    return false
  } else if (!!markDayCount && res.personDayCount >= markDayCount) {
    ElMessage.success(`您当天的任务量${markDayCount}已完成`)
    clearTaskView()
    return false
  } else {
    return true
  }
}
const onRefreshNext = () => {
  // onRefresh(true)  暂时注释掉，这是之前做的，点击刷新按钮获取本地任务池里的下一条的效果
  location.reload()
}
/** 刷新 */
const onRefresh = async (refreshToNext?: boolean) => {
  let bool = await checkMarkStatus()
  // if (!bool) {
  //   return false
  // }
  if (!refreshToNext) {
    await useFetch('clearCachedTasks').fetch()
  }
  if (!bool) {
    getNextTask(true, false, true)
  } else {
    getNextTask(true)
  }
}

/** 回评 */
const onRemark = () => {
  // remarkModalVisible.value = true
  useFetch('getMarkHistory')
    .fetch()
    .then((markHistoryRes: any) => {
      if (!markHistoryRes.enableRemark) {
        ElMessage.warning('审核中，暂时无法回评')
      } else {
        remarkBoxKey.value = new Date().getTime() + ''
        remarkModalVisible.value = true
      }
    })
}

/** 设置问题卷 */
const onSetProblem = () => {
  problemVisible.value = true
}

/** 预览试卷 */
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: onRefreshNext,
  remark: onRemark,
  problem: onSetProblem,
  example: onViewSample,
  standard: onViewStandard,
}

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

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentTask?.value?.url,
    rotate: rotate.value,
    scale: scale.value,
  }
})
const { drawing, dataUrl, imgLoading } = useSetImgBg(imgOption, frontColor, setFrontColor)

const getEnableRemark = () => {
  useFetch('getMarkHistory')
    .fetch()
    .then((markHistoryRes: any) => {
      enableRemark.value = markHistoryRes.enableRemark
    })
}
// const clearScrollTop = () => {
//   if (imgWrap.value) {
//     imgWrap.value.scrollTop = 0
//   }
// }
const showRejectReason = ref(false)
const rejectTask = ref<any>(null)
let timer: any = null
watch(currentTask, (newVal, oldVal) => {
  if (!oldVal && !!newVal) {
    getMarkStatus()
  }
  resume()
  if (!currentTask.value) {
    getEnableRemark()
  } else {
    if (currentTask.value?.rejectReason) {
      showRejectReason.value = true
      rejectTask.value = currentTask.value
    }
  }
  // clearScrollTop()
})

onRefresh()
getEnableRemark()
// bus.on('showStandard', () => {
//   standardVisible.value = true
// })
watch(enableRemark, (val) => {
  if (!val) {
    timer = setInterval(() => {
      getEnableRemark()
    }, 7000)
  } else {
    clearInterval(timer)
    timer = null
    getMarkStatus()
  }
  mainLayoutStore.getRenderMenuList()
})
bus.on('mark-prev', async () => {
  if (currentTaskType.value == 'remarking') {
    const markHistory = await useFetch('getMarkHistory').fetch()
    if (!markHistory.markHistoryList.length) {
      return false
    } else {
      historyTaskChange(markHistory.markHistoryList[0])
    }
  }
})
const showPreviewBtn = ref(false)
const previewLeft = computed(() => {
  return currentTaskType.value === 'SAMPLE_A' || currentTaskType.value === 'SAMPLE_B' ? '124px' : '96px'
})
// const previewLeft = ref('-1000px')
const imgLoaded = () => {
  // previewLeft.value = paperImg.value.width - 40 + 'px'
  showPreviewBtn.value = true
}

const handleTaskPool = () => {
  currentTaskPool.forEach((task: any) => {
    preloadImg(task?.url)
  })
}
</script>

<style scoped lang="scss">
.mark-page {
  :deep(> .el-overlay) {
    &.dialog-fade-leave-active {
      animation: none !important;
    }
  }
}

.mark-container {
  .waiting {
    background-color: #fff;
    font-size: 80px;
    color: #ccc;
    height: 100%;
  }
  .mark-content {
    position: relative;
    .img-wrap {
      // width: 100%;
      // height: 100%;
      // overflow: auto;
    }
    .mark-status {
      display: inline-block;
      // width: 24px;
      height: 38px;
      position: absolute;
      cursor: pointer;
      top: 38px;
      left: 20px;
      z-index: 100;
      img {
        // max-width: 100%;
        max-height: 100%;
      }
    }
    .preview {
      position: absolute;
      cursor: pointer;
      z-index: 100;
      top: 36px;
      font-size: 38px;
    }
  }
}
</style>
