<script setup lang="ts">
import hud from '@/utils/hud'
import num from '@/utils/num'
import type { TextBook } from '@/api/subject/subject'
import {
  getRealGrade,
  getSubjectsByStage,
  getStageByGrade,
  stage_options,
  getGradeByClassName,
} from '@/api/subject/config'
import { book_select_practice } from '@/components/book-select'
import { useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import type { TaskFreeLearnConfig } from '@/api/service/task'
import { userStore } from '@/stores'
import { shareStore } from '@/stores/share'

defineOptions({ name: 'TaskFreeLearn' })

const route = useRoute()
const { schoolId } = route.query as any

const { schoolMap } = storeToRefs(userStore())
const { taskSinglePerson, taskSinglePersonBookIds } = storeToRefs(shareStore())
// 阶段
const stageId = ref('' as any)
// 学科列表
const subjectList = ref([] as any[])
const subjectId = ref('' as any)

const amountText = '通关次数'

const data = reactive({ amount: 2 } as TaskFreeLearnConfig)
let config = {} as {
  bookName: string
  gradeId: any
  subjectId: any
  chapters: any
}

// 自由学-教材
const ui = reactive({
  showSelectBook: false,
  book: {} as TextBook,
  showSelectChapters: false,
})
// 自由学-教材-文字
const bookText = computed(() => {
  const name = ui.book.clean?.fullName
  if (!name) return ''
  return name + `(选了${hud.highlight(data.chapterIds?.length, '#3894ff')}个章节)`
})

// 选中了某本教材
function selectFreeLearnBook(book: TextBook) {
  console.log(book)
  ui.book = book
  ui.showSelectBook = false
  ui.showSelectChapters = true
  data.bookId = book.id

  config.bookName = book.clean.fullName!
  config.gradeId = getRealGrade(book.gradeId)
  config.subjectId = book.subjectId
}

// 选中了某章
function selectFreeLearnChapterList(chapters: any[], treeChapters: any[]) {
  if (chapters.length === 0) {
    hud.error('请选择章节')
    return
  }
  ui.showSelectChapters = false
  data.chapterIds = chapters.map(chapter => chapter.id)
  config.chapters = treeChapters
}

watch(
  () => stageId.value,
  () => {
    if (!stageId.value) return
    subjectList.value = getSubjectsByStage(stageId.value) as any[]
    subjectId.value = subjectList.value[0].subjectId
  },
)

watch(
  () => subjectId.value,
  () => {
    ui.book = {} as TextBook
    data.bookId = undefined
    data.chapterIds = []
    config = {} as any
    taskSinglePerson.value.subjectId = subjectId.value
  },
)

defineExpose({
  submit() {
    if (!data.bookId) {
      hud.error('请选择教材')
      return
    }
    if (!data.chapterIds?.length) {
      hud.error('请选择章节')
      return
    }
    if (!num.isPositiveInt(data.amount)) {
      hud.error('请输入正确的【' + amountText + '】（正整数）')
      return
    }
    const rawData = toRaw(data)
    // 处理章节id
    rawData.chapterIds = rawData.chapterIds.join(',')
    return {
      taskFreeLearnConfig: rawData,
      config: JSON.stringify(config),
    }
  },
})

function _getGradeId() {
  let gradeId = ''
  for (const cls of schoolMap.value[schoolId].classList) {
    gradeId = getGradeByClassName(cls.className) as any
    if (gradeId) break
  }
  return gradeId
}

onMounted(async () => {
  const stage = getStageByGrade(_getGradeId())
  if (stage) {
    stageId.value = stage
  }
})
</script>

<template>
  <div class="mj-data-row free-learn">
    <div class="mj-data-item required">
      <span class="mj-data-item-title">教材</span>
      <Select v-model="stageId" width="12.5vh" :select-list="stage_options" />
      <Select
        v-model="subjectId"
        :select-list="subjectList"
        label-key="name"
        value-key="subjectId"
      />
      <span class="book" @click="ui.showSelectChapters = true" v-html="bookText" />
      <mj-button class="button" type="warn" @click="ui.showSelectBook = true">选择教材</mj-button>
    </div>
    <book-select
      v-model="ui.showSelectBook"
      v-model:type="book_select_practice"
      :subjectId="subjectId"
      :stage-id="stageId"
      :show-book-ids="taskSinglePersonBookIds"
      @ok="selectFreeLearnBook"
    />
    <chapter-list
      v-model="ui.showSelectChapters"
      :book="ui.book"
      :mask-close="false"
      :selected-list="data.chapterIds"
      @ok="selectFreeLearnChapterList"
    />
  </div>
  <div class="mj-data-row">
    <div class="mj-data-item required">
      <span class="mj-data-item-title">{{ amountText }}</span>
      <el-input v-model="data.amount" class="amount mj-data-item-input" type="number" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '../../index.scss' as *;
.free-learn {
  .book {
    margin: 0 16px;
  }
}
</style>
