<script setup lang="ts">
import doWorkApi from '@/api/subject/doWork'
import homeWorkApi from '@/api/system/homeWork'
// 作业

import globalApi from '@/api/global'
import { debounce, XMessage } from '@/hooks'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'

import { $XXL, getDurationText } from '@/utils'

import { userStore, groupPaperStore } from '@/stores'
import {
  resource_type_ai,
  resource_type_analogy,
  resource_type_free,
  resource_type_homework,
  resource_type_paper,
  resource_type_wrong_book,
  resource_type_wrong_retry,
  resource_type_similar_recommend,
} from '.'
import wrongQuestionApi from '@/api/subject/wrongQuestion'
import type { IQuestion } from '@/types/question'
import { globalBack } from '@/router'
import { dialog } from '@/components/mj/mj-dialog'
import hud from '@/utils/hud'
import sass from '@/utils/sass'
import homeworkApi, { saveRecordAnswer, submitExam } from '@/api/subject/homework'

const emit = defineEmits(['urgeSubmit'])

defineOptions({
  name: 'DoWork',
})

const { token } = userStore()
const { groupPaperParams } = toRefs(groupPaperStore())

const resourceTypeConfig: Record<string, string> = {
  [resource_type_free]: '自由学',
  [resource_type_ai]: 'AI精准学',
  [resource_type_wrong_book]: '错题本',
  [resource_type_analogy]: '举一反三',
  [resource_type_homework]: '作业',
  [resource_type_wrong_retry]: '错题重练',
  [resource_type_similar_recommend]: '举一反三',
}

// 提交作业
const submitLoading = ref(false)
// 页面加载中（应该要默认为true，不然跟pageLoading相关的组件，可能会2次创建）
const pageLoading = ref(true)

const route = useRoute()
const router = useRouter()
// 题目列表
interface WorkQuestion extends IQuestion {
  /** 还未做过这道题 */
  unLook: boolean
  /** 上传中 */
  uploadLoading: boolean
  correctResult: boolean
}
const paperList = ref<WorkQuestion[]>([])
const paperInfo = ref<any>({})

function normalizePaperList(list: unknown, markUnLook = false): WorkQuestion[] {
  if (!Array.isArray(list)) return []
  if (!markUnLook) return list as WorkQuestion[]
  return list.map((item: any, idx: number) => ({
    ...item,
    unLook: idx > 0,
  })) as WorkQuestion[]
}

// 计时器缓存key
const getTimerKey = () => {
  const id = params.value.recordId || paperInfo.value.id
  return id ? `dowork_timer_${id}` : null
}

// 当前所在题目
const activeIdx = ref(-1)
const indicatorRef = ref()

// 是否为答题页面  0 答题  1 查看作业结果
const reportFlag = ref<0 | 1>(0)
// 是否可以直接离开当前页面
let leaveFlag = false
// 查询参数
const params = ref<anyObj>({})
// 获取参数
if (route.params.id) {
  // 查看已经完成的训练
  leaveFlag = true
  reportFlag.value = 1
  params.value = {
    ...route.query,
    id: route.params.id,
  }
} else {
  // 开始新训练
  reportFlag.value = 0
  params.value = { num: 10, ...route.query }
}

// 切换题目
async function switchQuestion(idx?: number) {
  // 点击当前题目，需要保存答案，且不能是已完成的作业
  if (idx === activeIdx.value) {
    if (
      !reportFlag.value &&
      (resourceType.value === resource_type_homework ||
        resourceType.value === resource_type_wrong_retry ||
        resourceType.value === resource_type_similar_recommend)
    ) {
      saveRecordAnswer({
        answer: paperList.value[activeIdx.value].submitAnswer || '',
        answerPic: paperList.value[activeIdx.value].submitAnswerPic || '',
        costTime: paperInfo.value.costTime * 1000,
        itemId: paperList.value[activeIdx.value].itemId,
        recordId: params.value.recordId,
      })
    }
    return
  }
  let flag = false // 是否为点击下一题
  if (idx !== undefined) {
    activeIdx.value = idx
  } else {
    if (activeIdx.value < paperList.value.length - 1) {
      console.log('点击下一题', paperList.value[activeIdx.value])
      // 如果是多选题，需要把submitAnswer进行字幕排序 为A,B,C,D
      if (paperList.value[activeIdx.value].titleChannelTypeName === '多选题') {
        const raw = paperList.value[activeIdx.value].submitAnswer || ''
        paperList.value[activeIdx.value].submitAnswer = raw
          .split(',')
          .filter(Boolean)
          .sort()
          .join(',')
      }
      // 点击下一题，保存答案
      if (
        resourceType.value === resource_type_homework ||
        resourceType.value === resource_type_wrong_retry ||
        resourceType.value === resource_type_similar_recommend
      ) {
        saveRecordAnswer({
          answer: paperList.value[activeIdx.value].submitAnswer || '',
          answerPic: paperList.value[activeIdx.value].submitAnswerPic || '',
          costTime: paperInfo.value.costTime * 1000,
          itemId: paperList.value[activeIdx.value].itemId,
          recordId: params.value.recordId,
        })
      }
      activeIdx.value++
      flag = true
    } else if (activeIdx.value === paperList.value.length - 1) {
      if (!reportFlag.value) {
        // 提交整卷前先保存当前题
        if (
          resourceType.value === resource_type_homework ||
          resourceType.value === resource_type_wrong_retry ||
          resourceType.value === resource_type_similar_recommend
        ) {
          saveRecordAnswer({
            answer: paperList.value[activeIdx.value].submitAnswer || '',
            answerPic: paperList.value[activeIdx.value].submitAnswerPic || '',
            costTime: paperInfo.value.costTime * 1000,
            itemId: paperList.value[activeIdx.value].itemId,
            recordId: params.value.recordId,
          })
        }
        // 提交作业
        if (paperList.value.some(i => i.uploadLoading)) {
          return XMessage.error('上传中，请稍后～')
        }
        if (paperList.value.some(i => !i.submitAnswer && !i.submitAnswerPic)) {
          dialog.show({
            content: '还有题目未作答，确定要提交答案吗？',
            ok: submitTrain,
          })
        } else {
          submitTrain()
        }
      }
    }
  }
  if (!reportFlag.value && paperList.value?.[activeIdx.value]) {
    paperList.value[activeIdx.value].unLook = false
  }

  // 点击下一题时下方往后滑动
  await nextTick()
  if (flag) indicatorRef.value && (indicatorRef.value.scrollLeft += 104)
}
const debounceChange = debounce(switchQuestion, 300)

// 上传前
function beforeUpload(rawFile: any) {
  const fileType = ['image/jpeg', 'image/png']
  if (!fileType.includes(rawFile.type)) {
    XMessage.error('上传格式不正确，只支持JPG/PNG')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    XMessage.error('图片过大')
    return false
  }
  return true
}
// 设置某道题的 uploadLoading（按 titleId 精确定位，避免因 activeIdx 变化造成串台）
function setUploadLoadingByTitleId(titleId: unknown, value: boolean) {
  if (!titleId) return
  const idx = paperList.value.findIndex(i =>
    isSameQuestionKey(getQuestionKey(i as anyObj), titleId),
  )
  if (idx !== -1) paperList.value[idx].uploadLoading = value
}

// 上传
async function uploadFile(options: anyObj) {
  const currentQuestion = paperList.value[activeIdx.value] as anyObj | undefined
  if (!currentQuestion) return
  const currentTitleId = getQuestionKey(currentQuestion)
  setUploadLoadingByTitleId(currentTitleId, true)

  try {
    let path = ''
    if (options.isAndroid) {
      if (options.submitAnswerPicOriginal) {
        const res = await $XXL.uploadFile({
          url: `${import.meta.env.VITE_SERVER_URL}/sysFileInfo/tenUploadAll`,
          header: {
            Authorization: token,
            'X-Tenant-Id': sass.platform.tenantId,
          },
          filePath: options.file,
          fileKey: 'file',
        })
        path = res.url
      }
    } else {
      const formData = new FormData()
      formData.append('file', options.file)
      const { data: res } = await globalApi.uploadFile(formData)
      path = extractUploadPath(res)
    }
    path = String(path || '')
      .replace(/[`]/g, '')
      .replace(/http:\/\//gi, 'https://')
      .trim()
    if (!options.isAndroid && !path) {
      hud.error('上传成功但未获取到图片地址，请重试')
      return
    }
    if (options.submitAnswerPicOriginal) {
      submitQuestion({
        submitAnswerPic: path,
        submitAnswerPicOriginal: options.submitAnswerPicOriginal,
        id: currentTitleId,
        isAndroid: options.isAndroid || 0,
      })
    } else {
      if (options.isAndroid) {
        submitQuestion({
          submitAnswerPic: '',
          submitAnswerPicOriginal: '',
          id: currentTitleId,
          isAndroid: 1,
        })
      } else {
        submitQuestion({
          filePath: path,
          id: currentTitleId,
          isAndroid: options.isAndroid || 0,
          fromCamera: !!options.fromCamera,
          replaceOnCameraUpload: !!options.replaceOnCameraUpload,
        })
      }
    }
    if (!reportFlag.value) {
      // 仅当当前题目仍是上传时的题目，才执行 switchQuestion 保存逻辑，避免抢答状态污染
      const currentIdx = paperList.value.findIndex(i =>
        isSameQuestionKey(getQuestionKey(i as anyObj), currentTitleId),
      )
      if (currentIdx === activeIdx.value) {
        await switchQuestion(activeIdx.value)
      }
    }
  } catch (error) {
    console.error('uploadFile error', error)
    hud.error('网络异常，请检查网络～')
  } finally {
    const finalIdx = paperList.value.findIndex(i =>
      isSameQuestionKey(getQuestionKey(i as anyObj), currentTitleId),
    )
    if (finalIdx !== -1) {
      paperList.value[finalIdx].uploadLoading = false
      paperList.value[finalIdx].isAndroid = options.isAndroid
    }
  }
}

let timeout: any
function startTime(init?: boolean) {
  clearInterval(timeout)
  if (init) paperInfo.value.costTime = 0

  // 尝试从缓存恢复时间
  const key = getTimerKey()
  if (key) {
    try {
      const saved = localStorage.getItem(key)
      if (saved) {
        const { costTime, timestamp } = JSON.parse(saved)
        const now = Date.now()
        // 如果缓存的时间大于服务端返回的时间，说明本地记录更准（服务端可能还没同步）
        // 加上时间差（防止刷新页面期间的时间丢失，设定阈值为5分钟内）
        const gap = (now - timestamp) / 1000
        if (costTime >= (paperInfo.value.costTime || 0)) {
          paperInfo.value.costTime = costTime
          if (gap < 300) {
            paperInfo.value.costTime += Math.floor(gap)
          }
        }
      }
    } catch (e) {
      console.error(e)
    }
  }

  const startTimestamp = Date.now() - (paperInfo.value.costTime || 0) * 1000

  timeout = setInterval(() => {
    // 使用时间差计算，避免setInterval的漂移
    const now = Date.now()
    paperInfo.value.costTime = Math.floor((now - startTimestamp) / 1000)

    // 保存到缓存
    if (key) {
      localStorage.setItem(
        key,
        JSON.stringify({
          costTime: paperInfo.value.costTime,
          timestamp: now,
        }),
      )
    }
  }, 1000)
}
const timeFilter = computed(() => {
  if (reportFlag.value) {
    // 查看报告
    if (paperInfo.value.costTimeInfo) return paperInfo.value.costTimeInfo
  }
  return getDurationText(paperInfo.value.costTime, reportFlag.value ? 'ms' : 's')
})

function handleTime(type: 0 | 1) {
  if (type) {
    startTime()
  } else {
    clearInterval(timeout)
  }
}

const submitFn = () => {
  switch (params.value.isHomework) {
    case resource_type_analogy:
      return homeWorkApi.submitHomeWorkInferences
    case resource_type_wrong_book:
      return homeWorkApi.submitErrorEditionObjective
    default:
      return doWorkApi.submitTrainRecord
  }
}

function normalizeAnswerPic(val: unknown) {
  return String(val || '')
    .split(',')
    .map(i =>
      String(i || '')
        .replace(/[`]/g, '')
        .replace(/http:\/\//gi, 'https://')
        .trim(),
    )
    .filter(Boolean)
    .join(',')
}

function isUploadImageQuestion(item: anyObj) {
  const typeText = [
    item?.titleChannelTypeName,
    item?.channelTypeName,
    item?.typeName,
    item?.titleTypeName,
  ]
    .filter(Boolean)
    .join(',')
  return /上传|拍照/.test(typeText)
}

function extractPicLinksFromAnswer(answer: unknown) {
  const raw = String(answer || '')
  if (!raw) return ''
  const links = raw.match(/https?:\/\/[^\s,]+/g) || []
  return normalizeAnswerPic(links.join(','))
}

function getSubmitAnswerPic(item: anyObj) {
  const answerPic = normalizeAnswerPic(item?.submitAnswerPic)
  if (answerPic) return answerPic
  if (!isUploadImageQuestion(item)) return ''
  return extractPicLinksFromAnswer(item?.submitAnswer)
}

function getQuestionKey(item: anyObj) {
  return item?.id || item?.itemId || item?.jobStuTittleId || ''
}

function isSameQuestionKey(a: unknown, b: unknown) {
  const aKey = String(a || '').trim()
  const bKey = String(b || '').trim()
  if (!aKey || !bKey) return false
  return aKey === bKey
}

function extractUploadPath(res: any) {
  return res?.data?.filePath || res?.data?.url || res?.filePath || res?.url || res?.data?.path || ''
}

function findQuestionIndexById(answerId: unknown) {
  return paperList.value.findIndex(i => isSameQuestionKey(getQuestionKey(i as anyObj), answerId))
}

function handleFilePathAnswer(answer: any, params: anyObj) {
  const idx = findQuestionIndexById(answer.id)
  if (idx === -1) return

  const safeUrl = String(answer.filePath || '')
    .replace(/[`]/g, '')
    .replace(/http:\/\//gi, 'https://')
    .trim()
  const q = paperList.value[idx]
  const isHandDrawn =
    q?.autoMarkFlag === 0 &&
    (q?.titleChannelTypeName === '填空题' ||
      (q?.subjectId === 3 && q?.titleChannelTypeName === '解答题'))
  const isCamera = !!answer.fromCamera
  const hadOriginal = !!q.submitAnswerPicOriginal

  let submitPic = ''
  if (isHandDrawn) {
    if (isCamera) {
      if (answer.replaceOnCameraUpload || hadOriginal) {
        submitPic = safeUrl
      } else {
        submitPic = q.submitAnswerPic || '' ? `${q.submitAnswerPic},${safeUrl}` : safeUrl
      }
    } else {
      submitPic = safeUrl
    }
  } else {
    submitPic = q.submitAnswerPic || '' ? `${q.submitAnswerPic},${safeUrl}` : safeUrl
  }

  const limitedSubmitPic = isCamera
    ? submitPic
        .split(',')
        .map(i => (i || '').trim())
        .filter(Boolean)
        .slice(-3)
        .join(',')
    : submitPic

  paperList.value[idx].submitAnswerPic = limitedSubmitPic
  params.submitAnswerPic = limitedSubmitPic
  if (isCamera) {
    paperList.value[idx].submitAnswerPicOriginal = ''
    params.submitAnswerPicOriginal = ''
  }
}

function clearAnswerPicById(answerId: unknown, params: anyObj) {
  const idx = findQuestionIndexById(answerId)
  if (idx === -1) return
  paperList.value[idx].submitAnswerPic = ''
  paperList.value[idx].submitAnswerPicOriginal = ''
  params.submitAnswerPic = ''
  params.submitAnswerPicOriginal = ''
}

function replaceAnswerPicById(answer: any, params: anyObj) {
  const idx = findQuestionIndexById(answer.id)
  if (idx === -1) return
  paperList.value[idx].submitAnswerPic = answer.submitAnswerPic
  paperList.value[idx].submitAnswerPicOriginal = answer.submitAnswerPicOriginal
  params.submitAnswerPic = answer.submitAnswerPic
  params.submitAnswerPicOriginal = answer.submitAnswerPicOriginal
}

// 提交每道题目
function submitQuestion(answer: any) {
  if (reportFlag.value) return
  const params: anyObj = {
    id: answer.id,
    isAndroid: answer.isAndroid,
  }
  if (answer.filePath) {
    // 添加图片
    handleFilePathAnswer(answer, params)
  } else if (answer.submitAnswer) {
    paperList.value[activeIdx.value].submitAnswer = answer.submitAnswer
    params.submitAnswer = answer.submitAnswer
  } else if (answer.delUrl) {
    // 删除图片
    const picList = paperList.value[activeIdx.value].submitAnswerPic.split(',') || []
    const idx = picList.indexOf(answer.delUrl)
    picList.splice(idx, 1)
    params.submitAnswerPic = picList.join(',')
    paperList.value[activeIdx.value].submitAnswerPic = params.submitAnswerPic
  } else if (answer.clearCanvas) {
    clearAnswerPicById(answer.id, params)
  } else if (answer.submitAnswerPic) {
    // 替换图片
    replaceAnswerPicById(answer, params)
  } else if (answer.submitAnswerPic === '' && answer.isAndroid) {
    // 清空图片
    clearAnswerPicById(answer.id, params)
  }

  // 单选题直接跳转下一题
  if (answer.toNext && activeIdx.value < paperList.value.length - 1) {
    setTimeout(switchQuestion, 0)
  }

  // 作业
  if (resourceType.value === resource_type_homework) {
    // 提交作业
    console.log(params)
  }
}

// 提交整个卷子练习
async function submitTrain() {
  clearInterval(timeout)
  await hud.load({
    option: '提交',
    task: async () => {
      let data
      /// 提交作业 / 错题重练 / 举一反三
      if (
        resourceType.value === resource_type_homework ||
        resourceType.value === resource_type_wrong_retry ||
        resourceType.value === resource_type_similar_recommend
      ) {
        data = await submitExam({
          answerDtoList: paperList.value.map(item => ({
            itemId: getQuestionKey(item),
            answer: item.submitAnswer || '',
            answerPic: getSubmitAnswerPic(item),
          })),
          costTime: paperInfo.value.costTime * 1000,
          recordId: params.value.recordId,
        })
      } else {
        data = await submitFn()({
          id: paperInfo.value.id,
          answerDtoList: paperList.value.map(item => ({
            titleId: getQuestionKey(item),
            answer: item.submitAnswer || '',
            answerPic: getSubmitAnswerPic(item),
          })),
          subjectId: params.value.subjectId || paperInfo.value.subjectId,
          costTime: paperInfo.value.costTime * 1000,
        })
      }
      paperInfo.value = data
      // paperList.value = data.titleVoList
      // handleChange(0)
      // // console.log('提交完成', data.titleVoList);
      // handleShowReport()
      leaveFlag = true
      // reportFlag.value = 1
      // params.value.id = paperInfo.value.id

      // if (inspectorInfo.value.conductInspectorPlanId) {
      //     // 督学模式
      //     return emit('urgeSubmit')
      // }

      // 清除本地缓存的时间
      const key = getTimerKey()
      if (key) localStorage.removeItem(key)

      // 指示标点返回第一个
      // await nextTick()
      // indicatorRef.value && (indicatorRef.value.scrollLeft = 0)
    },
    hideSuccess: true,
  })
  setTimeout(() => {
    globalBack()
  }, 200)
}

// 初始化报告
async function initReport() {
  // 查看已经完成的训练
  if (
    params.value.resourceType === resource_type_homework ||
    params.value.resourceType === resource_type_wrong_retry ||
    params.value.resourceType === resource_type_similar_recommend
  ) {
    const exam = await homeWorkApi.getPaperRecordDetail({
      recordId: params.value.recordId || params.value.id,
      reportFlag: 1,
    })
    paperInfo.value = exam.data
    paperList.value = normalizePaperList(exam.data?.titleVoList)
  } else {
    // 训练
    const data = await doWorkApi.getTrainSingle(params.value.id)
    paperInfo.value = data
    paperList.value = normalizePaperList(data?.titleVoList ?? data?.xkwQuestionTitleVoList)
  }
}

// 初始化新的训练
async function initNewTrain() {
  // 开始新训练
  if (params.value.resourceType === resource_type_homework) {
    // 作业
    const exam = await homeworkApi.startExam(params.value.recordId)
    paperInfo.value = exam
    if (paperInfo.value.costTime) {
      paperInfo.value.costTime = Math.floor(paperInfo.value.costTime / 1000)
    }
    paperList.value = normalizePaperList(exam?.titleVoList)
  } else if (params.value.resourceType === resource_type_paper) {
    // 自由组卷
    const { data: res } = await doWorkApi.startGroupPaper(groupPaperParams.value!)
    if (res.code !== 200) return
    paperInfo.value = res.data
    if (paperInfo.value.costTime) {
      paperInfo.value.costTime = Math.floor(paperInfo.value.costTime / 1000)
    }
    paperList.value = normalizePaperList(res.data?.titleVoList, true)
  } else if (params.value.isHomework === resource_type_analogy) {
    // 举一反三
    const { data: res } = await homeWorkApi.homeWorkInferences(params.value)
    if (res.code !== 200) return
    paperInfo.value = {
      subjectId: params.value.subjectId,
      costTime: 0,
    }
    paperList.value = normalizePaperList(res.data, true)
  } else if (params.value.isHomework === resource_type_wrong_book) {
    // 订正错题
    const { data: res } = await homeWorkApi.errorEditionObjective(params.value)
    if (res.code !== 200) return
    paperInfo.value = {
      subjectId: params.value.subjectId,
      costTime: 0,
    }
    paperList.value = normalizePaperList(res.data, true)
  } else if (params.value.resourceType === resource_type_wrong_retry) {
    // 错题重练
    const retryData = await wrongQuestionApi.retryStart({
      chapterId: params.value.chapterId ? Number(params.value.chapterId) : undefined,
      courseId: params.value.courseId ? Number(params.value.courseId) : undefined,
      questionCount: params.value.questionCount ? Number(params.value.questionCount) : 3,
      subjectId: params.value.subjectId ? Number(params.value.subjectId) : undefined,
      textbookId: params.value.textbookId ? Number(params.value.textbookId) : undefined,
    })
    params.value.recordId = retryData.recordId
    paperInfo.value = {
      id: retryData.recordId,
      paperId: retryData.paperId,
      paperName: retryData.paperName || '错题重练',
      costTime: retryData.costTime || 0,
      remark: retryData.remark,
      subjectId: params.value.subjectId,
    }
    paperList.value = normalizePaperList(retryData?.titleVoList, true)
  } else if (params.value.resourceType === resource_type_similar_recommend) {
    // 举一反三（错题本）
    const retryData = await wrongQuestionApi.similarRecommend({
      questionId: params.value.questionId,
    })
    params.value.recordId = retryData.recordId
    paperInfo.value = {
      id: retryData.recordId,
      paperId: retryData.paperId,
      paperName: retryData.paperName || '举一反三',
      costTime: retryData.costTime || 0,
      remark: retryData.remark,
      subjectId: params.value.subjectId,
    }
    paperList.value = normalizePaperList(retryData?.titleVoList, true)
  } else {
    const options = {
      ...params.value,
      // learnTarget: userInfo.value.learnTargetType,
    }
    // 其他练习
    const data = await doWorkApi.addTrain(options)
    paperInfo.value = data
    if (paperInfo.value.costTime) {
      paperInfo.value.costTime = Math.floor(paperInfo.value.costTime / 1000)
    }
    paperList.value = normalizePaperList(data?.xkwQuestionTitleVoList ?? data?.titleVoList, true)
  }

  if (!paperList.value.length) {
    XMessage.error('当前暂无可练习题目')
    leaveFlag = true
    router.go(-1)
  }
}

async function init() {
  try {
    pageLoading.value = true
    // 查看报告 且 不是作业
    // console.log('resourceType.value', resourceType.value ,resource_type_homework);

    if (reportFlag.value) {
      await initReport()
    } else {
      await initNewTrain()
      if (!paperList.value.length) return
      startTime()
    }
    if (params.value.idx) {
      switchQuestion(Number(params.value.idx))
    } else {
      switchQuestion(0)
    }
  } catch (err) {
    console.error('init error', err)
    leaveFlag = true
    router.go(-1)
  } finally {
    pageLoading.value = false
  }
}

function endTime() {
  clearInterval(timeout)
}

const resourceType = computed(() => {
  return route.query.resourceType || params.value.resourceType || paperInfo.value.resourceType
})

// 标题
const title = computed(() => {
  const type = resourceType.value
  if (type === resource_type_paper) {
    return groupPaperParams.value?.trainType === 1 ? '章节组卷' : '知识点组卷'
  } else if (type === resource_type_homework) {
    const name = paperInfo.value.paperName
    if (name) {
      // 去除日期
      return name.replace(/-\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, '')
    }
  }
  return (
    paperInfo.value.knowledgeName ||
    paperInfo.value.chapterName ||
    resourceTypeConfig[type] ||
    '自由学'
  )
})

/** 生命周期函数 */
onBeforeRouteLeave((to, _from, next) => {
  if (leaveFlag) return next()
  if (to.path === '/login') return next()
  next(false)

  if (dialog.isShowing()) return
  dialog.show({
    content: '是否确认退出，退出后不保留答题记录',
    ok: () => {
      leaveFlag = true
      // 清除本地缓存的时间
      const key = getTimerKey()
      if (key) localStorage.removeItem(key)
      router.go(-1)
    },
  })
})

// PC端鼠标拖拽滚动
let isDragging = false
let startX = 0
let scrollLeftStart = 0

function handleMouseDown(e: MouseEvent) {
  if (!indicatorRef.value) return
  isDragging = true
  startX = e.pageX - indicatorRef.value.offsetLeft
  scrollLeftStart = indicatorRef.value.scrollLeft
  indicatorRef.value.style.cursor = 'grabbing'
}

function handleMouseMove(e: MouseEvent) {
  if (!isDragging || !indicatorRef.value) return
  e.preventDefault()
  const x = e.pageX - indicatorRef.value.offsetLeft
  const walk = (x - startX) * 1.5 // 滚动速度
  indicatorRef.value.scrollLeft = scrollLeftStart - walk
}

function handleMouseUp() {
  isDragging = false
  if (indicatorRef.value) {
    indicatorRef.value.style.cursor = 'grab'
  }
}

function handleMouseLeave() {
  isDragging = false
  if (indicatorRef.value) {
    indicatorRef.value.style.cursor = 'grab'
  }
}

onMounted(async () => {
  if (route.fullPath === '/subject/doWork') {
    leaveFlag = true
    // 缺少参数，就直接返回
    globalBack()
    return
  }

  // 屏幕常亮
  $XXL.setScreenOn(1)
  await init()

  // 初始化拖拽滚动
  await nextTick()
  if (indicatorRef.value) {
    indicatorRef.value.style.cursor = 'grab'
    indicatorRef.value.addEventListener('mousedown', handleMouseDown)
    indicatorRef.value.addEventListener('mousemove', handleMouseMove)
    indicatorRef.value.addEventListener('mouseup', handleMouseUp)
    indicatorRef.value.addEventListener('mouseleave', handleMouseLeave)
  }
})

onUnmounted(() => {
  // 清理拖拽滚动事件
  if (indicatorRef.value) {
    indicatorRef.value.removeEventListener('mousedown', handleMouseDown)
    indicatorRef.value.removeEventListener('mousemove', handleMouseMove)
    indicatorRef.value.removeEventListener('mouseup', handleMouseUp)
    indicatorRef.value.removeEventListener('mouseleave', handleMouseLeave)
  }

  if (paperInfo.value && typeof paperInfo.value === 'object') {
    paperInfo.value.costTime = 0
  }
  activeIdx.value = 0
  paperList.value = []
  paperInfo.value = {}
  leaveFlag = false
  clearInterval(timeout)
})

defineExpose({
  startTime,
  endTime,
})
</script>
<template>
  <div class="dowork g-main-bg">
    <div class="top">
      <div>
        <BackBar />
      </div>
      <div v-if="!pageLoading" class="top-timeout">
        <Icon name="clock" width="48"></Icon>
        {{ timeFilter }}
      </div>
    </div>
    <div v-if="!pageLoading" class="main">
      <div class="main-box">
        <div class="main-top">
          <div class="title" :data-content="title">
            {{ title }}
          </div>
        </div>
        <div class="book-box">
          <div class="book">
            <template v-if="paperList && paperList.length > 0 && paperList[activeIdx]">
              <Question
                :data="paperList[activeIdx]"
                :idx="activeIdx + 1"
                :total="paperList.length"
                :resource-type="resourceType"
                :isDeadline="!!reportFlag"
                :reportFlag="reportFlag"
                :subjectId="paperInfo.subjectId"
                :isHomework="params.isHomework"
                :uploadFile="uploadFile"
                :beforeUpload="beforeUpload"
                @submit="submitQuestion"
                @handleTime="handleTime"
              ></Question>
            </template>
          </div>
        </div>
        <div class="bottom">
          <div ref="indicatorRef" class="indicator">
            <div
              v-for="(i, idx) in paperList"
              v-show="!i.unLook"
              :key="i.id"
              :class="{
                'indicator-item': true,
                pointer: true,
                active: activeIdx === idx,
                success: reportFlag && (i.correctResult || i.markFlag),
                error: reportFlag && !(i.correctResult || i.markFlag),
                empty: !i.submitAnswer && !i.submitAnswerPic,
              }"
              @click="switchQuestion(idx)"
            >
              {{ idx + 1 }}
            </div>
          </div>
          <mj-button
            v-if="!reportFlag"
            type="success"
            width="192"
            height="80"
            size="32"
            tilt
            :loading="submitLoading"
            :disabled="paperList && paperList[activeIdx] && paperList[activeIdx].uploadLoading"
            @click="debounceChange()"
          >
            {{
              paperList && paperList.length && activeIdx < paperList.length - 1 ? '下一题' : '提交'
            }}
          </mj-button>
        </div>
      </div>
    </div>
    <mj-loading
      v-else
      v-model="pageLoading"
      :fullscreen="true"
      :text="reportFlag ? '正在加载报告中...' : '正在精选题目中...'"
    />
  </div>
</template>
<style scoped lang="scss">
$filter: brightness(0) saturate(0) invert(0) sepia(0) hue-rotate(30deg);

.dowork {
  // background: rgb(163, 175, 199);
  position: relative;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  line-height: 1.5;
  // @include hidden_scroll;

  .top {
    padding: 2.67vh 64px 0;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &-timeout {
      color: $font-color;
      text-align: center;
      text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
      font-family: $font-special;
      font-size: 2.67vh;
      height: 4vh;
      display: flex;
      .x-icon {
        margin-right: 8px;
        filter: $filter;
      }
    }
  }
  .main {
    box-sizing: border-box;
    padding: 0 32px;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    &-top {
      margin-bottom: 1vh;
      display: flex;
      justify-content: center;
      padding: 0 140px;
      .title {
        color: #fff;
        text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
        font-family: $font-special;
        font-size: 4vh;
        font-style: normal;
        font-weight: 400;
        line-height: 6vh; /* 150% */
        text-align: center;
        letter-spacing: 10px;
        @include font-stroke($font-color, 6px);
        @include single_ellipsis;
      }
      .list-num {
        color: #fff;
        text-align: center;
        text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
        font-family: OPPOSans;
        font-size: 2.67vh;
        font-style: normal;
        font-weight: 400;
        line-height: 4vh; /* 150% */
      }
    }
    &-box {
      position: relative;
      top: 3vh;
    }

    .book-box {
      position: relative;
      height: 80vh;
      padding-top: 1.25vh;
    }
    .book {
      box-sizing: border-box;
      position: relative;
      z-index: auto;
      height: 100%;
      padding-bottom: 5.83vh;
      flex-shrink: 0;
      border-radius: 3.33vh;
    }
  }
  .bottom {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0 32px;
    position: relative;
    z-index: 10;
    overflow: hidden; // 确保子元素能正确计算可滚动区域
    touch-action: pan-x pinch-zoom; // 允许水平滑动
    .indicator {
      flex: 1;
      min-width: 0; // 关键：允许 flex 子项收缩，触发 overflow
      display: flex;
      overflow-x: auto;
      overflow-y: hidden;
      padding: 0.83vh 0;
      cursor: grab; // PC端显示可拖拽光标
      user-select: none; // 防止拖拽时选中文字
      // 隐藏滚动条但保持可滚动
      scrollbar-width: none; // Firefox
      -ms-overflow-style: none; // IE/Edge
      &::-webkit-scrollbar {
        display: none; // Chrome/Safari
      }
      &:active {
        cursor: grabbing;
      }

      &-item {
        box-sizing: border-box;
        width: 6.67vh;
        height: 6.67vh;
        background: #bed5fe;
        // border: 4px solid #fff;
        border-radius: 50%;
        margin-right: 24px;
        color: $font-color;
        text-align: center;
        font-family: $font-special;
        font-size: 3.33vh;
        font-style: normal;
        font-weight: 400;
        line-height: 6.67vh; /* 150% */
        text-align: center;
        flex-shrink: 0;
        box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.25);
        touch-action: pan-x; // 允许水平滑动，不阻止滚动
        &:last-child {
          margin-right: 0;
        }
        &.error {
          background: #febebf;
          border-color: #f00809;
          color: #f00809;
        }
        &.success {
          background: #ddff8c;
          border-color: #8ecc00;
          color: #8ecc00;
        }
        &.empty {
          background: #cccccc;
          color: #ffffff;
          border-color: #aaa;
        }
        &.active {
          background: #ebf1fd;
          border: 0.33vh solid #7eacfe;
          line-height: 6vh;

          &.empty {
            color: #7eacfe;
          }
        }
      }
    }
  }
}
</style>
