import cartPage from '@/apis/cartPage';
import goodPage from '@/apis/goodPage';
import { isArray } from '@/utils'
import reComputedShopCar from '@/utils/reComputedShopCar.js'
import { modal, toast } from '@/utils/uniapi.js'
import { msgData } from '@/config'
export default {
    /**
     * 获取购物车列表
     */
    getCarList: async ({ commit, rootGetters }, storeID) => {
        let res = await cartPage.getMyCart(storeID)
        if (!res) return []

        let count = res && res.length > 0 ? res.map(item => item.count).reduce((prev, cur) => prev + cur) : 0

        commit('saveCartCount', count)

        // 组装购物车数据
        let storeSkus = await goodPage.getStoresSkus({
            pageSize: -1,
            offset: 0,
            skuIDs: res.map(item => item.skuID)
        })
        let arr = []
        res.forEach(item => {
            let findItem = storeSkus.skuNames.find(sku => sku.id === item.skuID && sku.storeID === item.storeID)
            if (findItem) {
                arr.push({
                    ...findItem,
                    checked: item.isChecked ? true : false,
                    count: item.count
                })
            }
        });

        reComputedShopCar(arr)
        commit('saveCartList', arr)

        // 修改热销商品的数据
        
        let isMaterial = rootGetters['indexPage/isMaterial']
        if(isMaterial){
            let topGoods = rootGetters['indexPage/topGoods']
            if (arr && arr.length > 0) {
                arr.forEach(element => {
                    let findIndex = topGoods.findIndex(item => item.id === element.id)
                    if (findIndex !== -1) topGoods[findIndex].count = element.count
                })
            }
        }
        
    },

    /**
     * 改变购物车的商品数量
     */
    changeCar: async ({ state, commit, rootGetters }, { skuName, count }) => {
        const isMaterial = rootGetters["indexPage/isMaterial"]

        // #ifdef MP-WEIXIN
        const fromStoreInfo = rootGetters['indexPage/materialInfo'] ? rootGetters['indexPage/materialInfo'].fromStoreInfo : null
        if (isMaterial && fromStoreInfo.packageSwitch === 1) return toast(`非常抱歉,无法购买物料，请联系运营${fromStoreInfo.marketManPhone}`)
        // #endif

        if(count > skuName.stock) {
            return toast('暂时没有那么多商品喔~')
        }

        if (count <= 0) {
            let confirm = await modal("温馨提示", msgData.delGoods);
            if (!confirm) return
            count = 0
        }

        if (count > 999) {
            toast(msgData.moreThan999)
            count = 999
        }

        let list = JSON.parse(JSON.stringify(state.list))

        let topGoodsOld = rootGetters['indexPage/topGoods'] // 热销商品数据
        if (isArray(skuName)) {
            // 再次购买使用
            let findIndex = skuName.findIndex(item => item.actType && item.count > 1)
            if (findIndex !== -1 && rootGetters['confirmCheckShow']) toast('已超限购，将按原价购买')

            list = skuName.map(item => ({
                ...item,
                checked: true
            }))

            if (topGoodsOld && topGoodsOld.length > 0 && isMaterial) {
                // 修改热销商品的数据
                topGoodsOld.map((element, index) => {
                    let findItem = list.find(item => item.id === element.id)
                    if (findItem) topGoodsOld[index].count = findItem.count
                    else topGoodsOld[index].count = 0
                })
            }

        } else {
            if (skuName.actType && rootGetters['confirmCheckShow'] && count > 1) toast('已超限购，将按原价购买')

            let listItem = list.find(item => item.id === skuName.id && item.storeID === skuName.storeID)

            if (listItem) {
                if (count > 0) {
                    listItem.count = count

                    if (topGoodsOld && topGoodsOld.length > 0  && isMaterial) {
                        // 修改热销商品的数据
                        let findIndex = topGoodsOld.findIndex(item => item.id === listItem.id)
                        if (findIndex !== -1) topGoodsOld[findIndex].count = count
                    }
                } else {
                    // 移除
                    for (let i = 0; i < list.length; i++) {
                        if (list[i].id === skuName.id && list[i].storeID === skuName.storeID) {

                            if (topGoodsOld && topGoodsOld.length > 0 && isMaterial) {
                                // 修改热销商品的数据
                                let findIndex = topGoodsOld.findIndex(item => item.id === list[i].id)
                                if (findIndex !== -1) topGoodsOld[findIndex].count = 0
                            }

                            list.splice(i, 1)
                            break
                        }
                    }
                }
            } else {
                if (count > 0) {
                    // 添加
                    list.push({
                        ...skuName,
                        count,
                        checked: true
                    })

                    if (topGoodsOld && topGoodsOld.length > 0   && isMaterial) {
                        // 修改热销商品的数据
                        let findIndex = topGoodsOld.findIndex(item => item.id === skuName.id)
                        if (findIndex !== -1) topGoodsOld[findIndex].count = count
                    }
                }
            }


        }
        await cartPage.saveToCart(rootGetters['indexPage/storeID'][0], list)
        commit('saveCartList', list)    // 保存到购物车
    },

    /**
     * 移除商品 
     */
    removeSkuName: async ({ state, commit, rootGetters }, skuNames) => {
        const list = JSON.parse(JSON.stringify(state.list))
        skuNames.forEach(needRemove => {
            let listItem = list.find(item => item.id === needRemove.id && item.storeID === needRemove.storeID)
            if (listItem) {
                // 移除
                for (let i = 0; i < list.length; i++) {
                    if (list[i].id === needRemove.id && list[i].storeID === needRemove.storeID) {
                        list.splice(i, 1)
                        break
                    }
                }
            }
        })

        await cartPage.saveToCart(rootGetters['indexPage/storeID'][0], list)
        commit('saveCartList', list)    // 保存到购物车
    },


    /**
     *  勾选购物车可能会请求服务器异步调用
     */
    checkSkuName: async ({ state, commit, rootGetters }, { skuName, checkStatus }) => {
        const list = JSON.parse(JSON.stringify(state.list))
        let listItem = list.find(item => item.id === skuName.id && item.storeID === skuName.storeID)
        listItem.checked = checkStatus
        await cartPage.saveToCart(rootGetters['indexPage/storeID'][0], list)    // 保存
        commit('saveCartList', list)    // 保存到购物车
    },

    /**
     * 全选/取消全选
     */
    checkAllOrCancel: async ({ state, commit, rootGetters }, checked) => {
        let list = JSON.parse(JSON.stringify(state.list))
        list = list.map(item => ({
            ...item,
            checked
        }))
        await cartPage.saveToCart(rootGetters['indexPage/storeID'][0], list)    // 保存
        commit('saveCartList', list)    // 保存到购物车
    },

    /**
     * 清空购物车
     */
    clearAllShopCar: async ({ state, commit, rootGetters }) => {
        let list = JSON.parse(JSON.stringify(state.list))
        list = []
        await cartPage.saveToCart(rootGetters['indexPage/storeID'][0], list)    // 保存
        commit('saveCartList', list)
    }
}