const $ = global;
new $.Page({
    data: {
        goodsList: [],
        selectedAmount: 0,
        totalPrice: 0,
        isEditing: false, // 是否正在编辑
        hasAmountModify: false
    },

    onShow() {
        $.wx.showToast({
            title: '加载中'
        }, 'loading');
        this.setData({
            hasAmountModify: false,
            isEditing: false
        });
        this.getCarts();
    },

    getCarts() {
        $.request('shopcars', 'GET', {}).then((res) => {
            $.wx.hideToast('loading');
            if (res.data && res.data.length > 0) {
                this.setData({
                    goodsList: res.data
                });
                this.calAmount();
            } else {
                this.setData({
                    goodsList: [],
                    isEditing: false,
                    selectedAmount: 0,
                    totalPrice: 0
                });
            }
        });
    },

    changeEditStatus() {
        this.setData({
            isEditing: !this.data.isEditing
        });
        if (!this.data.isEditing && this.data.hasAmountModify) {
            this.confirmModify();
        }
    },

    // 删除指定商品
    deleteGoods(e) {
        const idx = e.currentTarget.dataset.index;
        const id = e.currentTarget.dataset.id;
        const goodsList = this.data.goodsList;
        $.wx.showToast({
            title: '删除中'
        }, 'loading');
        $.request(`shopcar/${id}`, 'DELETE', {}).then(() => {
            $.wx.hideToast('loading');
            if (goodsList.length > 0) {
                goodsList.splice(idx, 1);
                this.setData({
                    goodsList
                });
                if (goodsList.length === 0) {
                    this.setData({
                        isEditing: false
                    });
                }
                this.calAmount();
            }
        });
    },

    // 删除选中的商品
    deleteSelected() {
        const ids = [];
        const goodsList = this.data.goodsList;
        goodsList.forEach((g) => {
            if (g.checked) {
                ids.push(g.id);
            }
        });
        if (ids.length > 0) {
            $.wx.showToast({
                title: '删除中'
            }, 'loading');
            $.request('shopcar/pdelete', 'DELETE', {
                ids
            }).then(() => {
                this.getCarts();
            });
        } else {
            $.wx.showToast({
                title: '请选择需要删除的商品'
            });
        }
    },

    changeSelect(e) {
        const idx = e.currentTarget.dataset.index;
        const goodsList = this.data.goodsList;
        goodsList[idx].checked = !goodsList[idx].checked;
        this.setData({
            goodsList
        });
        this.calAmount();
    },

    changeSelectAll() {
        let goodsList = this.data.goodsList;
        let selectCount = 0;
        for (let goods of goodsList) {
            if (goods.checked) {
                selectCount++;
            }
        }
        if (selectCount < goodsList.length) {
            // 切到全选
            goodsList = goodsList.map((g) => {
                g.checked = true;
                return g;
            });
        } else {
            // 全不选
            goodsList = goodsList.map((g) => {
                g.checked = false;
                return g;
            });
        }
        this.setData({
            goodsList
        });
        this.calAmount();
    },

    minusAmount(e) {
        const idx = e.currentTarget.dataset.index;
        const goodsList = this.data.goodsList;
        if (goodsList[idx].product_amount > 1) {
            goodsList[idx].product_amount--;
            this.setData({
                goodsList,
                hasAmountModify: true
            });
            this.calAmount();
        }
    },

    addAmount(e) {
        const idx = e.currentTarget.dataset.index;
        const goodsList = this.data.goodsList;
        goodsList[idx].product_amount++;
        this.setData({
            goodsList,
            hasAmountModify: true
        });
        this.calAmount();
    },

    calAmount() {
        const goodsList = this.data.goodsList;
        let totalPrice = 0;
        let selectedAmount = 0;
        goodsList.forEach((g) => {
            if (g.checked) {
                selectedAmount++;
                totalPrice += g.price * g.product_amount;
            }
        });
        this.setData({
            selectedAmount,
            totalPrice
        });
    },

    confirmModify() {
        let carts = [];
        const goodsList = this.data.goodsList;
        if (goodsList.length === 0) return;
        goodsList.forEach((g) => {
            carts.push({
                id: g.id,
                product_id: g.product_id,
                product_amount: g.product_amount
            });
        });
        $.request('shopcar/pstore', 'POST', {
            data: carts
        }).then(() => {
            this.setData({
                hasAmountModify: false
            });
        });
    },

    toSettle() {
        const products = [];
        const { name, phone, address, goodsList } = this.data;
        if (goodsList.length === 0) return;
        if (!name || !phone || !address) {
            return $.wx.showToast({
                title: '请把地址信息填写完整'
            });
        }
        if (!this._isPhone(phone)) {
            return $.wx.showToast({
                title: '请输入正确的手机号码'
            });
        }
        goodsList.forEach((g) => {
            if (g.checked) {
                // g.amount = g.product_amount;
                // g.id = g.product_id;
                products.push({
                    id: g.product_id,
                    amount: g.product_amount
                });
            }
        });
        if (products.length === 0) {
            return $.wx.showToast({
                title: '请先选择购买商品'
            });
        }
        $.wx.showToast({
            title: '购买中'
        }, 'loading');
        $.request('product_order/store', 'POST', {
            address,
            contact: name,
            phone,
            products
        }).then((res) => {
            if (res.data) {
                this.callWXPay(res.data.id, res.data.order_type || 'product_order');
            }
        });
    },
    callWXPay(order_id, order_type) {
        $.request('payments/pay', 'POST', {
            order_id,
            order_type
        }).then((res) => {
            if (res.msg) {
                const {
                    timestamp,
                    paySign,
                    nonceStr
                } = res.msg;
                const pck = res.msg.package;
                wx.requestPayment({
                    timeStamp: timestamp + '',
                    nonceStr,
                    package: pck,
                    signType: 'MD5',
                    paySign,
                    success(res) {
                        $.wx.showToast({
                            title: '支付成功'
                        });
                    },
                    fail() {
                        $.wx.showToast({
                            title: '支付失败'
                        });
                    },
                    complete() {
                        setTimeout(function () {
                            $.router.goto({
                                path: '/pages/order/index',
                                type: $.ROUTER_TYPE.SWITCH_TAB
                            });
                        }, 2000);
                    }
                });
            }
        });
    }
});