import { defineStore } from 'pinia'
import type { PackageListItem, PackageState } from '/#/workorder'
import { useMessage } from 'naive-ui'
import { getPackageList } from '@/api/work/work'
import { store } from '@/store'

export const useWorkOrderStore = defineStore({
  id: 'work-order',
  state: (): PackageState => ({
    currentIndex: -1,
    activeId: '',
    packageList: [],
  }),
  getters: {
    getActiveId: (state: PackageState) => state.activeId,
    getCurrentIndex: (state: PackageState) => state.currentIndex,
    getOrderList: (state: PackageState) => state.packageList,
  },
  actions: {
    setOrderList(list: PackageListItem[]) {
      this.packageList = list
    },
    setActive(index: number, orderId?: string) {
      this.currentIndex = index
      const order = this.packageList[index]
      this.activeId = orderId || order?.id
    },
    forward() {
      const len = this.packageList.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 fetchOrderList(pagination) {
      const res = await getPackageList(pagination)
      this.setOrderList(res.data)

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

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

export function useWorkOrder() {
  return useWorkOrderStore(store)
}
