<script setup lang="ts">
import { computed, ref } from 'vue'
import obj from '@/utils/obj'
import { useWordBookSelect } from './store'

const props = defineProps<{
  modelValue: any
  onlyStage?: any
}>()

const emit = defineEmits(['update:modelValue'])

defineOptions({ name: 'WordBookSelect' })

const book = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

const store = useWordBookSelect()
const { stageOptions, stageMap, getVersionOptions, getTextbookOptions } = store

// 阶段
book.value.stageId = stageOptions[0].value

// 版本
book.value.versionId = ''
const versionOptions = ref([] as any[])
let versionMap = {} as any

// 年级
const bookOptions = ref([] as any[])
let bookMap = {} as any

// 监听
watch(
  () => book.value.stageId,
  async () => {
    if (!book.value.stageId) return
    // 加载教材版本
    const data = await getVersionOptions(book.value.stageId)
    versionOptions.value = data
    versionMap = obj.options2map(data)
    book.value.versionId = data[0].value
  },
  {
    immediate: true,
    deep: true,
  },
)

watch(
  () => book.value.versionId,
  async () => {
    if (!book.value.versionId) return

    // 加载教材版本
    const data = await getTextbookOptions(book.value.versionId)
    bookOptions.value = data
    bookMap = obj.options2map(data)
    book.value.bookId = data[0].value
  },
  {
    immediate: true,
    deep: true,
  },
)

watch(
  () => book.value.bookId,
  async () => {
    if (!book.value.bookId) return

    // 把name补上
    book.value.stageName = stageMap[book.value.stageId]
    book.value.versionName = versionMap[book.value.versionId]
    book.value.bookName = bookMap[book.value.bookId]
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <div class="word-book-select">
    <Select v-model="book.stageId" width="12vh" class="stage" :select-list="stageOptions" />
    <Select
      v-if="!onlyStage"
      v-model="book.versionId"
      width="22vh"
      class="version"
      :select-list="versionOptions"
    />
    <Select
      v-if="!onlyStage"
      v-model="book.bookId"
      width="20vh"
      class="book"
      :select-list="bookOptions"
    />
  </div>
</template>

<style lang="scss" scoped>
.word-book-select {
  display: flex;
  column-gap: 2vh;
}
</style>
