import { CartTypeEnum } from "@/types/cart";
import { defineStore } from "pinia";

type ShoppingGoods = {
  type: CartTypeEnum;
  name:string;
  price:number;
  count:number;
  cover:string;
  id:string|number;
  desc?:string;
}

type ShoppingCartState = {
  shoppingCartList: ShoppingGoods[];
}

export const useShoppingCartStore = defineStore("ShoppingCart", {
    persist: true,
    state: ():ShoppingCartState => ({
      shoppingCartList: [],
    }),
    getters: {
      getShoppingCartList(state) {
        return state.shoppingCartList;
      },
      getShoppingCartByMall(state){
        return state.shoppingCartList.filter(item => item.type === CartTypeEnum.Mall);
      },
      getShoppingCartByRestaurant(state){
        return state.shoppingCartList.filter(item => item.type === CartTypeEnum.Restaurant);
      },
      getShoppingCartByCourse(state){
        return state.shoppingCartList.filter(item => item.type === CartTypeEnum.Course);
      },
      getShoppingCartByHealthCare(state){
        return state.shoppingCartList.filter(item => item.type === CartTypeEnum.HealthCare);
      },
      getShoppingCartByHousekeeping(state){
        return state.shoppingCartList.filter(item => item.type === CartTypeEnum.Housekeeping);
      },
      getShoppingCartByHousekeepingWithId(state){
        return (id: number) => {
          return state.shoppingCartList.filter(
            item => item.type === CartTypeEnum.Housekeeping && item.id === id
          );
        };
      }
    },
    actions: {
      addShoppingCart(goods:ShoppingGoods){
        let isExist = this.shoppingCartList.find(item => item.id === goods.id && item.type === goods.type); 
        if(isExist){
          isExist.count = Number(isExist.count) + Number(goods.count);
        }else{
          this.shoppingCartList.push(goods);
        }
      },
      addShoppingCartWithOne(goods:ShoppingGoods){
        let isExist = this.shoppingCartList.find(item => item.id === goods.id && item.type === goods.type);        
        if(isExist){
          return;
        }else{
          this.shoppingCartList.push(goods);
        }
      },
      removeShoppingCart(id:string|number){
        this.shoppingCartList = this.shoppingCartList.filter(item => item.id !== id);
      },
      updateShoppingCart(id:string|number, goods:ShoppingGoods){
        this.shoppingCartList = this.shoppingCartList.map(item => (item.id === id && goods.type === item.type) ? goods : item);
        console.log(this.shoppingCartList);
        
      },
      clearShoppingCart(){
        this.shoppingCartList = [];
      },
      clearShoppingCartByType(type:CartTypeEnum){
        this.shoppingCartList = this.shoppingCartList.filter(item => item.type !== type);
      }
    },
  });