<script setup lang="ts" name="word-mgr">
import type { VxeGridPropTypes } from 'vxe-table'

import type { TextBookWord } from '#/api/modules/word-book'
import type {
  MjEditFormProps,
  MjFormProps,
  MjGridProps,
} from '#/components/mj/mj-table'

import { getWordBySpellApi, getWordDetailApi } from '#/api'
import {
  fixTextBookWordApi,
  syncWordByTextBookApi,
} from '#/api/modules/word-book'
import { get } from '#/api/http'
import { levelService } from '#/api/service/english/level'
import { wordBookService } from '#/api/service/word-book/word-book-word'
import MjTable, {
  mj_form_input,
  mj_form_select,
} from '#/components/mj/mj-table'
import hud from '#/utils/hud'

import AddWord from './add-word.vue'
import BindLevel from './bind-level.vue'

// 阶段
const stagesData = ref<any[]>([])
// 版本
const versionsData = ref<any[]>([])
// 书本
const booksData = ref<any[]>([])
// 选中的单词
const selectedWord = ref({} as TextBookWord)
// 显示添加单词的对话框
const showAddWord = ref(false)
// 显示绑定关卡的对话框
const showBindLevel = ref(false)

// 表单
const editForm = {
  form: {
    rules: {
      wordSpell: [
        {
          required: true,
          message: '请输入单词拼写',
        },
      ],
    },
    items: [
      {
        field: 'wordSpell',
        title: '拼写',
        span: 24,
        itemRender: {
          name: mj_form_input,
        },
      },
    ],
  },
  updateFields: ['id', 'wordSpell'],
} as MjEditFormProps

const searchForm = {
  items: [
    {
      field: 'bind',
      title: '已绑定',
      span: 4,
      itemRender: {
        name: mj_form_select,
        props: {
          clearable: true,
        },
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '0',
          },
        ],
      },
    },
    {
      field: 'stage',
      title: '阶段',
      span: 4,
      itemRender: {
        name: mj_form_select,
        props: {
          clearable: true,
        },
        options: computed(() => stagesData.value),
        events: {
          change: async ({ data }) => {
            loadVersionsByStage(data.stage)
          },
        },
      },
    },
    {
      field: 'version',
      title: '版本',
      span: 4,
      itemRender: {
        name: mj_form_select,
        props: {
          clearable: true,
        },
        options: computed(() => versionsData.value),
        events: {
          change: async ({ data }) => {
            loadBooksByVersion(data.version)
          },
        },
      },
    },
    {
      field: 'textbookId',
      title: '书本',
      span: 4,
      itemRender: {
        name: mj_form_select,
        props: {
          clearable: true,
        },
        options: computed(() => booksData.value),
      },
    },
  ],
} as MjFormProps

// 表格列
const column_spell = 'wordSpell'
const column_level = 'level'
const columns = [
  { type: 'seq' },
  {
    field: column_spell,
    title: '单词',
    slots: {
      default: column_spell,
    },
  },
  { field: 'wordDesc', title: '中文' },
  {
    title: '教材',
    formatter(params) {
      const word = params.row as TextBookWord
      return `${word.stageName}·${word.versionName}·${word.textbookName}`
    },
  },
  {
    field: column_level,
    title: '关卡',
    slots: {
      default: column_level,
    },
  },
] as VxeGridPropTypes.Columns

// 表格
const gridRef = ref()
const grid = {
  columns,
  // 请求前的参数处理
  beforeLoadData(params: any) {
    for (const key in params) {
      if (!params[key]) {
        delete params[key]
      }
    }
    return params
  },
} as MjGridProps

function fix() {
  const textbookId = gridRef.value?.getSearchFormData()?.textbookId
  const byTextbook = Boolean(textbookId)
  hud.confirm({
    content: byTextbook
      ? '确定要修复当前选中教材的单词书数据吗？'
      : '未选择教材，将修复全部单词书数据，确定继续吗？',
    onConfirm: async () => {
      hud.toastLoad({
        task: async () => {
          await fixTextBookWordApi(byTextbook ? textbookId : undefined)
          if (byTextbook) {
            gridRef.value?.reload()
          }
        },
        option: '修复',
        hideSuccess: false,
      })
    },
  })
}

function syncByTextbook() {
  const textbookId = gridRef.value?.getSearchFormData()?.textbookId
  if (!textbookId) {
    hud.error('请先选择教材')
    return
  }
  hud.confirmLoad('确定要同步当前教材的单词数据吗？', {
    task: async () => {
      await syncWordByTextBookApi(textbookId)
      gridRef.value?.reload()
    },
    option: '同步',
    hideSuccess: false,
  })
}

// 点击拼写
const meanings = ref([] as any)
async function clickCellSpell(row: any) {
  hud.load({
    task: async () => {
      // 根据拼写获取单词（因为row.wordId可能不对）
      const word = await getWordBySpellApi(row.wordSpell)
      const wordId = word?.id

      if (wordId) {
        const data = await getWordDetailApi(wordId)
        // 获取单词的释义
        meanings.value = data.meaningList.map((item: any) => ({
          label: `[${item.typeAbbr}]${item.simpleDesc}`,
          value: item.id,
        }))
      } else {
        // 如果单词不存在
        meanings.value = []
      }
      // 重新设置单词的id
      selectedWord.value = {
        ...row,
        wordId,
      }
      // 显示对话框
      showAddWord.value = true
    },
    option: '获取单词',
    hideSuccess: false,
  })
}

// 点击关卡
async function clickCellLevel(row: TextBookWord) {
  // row.wordId可能不对
  hud.load({
    task: async () => {
      const word = await getWordBySpellApi(row.wordSpell)
      selectedWord.value = {
        ...row,
        wordId: word.id,
      }
      showBindLevel.value = true
    },
    option: '获取单词',
    hideSuccess: false,
  })
}

function extractList(res: any) {
  return Array.isArray(res) ? res : res?.rows || []
}

// 加载阶段列表
async function loadStages() {
  const res = await get<any>('/xkw/stage/list', { size: -1, status: 0 })
  stagesData.value = extractList(res).map((item: any) => ({
    label: item.name,
    value: item.id,
  }))
}

// 根据阶段获取课程（取英语），再加载版本
async function loadVersionsByStage(stageId: any) {
  versionsData.value = []
  booksData.value = []
  if (!stageId) return
  const courseRes = await get<any>('/xkw/course/list', {
    size: -1,
    status: 0,
    stageId,
  })
  const courses = extractList(courseRes)
  const englishCourse = courses.find(
    (c: any) => c.shortName === '英语' || c.name === '英语',
  )
  if (!englishCourse) return
  const versionRes = await get<any>('/xkw/textbookVersion/list', {
    size: -1,
    status: 0,
    courseId: englishCourse.id,
  })
  versionsData.value = extractList(versionRes).map((item: any) => ({
    label: item.name,
    value: item.id,
  }))
}

// 根据教材版本查找具体的书本
async function loadBooksByVersion(versionId: any) {
  booksData.value = []
  if (!versionId) return
  const res = await get<any>('/xkw/textbook/list', {
    size: -1,
    status: 0,
    versionId,
  })
  booksData.value = extractList(res).map((item: any) => ({
    label: item.volume,
    value: item.id,
  }))
}

onMounted(() => {
  loadStages()
})

// 解绑关卡
function unbindLevel(row: any) {
  hud.confirmLoad(`${row.wordSpell}[${row.wordDesc}]确定要解绑关卡吗？`, {
    task: async () => {
      await levelService.removeLevelWord(row.levelWordId)
      gridRef.value.reload()
    },
    option: '解绑',
    hideSuccess: false,
  })
}

watch(
  () => versionsData.value,
  () => {
    gridRef.value.updateSearchFormData({
      version: '',
      textbookId: '',
    })
  },
)

watch(
  () => booksData.value,
  () => {
    gridRef.value.updateSearchFormData({
      textbookId: '',
    })
  },
)
</script>

<template>
  <div class="word-mgr g-container">
    <MjTable
      ref="gridRef"
      :edit-form="editForm"
      :hide-add="true"
      :grid="grid"
      :search-form="searchForm"
      :service="wordBookService"
    >
      <template #wordSpell="{ row }">
        <span
          v-if="row.wordId && row.meaningId"
          style="cursor: pointer"
          @click="clickCellSpell(row)"
          >{{ row.wordSpell }}
        </span>
        <span
          v-else
          style="color: red; cursor: pointer"
          @click="clickCellSpell(row)"
          >{{ row.wordSpell }}
        </span>
      </template>
      <template #level="{ row }">
        <span
          v-if="row.levelName"
          style="cursor: pointer"
          @click="unbindLevel(row)"
        >
          {{ `${row.levelName}·第${row.levelNum}关` }}
        </span>
        <span
          v-else
          style="color: red; cursor: pointer"
          @click="clickCellLevel(row)"
          >未绑定
        </span>
      </template>
      <template #toolbarButtonsExtra>
        <el-button type="warning" @click="syncByTextbook">按教材同步</el-button>
        <el-button type="primary" @click="fix">同步修复</el-button>
      </template>
    </MjTable>
    <AddWord v-model="showAddWord" :word="selectedWord" :meanings="meanings" />
    <BindLevel v-model="showBindLevel" :word="selectedWord" />
  </div>
</template>

<style lang="scss" scoped>
.word-mgr {
  height: 100% !important;
}
</style>
