<script setup lang="ts">
import { useUserStore } from '@vben/stores'

import { difficulty_options } from '#/api/service/question-bank/question'
import { getStageByGrade, provinces, useBasicData } from '#/store/basic-data'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

import { year_options } from '../../hooks'
import { useChapter } from '../../hooks/chapter'
import { useFillType } from '../../hooks/fill-type'
import { useKnowledge } from '../../hooks/knowledge'
import { useOptionType } from '../../hooks/option-type'
import { useOtherType } from '../../hooks/other-type'

defineOptions({ name: 'BasicData' })

// 表单数据
const { formData, editQuestion, isOptionType, isFillType } = inject(
  'sharedData',
) as any

// 一些用户数据
const { userInfo } = storeToRefs(useUserStore())
const bookOptions = userInfo.value.personConfig?.books
const bookMap = obj.list2map(bookOptions, 'id')
const channelTypeOptions = ref([] as any[])

// 章节
const {
  chapterRef,
  chapterSearchText,
  initChapterData,
  chapters,
  chapterFilter,
  defaultExpandedChapters,
} = useChapter()

// 知识点
const {
  knowledgeRef,
  knowledgeSearchText,
  knowledgeList,
  initKnowledgeData,
  defaultExpandedKnowledge,
} = useKnowledge()

// 接口
const { getChapters, getKnowledgeList, getChannelTypeOptions, channelTypeMap } =
  useBasicData()

// 单选题
const optionType = useOptionType()
// 填空题
const fillType = useFillType()
// 其他题
const otherType = useOtherType()

// 书本变化了
const bookChange = async (bookId: any) => {
  chapters.value = await getChapters(bookId)
  const book = bookMap[bookId]
  if (!book) return

  // 阶段id
  const stageId = getStageByGrade(book.gradeId)

  // 题型
  channelTypeOptions.value = await getChannelTypeOptions(
    stageId,
    book.subjectId,
  )

  // 知识点
  knowledgeList.value = await getKnowledgeList(stageId, book.subjectId)
}

// 题型变化处理
const onTypeChange = () => {
  if (isOptionType.value) {
    optionType.onTypeChange()
  } else if (isFillType.value) {
    fillType.onTypeChange()
  } else {
    otherType.onTypeChange()
  }
}

watch(
  () => editQuestion.value,
  async () => {
    // 初始化
    if (editQuestion.value?.id) {
      // 获取题目类型
      channelTypeOptions.value = await getChannelTypeOptions(
        editQuestion.value.stagePid,
        editQuestion.value.subjectId,
      )
      // 题型
      formData.value.channelTypeId = editQuestion.value.channelTypeId
      // 难度
      formData.value.difficulty = editQuestion.value.difficulty
      // 地区
      formData.value.province = editQuestion.value.province
      // 年份
      formData.value.year = editQuestion.value.year
      // 来源
      if (editQuestion.value.sources) {
        formData.value.sources = editQuestion.value.sources?.split(',') || []
      }
      // 教材
      formData.value.textbookId = editQuestion.value.textbookId

      // 触发书本改变
      await bookChange(editQuestion.value.textbookId)

      // 初始化章节数据
      await initChapterData()

      // 设置知识点选中
      await initKnowledgeData()
    } else {
      formData.value.channelTypeId = ''
      formData.value.difficulty = '1'
      formData.value.province = 0
      formData.value.year = '2025'
      formData.value.sources = []
      formData.value.textbookId = undefined
      formData.value.chapterIds = []
      formData.value.knowledgeIds = []
    }

    // 触发题型改变
    onTypeChange()
  },
)

defineExpose({
  submit() {
    const chapterIds = chapterRef.value.getCheckedKeys(false, false)
    if (chapterIds.length === 0) {
      hud.error('请选择章节')
      return
    }

    let data = {} as any
    // 根据不同题型，返回不同的数据（比如答案之类的）
    if (isOptionType.value) {
      data = optionType.submit()
    } else if (isFillType.value) {
      data = fillType.submit()
    } else {
      data = otherType.submit()
    }
    if (!data) {
      return
    }

    // 知识点
    const knowledgeIds = knowledgeRef.value.getCheckedKeys(false, false)
    const textbookId = formData.value.textbookId
    return {
      ...data,
      // 教材
      textbookId,
      // 题型
      channelTypeId: formData.value.channelTypeId,
      channelTypeBaseId: channelTypeMap[formData.value.channelTypeId].baseId,
      // 难度
      difficulty: formData.value.difficulty,
      // 地区
      province: formData.value.province,
      // 年份
      year: formData.value.year,
      // 来源
      sources: formData.value.sources.join(','),
      // 章节
      chapterIds,
      // 知识点
      knowledgeIds,
      // 配置
      configJson: JSON.stringify({
        textbookTitle: bookMap[textbookId].title,
      }),
    }
  },
})
</script>

<template>
  <el-card shadow="never" class="form-section basic-data">
    <template #header>
      <span class="section-title">基本信息</span>
    </template>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="教材" prop="textbookId">
          <el-select
            v-model="formData.textbookId"
            placeholder="请选择教材"
            @change="bookChange"
          >
            <el-option
              v-for="item in bookOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="formData.difficulty" placeholder="请选择难度">
            <el-option
              v-for="item in difficulty_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="地区" prop="province">
          <el-select v-model="formData.province" placeholder="请选择地区">
            <el-option
              v-for="item in provinces"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="年份" prop="year">
          <el-select v-model="formData.year" placeholder="请选择年份">
            <el-option
              v-for="item in year_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="题型" prop="channelTypeId" required>
          <el-select
            filterable
            v-model="formData.channelTypeId"
            placeholder="请选择题型"
            @change="onTypeChange"
          >
            <el-option
              v-for="item in channelTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="18">
        <el-form-item label="来源" prop="sources">
          <el-input-tag
            v-model="formData.sources"
            placeholder="多个来源之间用回车键隔开"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="章节" prop="chapterIds">
          <el-input v-model="chapterSearchText" placeholder="搜索章节" />
          <el-tree
            class="tree"
            check-strictly
            v-model="formData.chapterIds"
            :data="chapters"
            :default-expanded-keys="defaultExpandedChapters"
            ref="chapterRef"
            show-checkbox
            node-key="id"
            :props="{
              children: 'children',
              label: 'name',
            }"
            :filter-node-method="chapterFilter"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="知识点" prop="knowledgeIds">
          <el-input v-model="knowledgeSearchText" placeholder="搜索知识点" />
          <el-tree
            class="tree"
            :data="knowledgeList"
            ref="knowledgeRef"
            :default-expanded-keys="defaultExpandedKnowledge"
            check-strictly
            show-checkbox
            node-key="id"
            :props="{
              children: 'children',
              label: 'name',
            }"
            :filter-node-method="chapterFilter"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-card>
</template>

<style lang="scss" scoped></style>
