/**
 * 用户购物车仓库
 */

import { productService } from '@/services/index.js'
import { msg as showMsg } from '@/common/util.js'
import { navigateTo } from '@/common/utilsTools.js'

// 计算价格
function totalShopPeice(goodsList) {
    return goodsList.map((item, index) => {
        const priceObj = item.productList.reduce((price, pros, i) => {
            // 处理阶梯价
            if (pros.activeStatus == 1) {
                pros.ladderList.forEach((item, index) => {
                    if (pros.productCount >= item.buyNum) pros.price = item.buyPrice
                })
            } else {
                pros.price = pros.price
            }
            // 计算每个商品下商品的价格
            let _price = pros.price * pros.productCount
            price.totalOriginalPrice += _price
            if (pros.promotion && pros.promotion.type != 2 && pros.promotion.mode == 2) {
                if (_price >= pros.promotion.touchPrice) {
                    _price = _price - pros.promotion.reducedPrice
                    price.reducedPrice += pros.promotion.reducedPrice
                }
                price.totalPrice += _price
            } else {
                price.reducedPrice = 0
                price.totalPrice += pros.price * pros.productCount
            }
            return price
        }, {
            totalPrice: 0,
            reducedPrice: 0,
            totalOriginalPrice: 0
        })
        item.totalPrice = priceObj.totalPrice
        item.reducedPrice = priceObj.reducedPrice
        item.totalOriginalPrice = priceObj.totalOriginalPrice
        return item
    })
}

const state = {
    isEmpty: true,
    goodsList: [], //购物车的商品
    failureList: [], //失效商品列表
    cartIds: [], // 已勾选商品cartId列表
    productIds: [],
    kindCount: 0,
}

const mutations = {
    // 设置购物车商品数量
    setKindCount(state, count) {
        state.kindCount = count
    },
    // 设置购物车有效商品
    setGoodsList(state, list) {
        state.goodsList = list
    },
    // 设置购物车失效商品
    setFailureList(state, list) {
        state.failureList = list
    },
    // 设置购物车是否为空
    setEmptyType(state, flag) {
        state.isEmpty = flag
    },
    saveCartIds(state, ids) {
        state.cartIds = ids
    },
    saveProductIds(state, ids){
        state.productIds = ids
    },
    // 勾选/不勾选 失效商品
    selectFailure(state, { productId, checked }) {
        state.failureList.forEach(prod => {
            if (prod.productId === productId) prod.productsChecked = checked
        })
    },
    // 勾选/取消勾选所有失效商品
    selectAllFailure(state, checked) {
        state.failureList.forEach(prod => {
            prod.productsChecked = checked
        })
    },
    // 重选商品
    resetSelectProducts(state, cartIds = []) {
        state.goodsList.forEach((shop) => {
            shop.productList.forEach(prod => {
                if (cartIds.includes(prod.cartId)) prod.productsChecked = true
            })
            shop.checked = shop.productList.every((prod) => prod.productsChecked === true)
        })
    },
    // 勾选商品
    selectProduct(state, { shopId, productId, checked }) {
        state.goodsList.forEach((shop) => {
            if (shop.shopId !== shopId) return
            shop.productList.forEach(prod => {
                if (prod.productId !== productId) return
                prod.productsChecked = checked
            })
            shop.checked = shop.productList.every((prod) => prod.productsChecked === true)
        })
    },
    // 全选/全不选 供应商下所有商品
    selectAllShopProduct(state, { shopId, checked }) {
        state.goodsList.forEach((shop) => {
            if (shop.shopId !== shopId) return
            shop.checked = checked
            shop.productList.forEach(prod => {
                prod.productsChecked = checked
            })
        })
    },
    // 全选/全不选 部商品
    selectAllProduct(state, checked) {
        state.goodsList.forEach((shop) => {
            shop.checked = checked
            shop.productList.forEach(prod => {
                prod.productsChecked = checked
            })
        })
    },
    // 设置购物车商品数量角标
    setTabBarBadge(state, num) {
        if (num >= 100) {
            uni.setTabBarBadge({
                index: 1,
                text: '99+'
            })
        } else if (num > 0) {
            uni.setTabBarBadge({
                index: 1,
                text: String(num)
            })
        } else {
            uni.removeTabBarBadge({
                index: 1,
            })
        }
    },
}

const actions = {
    // 初始化购物车
    initCart({ rootGetters, commit, state }) {
        return productService.QueryShoppingCartList({ userId: rootGetters.userId })
            .then(response => {
                let data = response.data
                commit('setTabBarBadge', data.cartQuantity)
                commit('setKindCount', data.cartQuantity)
                if (data.shopList.length > 0 || data.products.length > 0) {
                    commit('setEmptyType', false)
                } else {
                    commit('setEmptyType', true)
                }
                if (data.shopList && data.shopList.length > 0) {
                    commit('setGoodsList', totalShopPeice(data.shopList))
                    commit('resetSelectProducts', state.cartIds) // 勾选已选商品
                } else {
                    commit('setGoodsList', [])
                }
                if (data.products && data.products.length > 0) {
                    commit('setFailureList', data.products)
                } else {
                    commit('setFailureList', [])
                }
            })
            .catch(error => {
                showMsg(error.msg, 2000)
            })
    },
    // 获取购物车商品数量
    getCartNumber({ commit, rootGetters }) {
        productService.QueryShoppingQuantity({ userId: rootGetters.userId  })
            .then(response => {
                commit('setTabBarBadge', response.data)
                commit('setKindCount', response.data)
            })
            .catch(error => {
                console.log('查询购物车数量错误信息', error)
            })
    },
    // 添加购物车
    addToCart({ dispatch, rootGetters }, { productId, productCount = 1, heUserId = 0 }) {
        if (!rootGetters.hasLogin) return navigateTo('/pages/login/login')
        productService.shoppingAddCart({
            productId,
            userId: rootGetters.userId,
            productCount,
            heUserId
        }).then(response => {
            showMsg('加入购物车成功', 1500, true, 'success')
            dispatch('getCartNumber')
        }).catch(error => {
            showMsg(error.msg, 2000)
        })
    },
    // 从购物车移除
    removeFromCart({ dispatch, state }, cartIds = []) {
        // 从哪里获取cartIds
        const removeCartIds = cartIds.length > 0 ? cartIds : state.cartIds
        return productService.ShoppingCartDelete({
            cartIds: removeCartIds.join(',')
        }).then(response => {
            dispatch('initCart')
            showMsg('删除成功', 2000)
        }).catch(error => {
            showMsg(error.msg, 2000)
        })
    },
    // 删除失效商品
    removeFailureFromCart({ dispatch, state }) {
        const cartIds = state.failureList.reduce((cartIds, prod) => {
            cartIds.push(prod.cartId)
            return cartIds
        }, [])
        return dispatch('removeFromCart', cartIds)
    },
    // 加减购物车商品更新到后台
    updateShoppogCount({ dispatch, state }, { cartId, productCount }) {
        return productService.ShoppingCartUpdate({
            cartId,
            productCount
        }).finally(() => {
            dispatch('initCart')
        })
    }
}

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