import { defineStore } from 'pinia'

import { getCategoryList, insertCategory, updateCategory, deleteCategory } from '@/apis/order'
import type { OrderCategoryInfo } from '@/types/order'
import { SuccessResultCode, type Result } from '@cacp/ui'

interface CoreState {
  isInited: boolean
  categoryInfoList: Array<OrderCategoryInfo>
}

export const useCategoryStore = defineStore('category', {
  state: (): CoreState => ({
    isInited: false,
    categoryInfoList: []
  }),
  actions: {
    async initCategory() {
      if (!this.isInited) {
        const res: Result<Array<OrderCategoryInfo>> = await getCategoryList()
        if (res.code === SuccessResultCode) {
          this.$patch({
            isInited: true,
            categoryInfoList: res.data
          })
        }
      }
    },
    async insertCategory(category: OrderCategoryInfo) {
      // 插入
      const res = await insertCategory({ ...category })
      if (res.code == SuccessResultCode) {
        this.categoryInfoList.push({ ...category })
      }
    },
    async updateCategory(category: OrderCategoryInfo) {
      // 更新
      const res = await updateCategory({ ...category })
      if (res.code == SuccessResultCode) {
        const index = this.categoryInfoList.findIndex(
          (item: OrderCategoryInfo) => category.categoryCode === item.categoryCode
        )
        if (index > -1) {
          this.categoryInfoList.splice(index, 1, { ...category })
        }
      }
    },
    deleteCategory(categoryCode: string) {
      const index = this.categoryInfoList.findIndex((item: OrderCategoryInfo) => categoryCode === item.categoryCode)
      if (index > -1) {
        this.categoryInfoList.splice(index, 1)
        deleteCategory(categoryCode)
      }
    }
  }
})
