<script setup lang="ts">
import type { ChapterSelectData } from '.'

import { useBasicData } from '#/store/basic-data'

defineOptions({ name: 'ChapterSelect' })
const props = withDefaults(
  defineProps<{
    data?: ChapterSelectData
    modelValue?: boolean
  }>(),
  {
    modelValue: false,
    data: {} as any,
  },
)
const emits = defineEmits(['update:modelValue', 'ok'])
const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
    if (!newVal) return

    if (props.data) {
      await bookSelect(props.data.book)
      // 设置选中章节
      chaptersRef.value.setCheckedKeys(props.data.chapterIds)
    } else {
      await bookSelect(null)
    }
  },
})

const { getChapters } = useBasicData()

// const book = ref({} as any)
const bookSelectVisible = ref(false)
function showBookSelect() {
  bookSelectVisible.value = true
}

const bookData = ref({} as any)
const bookTitle = computed(() => bookData.value?.title || '请选择教材')
async function bookSelect(data: any) {
  bookData.value = data
  chapters.value = data?.bookId ? await getChapters(data.bookId) : []
}

const chapters = ref([] as any)
const chaptersRef = ref()

function ok() {
  emits('ok', {
    book: toRaw(bookData.value),
    chapterIds: chaptersRef.value.getCheckedKeys(false, false),
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title: '章节选择',
      width: '86%',
      height: '80%',
      showFooter: true,
      showConfirmButton: true,
      showCancelButton: true,
    }"
    @confirm="ok"
  >
    <div class="chapter-select">
      <div class="section">
        <span class="title">教材</span>
        <div class="item" @click="showBookSelect">
          {{ bookTitle }}
        </div>
      </div>
      <hr />
      <div class="section items-start">
        <span class="title">章节</span>
        <div class="item">
          <el-tree
            :data="chapters"
            ref="chaptersRef"
            show-checkbox
            node-key="id"
            :props="{
              children: 'children',
              label: 'name',
            }"
          />
        </div>
      </div>
    </div>
    <textbook-select
      v-model="bookSelectVisible"
      :data="bookData"
      @ok="bookSelect"
    />
  </mj-modal>
</template>

<style lang="scss" scoped>
.chapter-select {
  padding: 0 24px;

  .section {
    display: flex;
    align-items: center;
    padding: 20px 0;

    &.items-start {
      align-items: flex-start;
    }

    .title {
      margin-right: 20px;
      font-size: 18px;
      font-weight: bold;
    }

    .item {
      flex: 1;
      font-size: 16px;
      cursor: pointer;

      :deep(.el-tree) {
        width: 100%;

        .el-text {
          font-size: 16px;
        }
      }
    }
  }
}
</style>
