import Vue from "vue"
let prototype = Vue.prototype;

export default {
    /**
     * 获取总数
     */
    count(id, type) {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "service.cart.count",
            }).then((response) => {
                return resolve(response.data.count);
            }).catch(e => { });
        });
    },
    /**
     * 添加到购物车
     */
    toCart(id) {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "service.cart.toCart",
                data: {
                    id: id,
                }
            }).then((response) => {
                prototype.$utils.toast(response.msg);
                if (response.code == 1) {
                    return resolve();
                }
                return reject(response.msg);
            }).catch(e => { });
        });
    },
    /**
     * 增加/减少数量
     */
    change(id, type) {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "service.cart." + (type == 'sub' ? 'sub' : 'add'),
                data: {
                    id: id,
                }
            }).then(() => {
                return resolve();
            }).catch(e => { });
        });
    },
    /**
     * 删除
     */
    delete(id) {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "service.cart.delete",
                data: {
                    id: id,
                }
            }).then(() => {
                return resolve();
            }).catch(e => { });
        });
    },
    /**
     * 列表
     */
    list(refresh) {
        return new Promise((resolve, reject) => {
            let cacheList = uni.getStorageSync('USER_CART');
            if ((typeof refresh === "undefined" || false === refresh) && cacheList) {
                return resolve(cacheList);
            }

            prototype.$request({
                api: "service.cart.list",
            }).then(response => {
                if (response.code == 1) {
                    uni.setStorageSync('USER_CART', response.data);
                    return resolve(response.data);
                }
                return reject(response.msg);
            }).catch(e => { });
        });
    }
}
