
import {
  http
} from '@/utils/request'

const SELECT_CART = 'app_select_CART'

const getDefaultState = () => {
  return {
    cartList: [],
    selectedCart: uni.getStorageSync(SELECT_CART) || []
  }
}


const state = getDefaultState()

const mutations = {
  SET_CARTLIST(state, value) {
    state.cartList = value
  },
  SET_SELECTED_CART(state, value) {
    state.selectedCart = value
  }
}

const actions = {
  //添加购物车
  addCart({ dispatch,state }, params, custom) {
    const { skuId, number } = params;
    return new Promise((resolve, reject) => {
      http.post('/v1/shopping-cart-items', { sku_id: skuId, quantity: number }, custom).then(resData => {
        resolve(resData)
        dispatch('setSelectedCart',[...state.selectedCart,resData.id])
        dispatch('getCartList')
      }).catch(err => {
        reject(err)
      })
    })
  },
  //获取购物车列表
  getCartList({ commit, rootGetters,state,dispatch }) {
    if (!rootGetters.isLogin) return commit('SET_CARTLIST', [])
    return new Promise((resolve, reject) => {
      http.get('/v1/shopping-cart-items').then(resData => {
        commit('SET_CARTLIST', resData)
        dispatch('setSelectedCart',resData.filter(item=>state.selectedCart.findIndex(e=>e==item.id)>=0).map(e=>e.id))
        resolve(resData)
      }).catch(err => {
        reject(err)
      })
    })
  },
  setSelectedCart({commit},value){
    const arr = Array.from(new Set(value))
    uni.setStorageSync(SELECT_CART, arr)
    commit('SET_SELECTED_CART',arr)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
