import { defineStore } from 'pinia';
import { GoodsBean, StockBean } from '@/api/goods/types';

const useShoppingCartStore = defineStore('shoppingCart', {
  state: (): { shoppingCartList: GoodsBean[] } => ({
    shoppingCartList: []
  }),

  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: 'shoppingCartState',
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value); // [!code warning]
      },
      getItem(key) {
        return uni.getStorageSync(key); // [!code warning]
      }
    },
    // 部分持久化状态的点符号路径数组，[]意味着没有状态被持久化(默认为undefined，持久化整个状态)
    paths: undefined
  },

  getters: {
    getShoppingCartList(): any[] {
      return this.shoppingCartList;
    },

    getTotalCount(): number {
      return this.shoppingCartList.length;
    },

    getSameGoodsIndex: (state) => (goodsId: string, colorId: string, sizeId: string) => {
      return state.shoppingCartList.findIndex(res => res.id === goodsId && res.checkedStock.colorId === colorId && res.checkedStock.sizeId === sizeId);
    }
  },

  actions: {
    save(partial: Partial<GoodsBean>) {
      this.shoppingCartList.push(partial as GoodsBean);
    },

    updateCount(index: number, count: number) {
      this.shoppingCartList[index].checkedStock.count += count;
    },

    updateStock(index: number, stock: StockBean) {
      this.shoppingCartList[index].checkedStock = stock;
    },

    delete(index: number) {
      this.shoppingCartList.splice(index, 1);
    },

    deleteIfChecked() {
      this.shoppingCartList = this.shoppingCartList.filter(res => res.checked == undefined || res.checked === false);
    },

    clearAll() {
      this.shoppingCartList = [];
    }
  }
});

export default useShoppingCartStore;
