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

const CART = 'jiqu_library_store_cart'
const SELECT_CART = 'jiqu_library_store_cart_selected'

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 = {
  // 添加购物车
  add({ dispatch,state }, params, custom) {
    const { id, number } = params;
    return new Promise((resolve, reject) => {
      let cart = uni.getStorageSync(CART)
      if (!cart) {
        cart = []
      }
      let exists = false
      cart = cart.map(item => {
        if (item.id == id) {
          exists = true
          item.number += number
        }

        return item
      })
      if (!exists) {
        cart.push({ id, number })
      }
      uni.setStorageSync(CART, cart)

      resolve(cart)
    })
  },
  // 更新购物车商品数量
  update({ dispatch,state }, params) {
    const { id, number } = params;
    return new Promise((resolve, reject) => {
      let cart = uni.getStorageSync(CART)
      if (!cart) {
        cart = []
      }
      let exists = false
      cart = cart.map(item => {
        if (item.id == id) {
          exists = true
          item.number = number
        }

        return item
      })
      uni.setStorageSync(CART, cart)

      resolve(cart)
    })
  },
  // 删除购物车商品
  delete({}, params) {
    const { id } = params;
    return new Promise((resolve, reject) => {
      let cart = uni.getStorageSync(CART)
      if (!cart) {
        cart = []
      }
      cart = cart.filter(item => id.indexOf(item.id) === -1)
      uni.setStorageSync(CART, cart)

      resolve(cart)
    })
  },
  // 获取购物车列表
  getCartList({ commit, rootGetters, state, dispatch }, params) {
    const { mid } = params
    return new Promise((resolve, reject) => {
      const cart = uni.getStorageSync(CART)
      if (!cart || cart.length == 0) {
        resolve([])
      }
      const ids = cart.map(item => item.id).join(',')
      const data = []
      http.get(`/v1/store/${mid}/product-skus`, { params: { id: ids, per_page: -1 } }).then(res => {
        const data = res.map(item => {
          let cartItem = ''
          cart.map(item1 => {
            if (item1.id == item.id) {
              cartItem = item1
            }
          })
          item.is_online = true
          return { id: item.id, quantity: cartItem ? cartItem.number : 1, sku: item }
        })
        resolve(data)
      })
    })
  },
  // 清空购物车
  clear() {
    return new Promise((resolve, reject) => {
      uni.removeStorageSync(CART)
      resolve()
    })
  },
  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
}
