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

export const useTaskStore = defineStore({
  id: 'task-store',
  state: (): TaskState => ({
    currentIndex: -1,
    activeId: '',
    approvalList: [],
    packageid: '',
  }),
  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?.formid
      this.packageid = task.packageid
    },
    forward() {
      const len = this.approvalList.length
      const message = useMessage()

      if (this.currentIndex === len - 1)
        message.error('已经到达最后一个')

      this.setActive(++this.currentIndex)
    },
    back() {
      const message = useMessage()

      if (this.currentIndex === 0)
        message.error('已经到达第一个')

      this.setActive(--this.currentIndex)
    },
    async fetchApprovalList(pagination, id) {
      const res = await getApprovalList(pagination, id)
      this.setApprovalList(res.data)

      if (res.data.length > 0)
        this.setActive(0)

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

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