import { defineStore } from 'pinia'
import {
  OrderData,
  PodMakeOrderData,
  ProductList,
} from '@/types/api/podMakeOrder'
import { getPodBoxListApi } from '@/api/podUsOrder'
export interface OrderStoreState {
  podBoxList?: PodMakeOrderData[]
  podBoxIndex?: number | null
  socketConnect?: string
}
const useOrderStore = defineStore('order', {
  state: () => {
    return {
      podBoxList: [],
      podBoxIndex: null,
      socketConnect: '',
    } as OrderStoreState
  },
  actions: {
    async setPodBoxList(content: {
      url: string
      boxList: PodMakeOrderData[] | OrderData | null
      factoryNo: number | string | undefined
      fromUser: number
      warehouseId: number | string
      box?: number
      data?: OrderData
    }) {
      console.log(content, 'content')
      const { url, factoryNo, warehouseId, boxList, box, data, fromUser } = content
      if (Array.isArray(boxList)) {
        boxList.forEach((item) => {
          item.fromUser = fromUser
        })
        this.podBoxList = boxList
      } else {
        const index = this.podBoxList?.findIndex((item) => item.box === box)
        if (index === -1) {
          try {
            const res = await getPodBoxListApi(url, factoryNo, warehouseId)
            const boxList = res.data.map((item) => {
              item.fromUser = fromUser
              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] = {
              fromUser: fromUser,
              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
