/* eslint-disable unicorn/prefer-query-selector */
/* eslint-disable unicorn/prefer-ternary */
/* eslint-disable unicorn/no-negated-condition */
import { paperService } from '#/api/service/question-bank/paper'
import { paperTitleService } from '#/api/service/question-bank/paper-title'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

const status_published = 1
const status_disabled = 0
export const status_options = [
  {
    label: '发布',
    value: status_published,
  },
  {
    label: '禁用',
    value: status_disabled,
  },
]
export const status_map = obj.options2map(status_options)

export const pdf_upload_status_options = [
  { label: '未上传文件', value: 0 },
  { label: '文件解析中', value: 1 },
  { label: '解析完成', value: 2 },
  { label: '解析错误', value: 3 },
]
export const pdf_upload_status_map = obj.options2map(pdf_upload_status_options)
export const pdf_upload_status_tag_type: Record<number, string> = {
  0: 'info',
  1: 'warning',
  2: 'success',
  3: 'danger',
}

const type_unit_test = 1
const type_week_test = 2
const type_month_test = 3
// 随堂联系
const type_class_test = 4
// preview
const type_preview = 5
const type_hw = 6
const type_semester_hw = 7
const type_semester_test = 8
const type_final_test = 9
export const type_options = [
  {
    label: '单元测试',
    value: type_unit_test,
  },
  {
    label: '周测',
    value: type_week_test,
  },
  {
    label: '月考',
    value: type_month_test,
  },
  {
    label: '随堂练习',
    value: type_class_test,
  },
  {
    label: '课前预习',
    value: type_preview,
  },
  {
    label: '寒假作业',
    value: type_hw,
  },
  {
    label: '暑假作业',
    value: type_semester_hw,
  },
  {
    label: '期中测试',
    value: type_semester_test,
  },
  {
    label: '期末测试',
    value: type_final_test,
  },
]
export const type_map = obj.options2map(type_options)
export type PaperQuestion = {
  addrId: any
  analyzeData: any
  answer: string
  baseId: any
  delFlag: number
  difficulty: number
  difficultyLevel: string
  discuss: any
  examType: number
  explanation: string
  groupCount: number
  id: string
  // 额外增加是否在组的头或尾部
  isFirst: boolean
  isLast: boolean
  linkPaper: number
  method: any
  optionList: any[]
  originId: string
  pictureUrl: any
  pid: any
  provinces: string
  schoolId: string
  // 分数
  score: any
  // 评分标准
  point?: string
  seq: number
  simpTitle: any
  sourceId: any
  sourceName: string
  stageName: string
  stagePid: string
  status: number
  stem: string
  subjectId: string
  subjectName: string
  textBookId: string
  textBookName: string
  title: string
  titleAnalyze: string
  titleAnalyzeJson: any
  titleAnalyzePicture: any
  titleChannelType: string
  titleChannelTypeName: string
  titleData: any
  titleSourceIds: any
  titleType: number
  titleTypeBaseId: string
  voiceUrl: any
  year: number
  years: string
}

export interface PaperQuestionGroup {
  id: any
  isFirst: boolean
  isLast: boolean
  isNullType: boolean
  name: string
  namePrefix: string
  questions: PaperQuestion[]
  score: any
}

export interface PaperTitle {
  /** 难易程度 11容易 12较易 13普通 14较难 15困难 */
  difficulty: number
  /** 主键 */
  id: string
  /** 试卷id */
  paperId: string
  /** 学校id */
  schoolId: string
  /** 题目分数 */
  score: number
  /** 评分标准 */
  point?: string
  /** 排序由小到大 */
  sort: number
  /** 教材ID */
  textBookId: string
  /** 学校教材题目 */
  title: PaperQuestion
  /** 题目类型，关联 t_subject_stage_channel_type */
  titleChannelType: string
  /** 题目类型，关联 t_subject_stage_channel_type */
  titleChannelTypeName: string
  /** 题目id */
  titleId: string
  /** 学科网题目 */
  xkwTitle: any
}

export interface SchoolPaper {
  channelTypeVoList: any[]
  courseId: any
  description: any
  difficulty: any
  durationMinutes: number
  gradeId: string
  id: string
  name: string
  schoolId: string
  schoolPaperTitleVoList: PaperTitle[]
  // 额外增加
  score: any
  status: number
  subjectId: any
  textBookId: string
  textBookName: string
  totalScore: number
  type: number
}

const num_map = {
  1: '一',
  2: '二',
  3: '三',
  4: '四',
  5: '五',
  6: '六',
  7: '七',
  8: '八',
  9: '九',
  10: '十',
  11: '十一',
  12: '十二',
  13: '十三',
  14: '十四',
  15: '十五',
  16: '十六',
  17: '十七',
  18: '十八',
  19: '十九',
  20: '二十',
} as any

export const usePaperStore = defineStore('paper', () => {
  const paper = ref({} as SchoolPaper)
  const questions = ref([] as PaperQuestion[])
  const changed = ref(false)
  const defaultChapterId = ref<any>(null)
  const dataLoaded = ref(false)

  const detailRef = ref<HTMLElement | null>(null)

  const questionGroups = computed(() => {
    if (!questions.value?.length) return []
    // 按照question.titleTypeBaseId分组
    const groupMap = {} as any
    const groups = [] as PaperQuestionGroup[]
    for (const question of questions.value) {
      let group = groupMap[question.titleTypeBaseId]
      if (group) {
        group.questions.push(question)
      } else {
        group = {
          id: question.titleTypeBaseId,
          name: question.titleChannelTypeName,
          questions: [question],
          score: 0,
        }
        groups.push(group)
        groupMap[question.titleTypeBaseId] = group
      }
    }
    paper.value.score = 0
    // 编号
    let seq = 1
    for (const [i, group] of groups.entries()) {
      const prefix = `${num_map[i + 1]}、`
      group.namePrefix = prefix
      group.isNullType =
        !group.name || group.name === 'null' || group.name === 'undefined'
      group.name = `${prefix}${group.isNullType ? '' : group.name}`
      group.score = 0
      for (const question of group.questions) {
        // 重置
        question.isFirst = false
        question.isLast = false
        question.seq = seq
        seq += 1
        // 累加分数
        group.score += Number(question.score)
      }
      // 累加总分数
      paper.value.score += Number(group.score)
      // 是否在组的头或尾部
      const first = group.questions[0] as PaperQuestion
      first.isFirst = true
      const last = group.questions[group.questions.length - 1] as PaperQuestion
      last.isLast = true
    }
    // 是否在头或尾部
    const first = groups[0] as PaperQuestionGroup
    first.isFirst = true
    const last = groups[groups.length - 1] as PaperQuestionGroup
    last.isLast = true
    return groups
  })

  // 添加题目
  const addQuestion = (question: PaperQuestion) => {
    // 先从后往前找同类型的
    let index = questions.value.findLastIndex(
      (item) =>
        item.titleTypeBaseId.localeCompare(question.titleTypeBaseId) === 0,
    )
    if (index !== -1) {
      // 插入到同类型的后面
      index = index + 1
    } else {
      // 再从前往后找第一个比question题型大的
      index = questions.value.findIndex(
        (item) =>
          item.titleTypeBaseId.localeCompare(question.titleTypeBaseId) > 0,
      )
    }
    // 要创建一个新对象，避免影响外部的数据
    const newQuestion = {
      ...question,
      score: question.score || '',
      point: question.point || '',
    }
    if (index === -1) {
      questions.value.push(newQuestion)
    } else {
      // 插入到index位置
      questions.value.splice(index, 0, newQuestion)
    }
    changed.value = true
  }

  // 删除题目
  const removeQuestion = (question: PaperQuestion) => {
    questions.value = questions.value.filter((item) => item.id !== question.id)
    changed.value = true
  }

  // 下移题目
  const moveDownQuestion = (question: PaperQuestion) => {
    if (!questions.value?.length) return
    const index = questions.value.findIndex((item) => item.id === question.id)
    if (index === -1) return
    if (index === questions.value.length - 1) return
    const tmp = questions.value[index] as any
    // 已经是组尾
    if (tmp?.isGroupLast) return
    questions.value[index] = questions.value[index + 1] as any
    questions.value[index + 1] = tmp as any
    changed.value = true
    addFlashEffect(getQuestionDom(question.id))
  }

  // 上移题目
  const moveUpQuestion = (question: PaperQuestion) => {
    if (!questions.value?.length) return
    const index = questions.value.findIndex((item) => item.id === question.id)
    if (index === 0) return
    if (index === -1) return
    const tmp = questions.value[index] as any
    // 已经是组头
    if (tmp?.isGroupFirst) return
    questions.value[index] = questions.value[index - 1] as any
    questions.value[index - 1] = tmp as any
    changed.value = true
    addFlashEffect(getQuestionDom(question.id))
  }

  // 删除组
  const removeQuestionGroup = (group: PaperQuestionGroup) => {
    hud.confirm({
      content: `确定删除${hud.highlight(group.name)}整体吗？`,
      onConfirm: () => {
        // 将questions中titleTypeBaseId为group.id的题目删除
        questions.value = questions.value.filter(
          (item) => item.titleTypeBaseId !== group.id,
        )
        changed.value = true
      },
    })
  }

  // 上移组
  const moveUpQuestionGroup = (group: PaperQuestionGroup) => {
    const tempGroups = [...questionGroups.value]
    const index = tempGroups.findIndex((item) => item.id === group.id)
    if (index === 0) return
    if (index === -1) return
    const tmp = tempGroups[index] as any
    tempGroups[index] = tempGroups[index - 1] as any
    tempGroups[index - 1] = tmp as any
    let newList = [] as any
    for (const group of tempGroups) {
      newList = [...newList, ...group.questions]
    }
    questions.value = newList
    changed.value = true
    addFlashEffect(getGroupDom(group.id))
  }

  // 下移组
  const moveDownQuestionGroup = (group: PaperQuestionGroup) => {
    const tempGroups = [...questionGroups.value]
    const index = tempGroups.findIndex((item) => item.id === group.id)
    if (index === tempGroups.length - 1) return
    if (index === -1) return
    const tmp = tempGroups[index] as any
    tempGroups[index] = tempGroups[index + 1] as any
    tempGroups[index + 1] = tmp as any
    let newList = [] as any
    for (const group of tempGroups) {
      newList = [...newList, ...group.questions]
    }
    questions.value = newList
    changed.value = true
    addFlashEffect(getGroupDom(group.id))
  }

  const setGroupAverageScore = (groupId: any, score: any) => {
    for (const question of questions.value) {
      if (question.titleTypeBaseId === groupId) {
        question.score = score
      }
    }
  }

  // 设置试卷
  const setPaper = (val: SchoolPaper) => {
    $reset()

    defaultChapterId.value = (val as any).chapterId || null
    paper.value = val
    hud.load({
      task: async () => {
        const res = await paperService.get(paper.value.id)
        paper.value = res as SchoolPaper
        // 设置questions
        questions.value = paper.value.schoolPaperTitleVoList.map((item) => ({
          ...item.xkwTitle,
          titleTypeBaseId: item.titleChannelType || item.xkwTitle?.typeId,
          titleChannelTypeName:
            item.titleChannelTypeName || item.xkwTitle?.typeName,
          score: item.score || '',
          point: item.point ?? item.xkwTitle?.point ?? '',
        }))
        dataLoaded.value = true
      },
    })
  }

  // 判断题目是否在试卷中
  const isQuestionInPaper = (question: PaperQuestion) => {
    return questions.value.some((item) => item.id === question.id)
  }

  // 滚动
  const scrollToElement = (element: HTMLElement, addParentTop = false) => {
    if (!element || !detailRef.value) {
      return
    }
    // 计算元素在父容器中的相对位置
    let offsetTop = element.offsetTop
    if (addParentTop) {
      offsetTop += element.parentElement?.offsetTop || 0
      offsetTop += element.parentElement?.parentElement?.offsetTop || 0
      offsetTop -= 60
    }
    // 使用平滑滚动动画
    detailRef.value.scrollTo({
      top: offsetTop - 70, // 添加一点偏移量，使元素不会贴在容器顶部
      behavior: 'smooth', // 添加平滑滚动效果
    })
  }

  // 添加闪烁效果
  const addFlashEffect = (element: HTMLElement) => {
    if (!element) {
      return
    }

    // 添加闪烁类
    element.classList.add('highlight-flash')
    // 动画结束后移除类
    setTimeout(() => {
      element.classList.remove('highlight-flash')
    }, 1500) // 与动画时长一致
  }

  const getQuestionDom = (questionId: any) => {
    return document.getElementById(
      `detail-question-${questionId}`,
    ) as HTMLElement
  }

  const getGroupDom = (groupId: any) => {
    return document.getElementById(`detail-group-${groupId}`) as HTMLElement
  }

  // 滚动到指定题目
  const scrollToQuestion = (questionId: any) => {
    const questionElement = getQuestionDom(questionId)
    if (!questionElement) {
      return
    }
    scrollToElement(questionElement, true)
    // 添加闪烁效果
    addFlashEffect(questionElement)
  }

  // 滚动到指定题目组
  const scrollToGroup = (groupId: any) => {
    const groupElement = getGroupDom(groupId)
    if (!groupElement) {
      return
    }
    scrollToElement(groupElement)
    // 添加闪烁效果
    addFlashEffect(groupElement)
  }

  // 保存试卷
  const savePaper = (close: () => void) => {
    if (!paper.value.name) {
      hud.error('请输入试卷名称')
      return
    }
    // 检查是否有题目
    if (!questions.value.length) {
      hud.error('请添加题目')
      return
    }
    // 检查是否设置了分数
    for (let i = 0; i < questions.value.length; i++) {
      const question = questions.value[i] as PaperQuestion
      if (!Number(question.score)) {
        hud.error(`请设置第${i + 1}题的分数`)
        scrollToQuestion(question.id)
        return
      }
    }
    // 保存
    paperTitleService
      .batchAdd({
        paperId: paper.value.id,
        paperName: paper.value.name,
        paperTitleDtoList: questions.value.map((item) => ({
          titleId: item.id,
          score: item.score,
          point: item.point,
        })),
      })
      .then(() => {
        hud.success('保存成功')
        close()
      })
  }

  const updateGroupType = (groupId: any, typeId: string, typeName: string) => {
    for (const question of questions.value) {
      if (question.titleTypeBaseId === groupId) {
        question.titleTypeBaseId = typeId
        question.titleChannelTypeName = typeName
      }
    }
  }

  const $reset = () => {
    paper.value = {} as SchoolPaper
    questions.value = []
    changed.value = false
    detailRef.value = null
    defaultChapterId.value = null
    dataLoaded.value = false
  }

  const isChanged = computed(() => changed.value)
  return {
    $reset,
    detailRef,
    paper,
    questions,
    isChanged,
    dataLoaded,
    defaultChapterId,
    questionGroups,
    savePaper,
    setGroupAverageScore,
    scrollToQuestion,
    scrollToGroup,
    isQuestionInPaper,
    setPaper,
    addQuestion,
    removeQuestion,
    moveUpQuestion,
    moveDownQuestion,
    removeQuestionGroup,
    moveUpQuestionGroup,
    moveDownQuestionGroup,
    updateGroupType,
  }
})
