// pages/order/placeOrder/placeOrder.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeKey: 0,
        navList: [],
        height: '',
        show: false,
        detailsShow: false,
        carList: [

        ],
        carNum: 0,
        carPrice: 0,
        shoppingList: [],
        shop: [],
        worke: "",
        status: "",
        order_num:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

         console.log(options);
        const q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
        if(options.network_id){
            this.setData({worke:{id:options.network_id}})
        }
    
        if(typeof options.parmise!="undefined"){
            console.log('-------'+options.parmise)
            var worke = JSON.parse(options.parmise);
            this.setData({
                worke:worke
            })
            this.getcart();
        }else if(typeof options.network_id!="undefined"){
            this.getNwetwork(options.network_id)
        }else{
           var network_id=app.getQueryVariable(q,"network_id")
           var order_num=app.getQueryVariable(q,"order_num")
           console.log(network_id);
            this.setData({
                order_num:order_num
            })
            this.getNwetwork(network_id)
        }
     
      
    
        this.setData({
            status: app.globalData.status
        })
        this.getHeight()
        this.getCarAll()
       
        this.leftList()
    },
    onShow() {
        this.getcart();
    },
    goto(){
        wx.navigateTo({
          url: '/pages/order/access/access?network_id='+this.data.worke.id,
        })
    },
    shoppingMinus(e) {
        let items = e.currentTarget.dataset.item, list = this.data.shoppingList;
        var carNum = this.data.carNum ? this.data.carNum : 0
        var carPrice = this.data.carPrice ? this.data.carPrice : 0
        list.map(item => {
            if (items.id == item.id) {
                if (item.num <= 0) {
                    item.num = 0
                } else {
                    item.num--
                }

                console.log(item);
                var price = (item.price.end_time == 0 && item.price.start_time == 0) ? item.price.price : item.price.sale_price
                this.setData({
                    carNum: (carNum - 1) <= 0 ? 0 : carNum - 1,
                    carPrice: (parseFloat(carPrice) - parseFloat(price)) <= 0 ? 0 : parseFloat(carPrice) - parseFloat(price)
                })

                this.changeCarList(item)
                var good_id = items.id;
                var money = price;
                var stock = item.num;
                this.cartChang(good_id, money, stock);

            }
        })
        this.setData({
            shoppingList: list
        })
        // this.getCarAll()
    },

    shoppingPlus(e) {
        let items = e.currentTarget.dataset.item, list = this.data.shoppingList;
        var carNum = this.data.carNum ? this.data.carNum : 0
        var carPrice = this.data.carPrice ? this.data.carPrice : 0
        list.map(item => {
            if (items.id == item.id) {
                item.num++
                console.log(item);
                this.changeCarList(item)
                var price = (item.price.end_time == 0 && item.price.start_time == 0) ? item.price.price : item.price.sale_price
                this.setData({
                    carNum: carNum + 1,
                    carPrice: parseFloat(carPrice) + parseFloat(price)
                })
                var type = items.good_type
                var good_id = items.id;
                var money = price;
                var stock = item.num;
                this.cartChang(good_id, money, stock, type);


            }
        })



        this.setData({
            // carList:items,
            shoppingList: list
        })
        //this.getCarAll()
    },

    changeCarList(item) {
        let carList = this.data.carList

        if (carList == {} || carList.length == 0 || !carList || carList !== []) {
            //  carList.push(item)
            this.setData({
                carList: item
            })
            return false;
        } else {
            console.log(item);
            var type = false;
            carList.map((i, index) => {
                if (i.id === item.id) {
                    i.stock = item.num
                    if (item.num == 0) {
                        carList.splice(index, 1)
                    }
                    this.setData({
                        carList
                    })
                    type = false
                } else {
                    type = true
                }
            })
            if (type) {
                carList.push(item)
            }
            console.log(carList);
            this.setData({
                carList
            })
        }
    },

    //修改购物车
    cartChang(good_id, money, stock, type = 1) {
        var nid = this.data.worke.id;
        app.api.useApi(app.globalData.baseAppUrl + "api/change_cart", {
            network_id: nid,
            good_id: good_id,
            money: money,
            stock: stock
        }, "post").then(function (res) {
            console.log(res);
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.status,
                })
            } else {
                var data = res.message.data;
                var shop = [];
                for (var index in data) {
                    shop[data[index].id] = data[index].goods
                }

                that.setData({
                    navList: res.message.data,
                    shoppingList: res.message.data[0].goods,
                    shop: shop
                })

                if (type != 1) {
                    that.getOrder();
                }

            }

            wx.hideLoading();

        }).catch(function (err) {
            console.log(222);
        })
    },

    changeShoppingList(item) {
        console.log(item);
        let shoppingList = this.data.shoppingList;
        shoppingList.map(i => {
            if (item.id == i.id) {
                i.num = item.num
            }
        })
        this.setData({
            shoppingList
        })

    },

    getCarAll() {

        let carList = this.data.carList
        var carNum = this.data.carNum ? this.data.carNum : 0
        var carPrice = this.data.carPrice ? this.data.carPrice : 0

        carList.map(item => {
            wx.nextTick(() => {
                var price = (item.price.end_time && item.price.start_time) ? item.price.sale_price : item.price.price
                carPrice = carPrice + price * item.num;
                this.setData({
                    carNum: carNum + item.num,
                    carPrice: carPrice
                })

            })
        })

    },

    getcart() {
        var nid = this.data.worke.id;
        var that = this;
        app.api.useApi(app.globalData.baseAppUrl + "api/cart_info", {
            network_id: nid,
        }, "get").then(function (res) {
            console.log(res);
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.msg,
                })
            } else {
                console.log(res.message.msg)
                if (res.message.msg == "空购物车") {
                    console.log(111)
                    that.setData({
                        carList: {},
                        carNum: 0,
                        carPrice: 0
                    })
                } else {
                    console.log(444)
                    that.setData({
                        carList: res.message.data.cart.data,
                        carNum: res.message.data.carNum,
                        carPrice: res.message.data.carPrice
                    })
                }

            }

            wx.hideLoading();

        }).catch(function (err) {
            console.log(222);
        })
    },

    getOrder() {
        var nid = this.data.worke.id;
        if(this.data.carNum>0){

            app.api.useApi(app.globalData.baseAppUrl + "api/makeorder", {
                network_id: nid,
            }, "post").then(function (res) {
                console.log(res);
                if (res.code != 200) {
                    wx.showLoading({
                        title: res.message.msg,
                    })
                    wx.setTimeout(() => {
                        wx.hideLoading();
                    }, 1000);
                } else {
                    var order_no = res.message.data.order_no;
                    wx.navigateTo({
                        url: '/pages/order/confirmOreder/confirmOreder?order_no=' + order_no,
                    })
                }
    
    
    
            }).catch(function (err) {
                console.log(222);
            })
        }else{
            wx.showToast({
                title: '购物车不能为空',
                icon: 'none',
                duration: 2000
            })
        }




    },
    
    getOrderone(e) {
        var gid = e.currentTarget.dataset.gid;
        var nid = this.data.worke.id;
        app.api.useApi(app.globalData.baseAppUrl + "api/CreateOrder", {
            network_id: nid,
            good_id: gid,
            num: 1
        }, "post").then(function (res) {
            console.log(res);
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.msg,
                })
                wx.setTimeout(() => {
                    wx.hideLoading();
                }, 1000);
            } else {
                var order_no = res.message.data.order_no;
                wx.navigateTo({
                    url: '/pages/order/confirmOreder/confirmOreder?order_no=' + order_no,
                })
            }



        }).catch(function (err) {
            console.log(222);
        })




    },
    carPlus(e) {
        let items = e.currentTarget.dataset.item, list = this.data.carList;
        var carNum = this.data.carNum ? this.data.carNum : 0
        var carPrice = this.data.carPrice ? this.data.carPrice : 0
        list.map(item => {

            if (items.good_id == item.good_id) {
                item.stock++
                console.log(item);
                //  this.changeShoppingList(item)
                //var price = (item.price.end_time && item.price.start_time) ? item.price.sale_price : item.price.price
                var price = item.money
                this.setData({
                    carNum: carNum + 1,
                    carPrice: parseFloat(carPrice) + parseFloat(price),

                })

                var good_id = items.good_id;
                var money = price;
                var stock = item.stock;
                this.cartChang(good_id, money, stock);


            }
        })



        this.setData({
            carList: list
        })
        //this.getCarAll()
    },

    carMinus(e) {
        let items = e.currentTarget.dataset.item, list = this.data.carList;
        var carNum = this.data.carNum ? this.data.carNum : 0
        var carPrice = this.data.carPrice ? this.data.carPrice : 0
        console.log(items);
        list.map(item => {
            if (items.good_id == item.good_id) {
                item.stock--
                if (item.stock <= 0) {
                    item.stock = 0
                } else {
                    item.stock--
                }
                console.log(item);
                var price = item.money
                this.setData({
                    carNum: (carNum - 1) <= 0 ? 0 : carNum - 1,
                    carPrice: (parseFloat(carPrice) - parseFloat(price)) <= 0 ? 0 : parseFloat(carPrice) - parseFloat(price)
                })

                //  this.changeShoppingList(item)
                var good_id = items.good_id;
                var money = price;
                var stock = item.stock;
                this.cartChang(good_id, money, stock);
                if (item.num == 0) {
                    list.splice(index, 1)
                }
            }
        })
        this.setData({
            carList: list
        })

    },
    clearCarAll() {
        this.setData({
            carList: []
        })
        let shoppingList = this.data.shoppingList
        shoppingList.map(item => {
            item.num = 0
        })
        this.setData({
            shoppingList
        })


        var that = this;
        var nid = this.data.worke.id;

        app.api.useApi(app.globalData.baseAppUrl + "api/DeleteCart", {
            network_id: nid,
        }, "DELETE").then(function (res) {
            console.log(res);
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.msg,
                })
            } else {
                var data = res.message.data;
                wx.showLoading({
                    title: res.message.msg,
                })
            }

            wx.hideLoading();

        }).catch(function (err) {
            console.log(222);
        })






        this.getCarAll()
        this.btnShow()
        this.getHeight()

    },

    closeNews() {
        console.log(this.data.height);
        this.setData({
            height: this.data.height + 40
        })
    },
    changeActive(e) {
        let { activekey } = e.currentTarget.dataset
        var id = e.currentTarget.dataset.id;


        var shoppingList=this.data.shop[id];
    
        if(typeof shoppingList=="undefined"){
            shoppingList=new Array();
        }
    

        this.setData({
            activeKey: activekey,
            shoppingList: shoppingList
        })
    },
    addressDetail() {
        this.setData({
            detailsShow: !this.data.detailsShow
        })
    },
    getHeight() {
        var clientHeight;
        wx.getSystemInfo({
            success: (res) => {
                clientHeight = res.windowHeight;
            }
        });
        var query1 = wx.createSelectorQuery()
        var query2 = wx.createSelectorQuery()
        var query3 = wx.createSelectorQuery()
        query1.select('#footerBar').boundingClientRect()
        query2.select('#topBox').boundingClientRect()
        query3.select('#scrollBox').boundingClientRect()
        query2.exec(result => {
            query3.exec(r => {
                query1.exec(res => {
                    if (res && res[0] != null) {
                        this.setData({
                            height: clientHeight - res[0].height - result[0].height - r[0].height - 40
                        })

                    } else {
                        this.setData({
                            height: clientHeight - result[0].height - r[0].height - 40
                        })
                    }
                    console.log(clientHeight, result[0].height, r[0].height);


                })
            })
        })
    },
    btnShow() {
        this.setData({
            show: !this.data.show
        })
        this.getcart()
    },
    leftList: function () {
        var that = this;
        var nid = this.data.worke.id;

        app.api.useApi(app.globalData.baseAppUrl + "api/good", {
            network_id: nid,
        }, "get").then(function (res) {
            console.log(res);
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.status,
                })
            } else {
                var data = res.message.data;
                var shop = [];
                for (var index in data) {
                    shop[data[index].id] = data[index].goods
                }


                that.setData({
                    navList: res.message.data,
                    shoppingList: res.message.data[0].goods,
                    shop: shop
                })
            }

            wx.hideLoading();

        }).catch(function (err) {
            console.log(222);
        })
    },
    location() {
       
        wx.openLocation({
            latitude: Number(this.data.worke.lat),
            longitude:  Number(this.data.worke.lng),
        });
    },


    /**
     * @name获取网点
     */
    getNwetwork(network_id){
        var that=this;
        wx.getLocation({
            type: "wgs84",
            success: function (res) {
              // console.log('getLocation:success', res)
              var latitude = res.latitude
              var longitude = res.longitude
                app.api.useApi(app.globalData.baseAppUrl+'api/network/desc',{
                    lat: latitude,
                    lng: longitude,
                    network_id:network_id>0?network_id:wx.getStorageSync('nid')
                }).then((res)=>{
                    if(res.code!=200){
                        wx.showToast({
                        title: res.message.msg,
                        })
                    }else{
                        console.log(res.message.data);
                        that.setData({
                            worke:res.message.data
                        });
                        this.getcart();
                    }

                
                }).catch((err)=>{
                    console.log(err.message)
                })
            }
        })
    }

})