import { defineStore } from 'pinia'
import {
  OrderData,
  PodMakeOrderData,
  ProductList,
} from '@/types/api/podMakeOrder'
import { getSuperPodBoxListApi } from '@/api/podCnOrder'
export interface OrderStoreState {
  podBoxList?: PodMakeOrderData[]
  podBoxIndex?: number | null
  socketConnect?: string
}
const useOrderStore = defineStore('cnSuperOrder', {
  state: () => {
    return {
      podBoxList: [],
      podBoxIndex: null,
      socketConnect: '',
    } as OrderStoreState
  },
  actions: {
    async setPodBoxList(content: {
      boxList: PodMakeOrderData[] | OrderData | null | undefined,
      factoryNo: number | string
      box?: number
      data?: OrderData
    }) {
      const { factoryNo, boxList, box, data } = content

      if (Array.isArray(boxList)) {
        this.podBoxList = boxList
      } else {
        const index = this.podBoxList?.findIndex((item) => item.box === box)
        if (index === -1) {
          try {
            const res = await getSuperPodBoxListApi(factoryNo)
            const boxList = res.data.map((item) => {
              if (res.data) {
                const productList = item?.data?.productList || []
                const pickingNumber = productList.reduce(
                  (prev: number, item1: ProductList) => {
                    if (item1.count) {
                      return prev + item1.count
                    }
                    return prev
                  },
                  0,
                )
                if (item.data) {
                  item.data.pickingNumber = pickingNumber
                }
              }

              return item
            })
            this.podBoxList = boxList
            this.podBoxIndex = box
          } catch (error) {
            console.error(error)
          }
        } else if (box !== 0 && box !== undefined) {
          const arr = this.podBoxList
          if (arr) {
            arr[box - 1] = {
              box,
              data: data || boxList || null,
            }
          }
          this.podBoxList = arr
          this.podBoxIndex = box
        }
      }
    },
    // 清空所有箱子
    clearPodBoxList() {
      this.podBoxList = []
    },
    // 设置当前箱子
    setPodBox(box: number) {
      this.podBoxIndex = box
    },
    // 清空当前箱子
    clearPodBox() {
      this.podBoxIndex = null
    },
    setSocketConnect(connect: string) {
      this.socketConnect = connect
    },
  },
})

export default useOrderStore
