<script setup lang="ts">
import type { VxeFormEventProps } from 'vxe-pc-ui'

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

import {
  forceReplaceLevelWordApi,
  getLevelListApi,
  getStageListApi,
  getWordDetailApi,
} from '#/api'
import MjModal from '#/components/mj/mj-modal/index.vue'
import { mj_form_button_group, mj_form_select } from '#/components/mj/mj-table'
import hud from '#/utils/hud'

defineOptions({ name: 'BindLevel' })
// 属性
const props = defineProps<{
  modelValue: boolean
  word: TextBookWord
}>()
const emit = defineEmits(['update:modelValue'])
const value = computed({
  get: () => props.modelValue,
  set: async (val) => {
    emit('update:modelValue', val)
    if (!val) return
    form.data.wordId = props.word.wordId

    // 加载阶段
    loadStageList()

    // 加载释义
    loadMeaningList()
  },
})

type OptionsType = {
  label: string
  value: any
}[]

const stageList = ref([] as OptionsType)
const levelList = ref([] as OptionsType)
const meaningList = ref([] as OptionsType)
// key: stageId, value: {options, wordsMap}
const stageLevelMap = {} as any

const form = reactive({
  titleWidth: 60,
  titleAlign: 'right',
  data: {
    wordId: '',
    levelNum: '',
    stageId: '',
    meaningId: '',
  },
  rules: {
    levelNum: [
      {
        required: true,
        message: '请选择关卡',
      },
    ],
    stageId: [
      {
        required: true,
        message: '请选择阶段',
      },
    ],
    meaningId: [
      {
        required: true,
        message: '请选择释义',
      },
    ],
  },
  items: [
    {
      field: 'stageId',
      title: '阶段',
      span: 24,
      itemRender: {
        name: mj_form_select,
        options: computed(() => stageList.value),
      },
    },
    {
      field: 'levelId',
      title: '关卡',
      span: 24,
      itemRender: {
        name: mj_form_select,
        options: computed(() => levelList.value),
      },
    },
    {
      field: 'meaningId',
      title: '释义',
      span: 24,
      itemRender: {
        name: mj_form_select,
        options: computed(() => meaningList.value),
      },
    },
    {
      align: 'center',
      span: 24,
      itemRender: {
        name: mj_form_button_group,
        options: [
          { type: 'submit', content: '提交', status: 'primary' },
          { type: 'reset', content: '重置' },
        ],
      },
    },
  ],
} as MjFormProps)

const formEvents = {
  submit() {
    hud.load({
      task: async () => {
        await forceReplaceLevelWordApi({
          levelId: form.data.levelId,
          targetMeaningId: form.data.meaningId,
        })
      },
      hideSuccess: false,
      success: async () => {
        emit('update:modelValue', false)

        // 清理数据，以便重新加载
        stageLevelMap[form.data.stageId] = undefined
        loadLevelList(form.data.stageId).then(() => {
          // 更新
          showWordsCounter.value = showWordsCounter.value + 1
        })
      },
      option: `【${props.word.wordSpell}】加入关卡`,
    })
  },
} as VxeFormEventProps

watch(
  () => form.data.stageId,
  (stageId) => loadLevelList(stageId),
)

const showWordsCounter = ref(1)
const showWords = computed(() => {
  // 用来配合刷新属性
  if (!showWordsCounter.value) return
  if (!form.data.stageId || !form.data.levelId) return []
  const wordsMap = stageLevelMap[form.data.stageId]?.wordsMap
  if (!wordsMap) return []
  return wordsMap[form.data.levelId]
})

// 加载阶段
async function loadStageList() {
  if (stageList.value.length > 0) return
  const data = await getStageListApi()
  const options = data.rows.map((item: any) => ({
    label: item.name,
    value: item.id,
  })) as any
  stageList.value = options
  form.data.stageId = options[options.length - 1].value
}

// 加载关卡
async function loadLevelList(stageId: any) {
  let levelData = stageLevelMap[stageId]
  if (!levelData) {
    const res = await getLevelListApi({
      stageId,
      size: 1000,
      current: 1,
    })
    const rows = res.rows.filter((item: any) => item.wordList?.length < 4)
    levelData = {
      // 下拉框
      options: rows.map((item: any) => ({
        label: item.levelNum,
        value: item.id,
      })),
      // 关卡id  - 单词列表
      wordsMap: rows?.reduce((map: any, item: any) => {
        map[item.id] = item.wordList
        return map
      }, {}),
      // 关卡id - 关卡编号
      // numMap: rows.reduce((map: any, item: any) => {
      //   map[item.id] = item.levelNum
      //   return map
      // }, {}),
    }
    stageLevelMap[stageId] = levelData
    form.data.levelId = levelData.options[0].value
  }
  levelList.value = levelData.options

  if (!form.data.levelId) {
    form.data.levelId = levelData.options[0].value
  }
}

// 加载释义
async function loadMeaningList() {
  form.data.meaningId = ''
  const data = (await getWordDetailApi(props.word.wordId)) as any
  const meanings = data.meaningList.map((item: any) => ({
    label: `[${item.typeAbbr}]${item.simpleDesc}`,
    value: item.id,
  }))
  meaningList.value = meanings

  // 选中：跟外面单词释义一致的
  for (const meaning of meanings) {
    if (meaning.label === props.word.wordDesc) {
      form.data.meaningId = meaning.value
      break
    }
  }

  // 没有选中，默认选中第一个
  if (!form.data.meaningId) {
    form.data.meaningId = meanings[0].value
  }
}
</script>

<template>
  <div class="bind-level">
    <MjModal
      v-model="value"
      :options="{
        title: '绑定关卡',
      }"
    >
      <div class="spell">{{ word.wordSpell }}</div>
      <div class="meanings">
        <div v-for="item in showWords" :key="item.id" class="meaning">
          <span>{{ item.spell }}</span>
          <span>{{ item.meaningVo?.simpleDesc }}</span>
        </div>
      </div>
      <VxeForm v-bind="form" v-on="formEvents" />
    </MjModal>
  </div>
</template>

<style lang="scss" scoped>
.bind-level {
  .spell {
    margin-bottom: 20px;
    font-size: 24px;
    text-align: center;
  }

  .meanings {
    .meaning {
      display: flex;
      column-gap: 10px;
      justify-content: center;

      span {
        flex: 1;
      }
    }
  }
}
</style>
