
let Parse = getApp().Parse;
const company = getApp().globalData.company
Page({

    /**
     * 页面的初始数据
     */
    data: {
        scrollTops: 0, // 要滚动的高度
        tabCur: 0, // 当前项
        rightCur: 0, // 用于实现左边联动右边
        cates: [],

        countMap: {},
        totalPrice: 0,
        totalCount: 0,
        tradeNo: "",
        show: false
    },

    onLoad: async function (options) {
        console.log(options)
        let storeid = options.storeid
        let tableid = options.tableid
        let active = options.active
        let desc = options.desc
        this.setData({
            storeid: storeid,
            tableid: tableid,
            active: active,
            desc: desc
        })
        await this.getCategory(storeid)
    },
    async getCategory(storeid) {
        let Category = new Parse.Query('Category')
        Category.notEqualTo('isDeleted', "true")
        Category.equalTo('company', company)
        Category.equalTo('store', storeid)
        Category.equalTo('type', 'catering')
        Category.ascending('index')
        let cates = await Category.find()
        if (cates && cates.length > 0) {
            let cateJSON = []
            cates.forEach(c => {
                cateJSON.push(c.toJSON())
            });
            this.setData({
                cates: cateJSON
            })
            await this.getFoodSet(storeid)
        }
    },

    async getFoodSet(storeid) {
        let FoodSet = new Parse.Query('Food')
        FoodSet.equalTo('store', storeid)
        FoodSet.equalTo('company', company)
        FoodSet.ascending('price')
        FoodSet.limit(200)
        let foodList = await FoodSet.find()
        console.log(foodList, this.data.cates)
        let countMap = {}
        if (foodList && foodList.length > 0) {
            let cates = this.data.cates
            cates.forEach(c => {
                c.foodList = []
                foodList.forEach(f => {
                    let fJSON = f.toJSON()
                    if (fJSON.category.objectId == c.objectId) {
                        c.foodList.push(fJSON)
                    }
                })

            })
            console.log(cates, countMap)
            this.setData({
                cates: cates,
            })
        }
    },

    discount(e) {
        let food = e.currentTarget.dataset.food
        if (this.data.countMap[food.objectId] == 0) {
            return
        }
        let count = this.data.countMap[food.objectId] ? this.data.countMap[food.objectId] - 1 : 0
        let tem = `countMap.${food.objectId}`
        let price = food.price
        this.setData({
            [tem]: count,
            totalCount: this.data.totalCount - 1,
            totalPrice: Number((this.data.totalPrice - price).toFixed(2))
        })
    },

    addcount(e) {
        let food = e.currentTarget.dataset.food
        let count = this.data.countMap[food.objectId] ? this.data.countMap[food.objectId] + 1 : 1
        let price = food.price
        let tem = `countMap.${food.objectId}`
        this.setData({
            [tem]: count,
            totalCount: this.data.totalCount + 1,
            totalPrice: Number((this.data.totalPrice + price).toFixed(2))
        })
        console.log(this.data.countMap)
    },

    tabNav(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index)
        this.setData({
            tabCur: index,
            rightCur: index,
            // 实现左边自动滑动到某个位置 4表示自动滑动到 第五项 （4为索引值）
            // scrollTops: (index - 4) * 50
        })
    },
    /**
     * 滑动右边对应左边菜单切换
     * 1、拿到该元素的高度，设定它的top和bottom
     * 2、判断滑动的距离是否大于 设定的top并小于设定的bottom，然后对应左边菜单的滑动
     */
    scrollLink(e) {
        let list = this.data.cates
        let itemHeight = 0;
        for (let i = 0; i < list.length; i++) {
            //拿到每个元素
            let els = wx.createSelectorQuery().select("#scroll-" + i);
            els.fields({
                size: true
            }, function (res) {
                if (res) {
                    list[i].top = itemHeight;
                    itemHeight += res.height;
                    list[i].bottom = itemHeight
                }
            }).exec()
        }
        console.log(list)
        this.setData({
            list
        })
        // 拿到滚动的高度
        let scrollTop = e.detail.scrollTop;
        console.log(scrollTop)
        for (let i = 0; i < list.length; i++) {
            if (scrollTop > list[i].top && scrollTop + 675 < list[i].bottom) {
                this.setData({
                    tabCur: i,
                    scrollTops: (i - 4) * 50
                })
                return false
            }
        }
    },


    async toSubmit() {
        console.log(this.data.totalCount, this.data.totalPrice)
        if (!this.data.totalPrice || !this.data.totalCount) {
            return
        }
        let now = new Date()
        let user = Parse.User.current()
        let tradeNo = "C" +
            String(now.getFullYear()) +
            (now.getMonth() + 1) +
            now.getDate() +
            now.getHours() +
            now.getMinutes() +
            now.getSeconds() +
            Math.random().toString().slice(-6); //生成六位随机数
        let specMapArr = Object.keys(this.data.countMap)
        let foods = []
        specMapArr.forEach(id => {
            if (this.data.countMap[id]) {
                foods.push({
                    __type: "Pointer",
                    className: "Food",
                    objectId: id
                })
            }
        })
        let FoodOrder = Parse.Object.extend('FoodOrder')
        let foodOrder = new FoodOrder()
        foodOrder.set('totalPrice', this.data.totalPrice)
        foodOrder.set('tradeNo', tradeNo)
        foodOrder.set('state', '100')
        foodOrder.set('type', "meal")
        foodOrder.set('isPay', false)
        foodOrder.set('merber', Number(this.data.active))
        foodOrder.set('foods', foods)
        foodOrder.set('specMap', this.data.countMap)
        foodOrder.set('user', {
            __type: "Pointer",
            className: "_User",
            objectId: user.id
        })
        foodOrder.set('company', {
            __type: "Pointer",
            className: "Company",
            objectId: company
        })
        foodOrder.set('store', {
            __type: "Pointer",
            className: "ShopStore",
            objectId: this.data.storeid
        })
        foodOrder.set('table', {
            __type: "Pointer",
            className: "TableNumber",
            objectId: this.data.tableid
        })
        console.log(1111)
        let order = await foodOrder.save()
        if (order && order.id) {
            this.setData({
                order: order,
                tradeNo: tradeNo,
                show: true
            })
        }
    },
    async acceptResult(e) {
        let { activeOrder } = this.data
        let that = this
        let {
            params,
            no
        } = e.detail;
        that.setData({
            show: false
        })
        try {
            if (params == "ok") {

                let order = this.data.order
                order.set('state', '400')
                order.set('isPay', true)
                await order.save()
                wx.showToast({
                    title: '购买成功',
                    icon: 'none',
                    image: '',
                    duration: 1500,
                    mask: false,
                });
                wx.navigateBack({
                    delta: 2,
                })
            } else {
                wx.showToast({
                    title: '支付失败，取消订单',
                    icon: 'none',
                    image: '',
                    duration: 1500,
                    mask: false,
                });
            }
        } catch (error) {
            console.log(error)
            wx.showToast({
                title: "支付失败",
                icon: "error",
                duration: 1500,
            });
            wx.hideLoading()
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})