<script setup lang="ts">
import hud from '@/utils/hud'
import num from '@/utils/num'
import { topic_word_review } from '../../..'
import { Minus, Plus } from '@element-plus/icons-vue'
import type { TaskWordTableConfig } from '@/api/service/task'
import wordTableApi from '@/api/subject/wordTable'

const props = defineProps<{
  type: any
}>()
defineOptions({ name: 'TaskWordTable' })
const amountText = '单词数量'

const data = reactive({} as TaskWordTableConfig)

// 是否显示教材
const book_mode_none = 1
const book_mode_stage = 2
const book_mode_book = 3
const bookMode = ref(book_mode_none)

type Config = {
  stageId: any // 阶段
  stageName: string
  versionId: any // 版本
  versionName: string
  bookName: string
  bookId: any // 教材
}
const config = reactive({} as Config)

defineExpose({
  submit() {
    if (!num.isPositiveInt(data.amount)) {
      hud.error('请输入正确的【' + amountText + '】（正整数）')
      return
    }
    let rawConfig = toRaw(config) as Config
    const rawData = {
      amount: data.amount,
    } as TaskWordTableConfig
    if (bookMode.value === book_mode_stage) {
      // 没有选择教材
      rawConfig = {
        stageId: rawConfig.stageId,
        stageName: rawConfig.stageName,
      } as any
      rawData.stageId = rawConfig?.stageId
    } else if (bookMode.value === book_mode_none) {
      rawConfig = undefined as any
    } else {
      rawData.bookId = rawConfig?.bookId
    }

    const key = props.type === topic_word_review ? 'taskWordReviewConfig' : 'taskWordMasteryConfig'
    const res = {
      [key]: rawData,
    } as any
    if (rawConfig) {
      res.config = JSON.stringify(rawConfig)
    }
    return res
  },
})
</script>

<template>
  <div class="task-word-table mj-data-row" :class="{ 'auto-items': bookMode === book_mode_book }">
    <div class="mj-data-item">
      <span class="mj-data-item-title">教材</span>
      <div class="book-box">
        <word-book-select
          v-if="bookMode !== book_mode_none"
          v-model="config"
          :only-stage="bookMode === book_mode_stage"
        />
        <el-button
          v-if="bookMode !== book_mode_book"
          :icon="Plus"
          type="primary"
          circle
          @click="bookMode += 1"
        />
        <el-button
          v-if="bookMode !== book_mode_none"
          :icon="Minus"
          type="danger"
          circle
          @click="bookMode -= 1"
        />
      </div>
    </div>

    <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 *;
.task-word-table {
  .book-box {
    display: flex;
    align-items: center;
    gap: 20px;
  }
}
</style>
