import {
  taskService,
  type TaskFreeLearnConfig,
  type TaskSentenceConfig,
  type TaskWordQuestConfig,
  type TaskWordTableConfig,
} from '@/api/service/task'
import { topic_free_learn } from '@/page/student-mgr/set-task'
import { defineStore, storeToRefs } from 'pinia'
import { userStore } from './user'

interface Reward {
  rewardId: any
  rewardType: string
  rewardCode: any
  rewardCount: number
  propertyVo: any
  clothingVo: any
  personalityVo: any
  userRewardMappingVo: any
  showUser: any
  userHaveCount: any
}

interface Task {
  taskId: string
  taskTitle: any
  taskType: string
  taskCategory: string
  name: string
  description: any
  sort: any
  status: number
  needProportion: number
  proportionSum: number
  calculateProportionSum: number
  completeProportionCount: number
  needRemoveRepetition: any
  repetitionKeySet: any
  display: boolean
  rewardList: Reward[]
  dynamicCount: any
  taskExtraRewardList: any[]
  taskFreeLearnConfig: TaskFreeLearnConfig
  taskWordMasteryConfig: TaskWordTableConfig
  taskWordQuestConfig: TaskWordQuestConfig
  taskSentenceConfig: TaskSentenceConfig
  taskWordReviewConfig: TaskWordTableConfig
  topicTypeCode: string
  priority: number
  endTime: string
  config: string
  punish: any
  // 必须要先完成
  first: any
}

export const useLeadTaskStore = defineStore('lead-task', () => {
  const taskList = ref([] as Task[])
  const chapterIds = ref({} as any)
  const { userInfo } = storeToRefs(userStore())
  watch(
    () => taskList.value,
    list => {
      if (!list?.length) {
        chapterIds.value = {}
        return
      }
      const map = {} as any
      for (const item of list) {
        if (item.taskCategory !== topic_free_learn) {
          continue
        }
        const ids = item.taskFreeLearnConfig.chapterIds.split(',')
        for (const id of ids) {
          map[id] = item.taskFreeLearnConfig
        }
      }
      chapterIds.value = map
    },
  )

  async function updateTaskList(force = true) {
    if (!userInfo.value.isTaskStudent) return
    if (force || !taskList.value.length) {
      taskList.value = (await taskService.getProcessingTasks()).taskList
    }
  }

  function $reset() {
    taskList.value = []
    chapterIds.value = {}
  }
  return { taskList, chapterIds, updateTaskList, $reset }
})
