import { defineStore } from 'pinia'
import type { TaskState } from '/#/task'
import { getApprovalList } from '@/api/task/task'
import { store } from '@/store'

export const useTaskStore = defineStore({
  id: 'task-store',
  state: (): TaskState => ({
    currentIndex: -1,
    activeId: '',
    approvalList: [],
    packageid: '',
    immersion: false,
  }),
  getters: {
    getActiveId: (state: TaskState) => state.activeId,
    getPackageid: (state: TaskState) => state.packageid,
    getCurrentIndex: (state: TaskState) => state.currentIndex,
    getApprovalList: (state: TaskState) => state.approvalList,
  },
  actions: {
    setApprovalList(list: any[]) {
      this.approvalList = list
    },
    setActive(index: number, taskId?: string) {
      this.currentIndex = index
      const task = this.approvalList[index]
      this.activeId = taskId || task?.id
      this.packageid = task.packageid
    },
    forward() {
      const len = this.approvalList.length

      if (this.currentIndex === len - 1)
        return

      this.setActive(++this.currentIndex)
    },
    back() {
      if (this.currentIndex === 0)
        return

      this.setActive(--this.currentIndex)
    },
    async fetchApprovalList(pagination) {
      const res = await getApprovalList(pagination)
      if (res.data.length > 0) {
        this.approvalList.push(...res.data)
        if (!this.activeId)
          this.setActive(0)
      }

      return res
    },
    updateImmersion() {
      this.immersion = !this.immersion
    },
    reset() {
      this.currentIndex = -1
      this.activeId = ''
      this.packageid = ''
      this.approvalList = []
    },
  },
})

export function useTask() {
  return useTaskStore(store)
}
