import cart from '@/core/models/cart';

export default {
    namespaced: true,
    state: {
        cart: {
            loaded: false,
            list: [],
        },
    },
    getters: {
        briefCart(state) {
            let data = {
                count: 0,
                ids: [],
                list: {},
            };
            state.cart.list.forEach((item) => {
                item.good.forEach((k) => {
                    data.count += k.number;
                    data.list[k.gid] = k.number;
                });
            });
            data.ids = Object.keys(data.list);

            return data;
        }
    },
    mutations: {
        cart(state, data) {
            state.cart = data;
        }
    },
    actions: {
        async update(context, refresh) {
            if (!context.state.cart.loaded || refresh) {
                await cart.list().then((list) => {
                    context.commit('cart', {
                        list: list,
                        loaded: true,
                    });
                });
            }
        }
    }
}
