// subpages/goodscar/goodscar.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        carList: [],
        isHidePageloading: false,
        imgUrl: app.shopImgUrl,
        totalPrice: 0.0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var _self = this;
        try {
            var value = wx.getStorageSync('carlist');
            console.log(value)
            if (value) {
                _self.setData({
                    carList: value,
                    isHidePageloading: true
                })
                _self.countPrice()
            } else {
                _self.setData({
                    isHidePageloading: true
                })
            }
        } catch (e) {

        }
    },
    delGoods(e) {
        var _self = this;
        wx.showModal({
            title: '提示',
            content: '确定要删除该商品吗?',
            complete: (res) => {
                if (res.confirm) {
                    var index = e.currentTarget.dataset.index
                    console.log(index)
                    _self.data.carList.splice(index, 1)
                    _self.setData({
                        carList: _self.data.carList
                    })
                    wx.setStorageSync('carlist', _self.data.carList);
                    _self.countPrice();
                }
            }
        })
    },
    delCount(e) {
        var _self = this;
        var index = e.currentTarget.dataset.index
        if (this.data.carList[index].carAmount == 1) {
            return;
        }
        this.data.carList[index].carAmount -= 1;
        this.setData({
            carList: this.data.carList
        })
        wx.setStorageSync('carlist', _self.data.carList);
        _self.countPrice();
    },
    addCount(e) {
        var _self = this;
        var index = e.currentTarget.dataset.index
        this.data.carList[index].carAmount += 1;
        this.setData({
            carList: this.data.carList
        })
        wx.setStorageSync('carlist', _self.data.carList);
        _self.countPrice();
    },
    selSelect(e) {
        var _self = this;
        var index = e.currentTarget.dataset.index;
        _self.data.carList[index].isCheck = !_self.data.carList[index].isCheck;
        _self.setData({
            carList: _self.data.carList
        })
        wx.setStorageSync('carlist', _self.data.carList);
        _self.countPrice();
    },
    countPrice() {
        var _self = this;
        var tempCount = 0;
        for (let i = 0; i < _self.data.carList.length; i++) {
            const item = _self.data.carList[i];
            if (item.isCheck) {
                tempCount = item.goodsPrice * item.carAmount + tempCount;
            }
        }
        _self.setData({
            totalPrice: tempCount
        })
    }
})