<script setup lang="ts">
import type { Option } from '@/api/global'
import { userStore } from '@/stores'

const props = defineProps<{
  modelValue: {
    schoolId: any
    school: any
    classId: any
    class: any
  }
  height?: any
  hideClass?: boolean
  showAllClasses?: boolean
}>()

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

defineOptions({ name: 'SchoolClassSelect' })

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

const { schoolMap, schoolOptions, classOptionsMap, classesMap } = storeToRefs(userStore())
const classOptions = ref<Option[]>([])

watch(
  () => data.value.schoolId,
  async schoolId => {
    if (!schoolId || props.hideClass) return
    data.value.school = schoolMap.value[schoolId]
    const options = props.showAllClasses ? [{ value: '', label: '全校' }] : []
    classOptions.value = [...options, ...classOptionsMap.value[schoolId]]
    // 默认选中第1个
    if (classOptions.value.length) {
      data.value.classId = classOptions.value[0].value
    }
  },
  { immediate: true },
)

watch(
  () => data.value.classId,
  async classId => {
    if (!classId) return
    data.value.class = classesMap.value[classId]
  },
  { immediate: true },
)
</script>

<template>
  <div class="school-class-select">
    <Select v-model="data.schoolId" width="320" :height="height" :select-list="schoolOptions" />
    <Select
      v-if="!hideClass"
      v-model="data.classId"
      width="230"
      :height="height"
      :select-list="classOptions"
    />
  </div>
</template>

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