import { defineStore } from 'pinia'

import _ from 'lodash'

import { getItems, addCart, deleteCart, updateCart } from '@/services/cart'

export const useCartStore = defineStore('cart', {
  state: () => {
    return {
      cartItems: []
    }
  },
  getters: {
    cartNum(state) {
      return state.cartItems.length
    }
  },
  actions: {
    async initCart() {
      let res = await getItems()
      if (res.code === 200) {
        this.cartItems = res.data
      }
    },
    async addCart(goods) {
      let res = await addCart(goods)
      if (res.code === 200) {
        this.cartItems = res.data
        return true
      } else {
        return false
      }
    },
    async delCart(id) {

      let res = await deleteCart(id)

      if (res.code === 200) {
        _.remove(this.cartItems, function (i) {
          return i.rec_id === id
        })
      }
    },
    async updateCart(goods, num) {
      let res = await updateCart({ ...goods, num })

      if (res.code === 200) {
        this.cartItems.map((element, index) => {
          if (element.rec_id === goods.rec_id) {
            element.goods_number = num
          }
        })
      }
    },
    async clearCart() {
      this.cartItems = []
    },
  },
})