let {
    statusBarHeight,
    screenHeight,
    safeArea: {
        bottom
    }
} = wx.getSystemInfoSync();
statusBarHeight = Math.abs(statusBarHeight)
let custom = wx.getMenuButtonBoundingClientRect();
let customBarHeight = custom.bottom + custom.top - statusBarHeight;
customBarHeight = Math.abs(customBarHeight)
const Parse = getApp().Parse;
const company = getApp().globalData.company
// nova-tourism/pages/shop/index.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        statusBarHeight,
        customBarHeight,
        screenHeight,
        bottom,
        user: null,
        value: '',
        store: null,
        category: null,
        activeItem: 'all',
        goods: [],
        loading: true,
        cartLoading: false,
        show: false,
        allCheck: true,
        shopCart: [],
        banners:[]
    },



    lifetimes: {
        created() { },
        attached() {
            // this.getBindStore()
            this.getCategory()
            this.getGoods()
        },
    },
    //监听页面数据加载
    pageLifetimes: {
        show: function () {
            this.getBindStore()
        }
    },
    /**
     * 组件的方法列表
     */
    methods: {
        async refresh(){
            await this.getBindStore()
            this.getCategory()
            this.getGoods()
        },
        async getBanner() {
            let Banner = new Parse.Query('Banner')
            Banner.notEqualTo('isDeleted', "true")
            Banner.equalTo('company', company)
            Banner.equalTo('isEnabled', "true")
            Banner.equalTo('type','shop')
            let banner = await Banner.find()
            if (banner && banner.length > 0) {
                let listJSON = []
                banner.forEach(c => {
                listJSON.push(c.toJSON())
                })
                this.setData({
                banner: listJSON
                })
            }
        },
        async getmy() {
            // let userLogin = wx.getStorageSync("userLogin");
            // if (userLogin == "") {
            //     login.loginNow();
            //     return;
            // }
            let uid = Parse.User.current().id
            let ShopOrder = new Parse.Query('_User')
            let shopOrder = await ShopOrder.get(uid)
            this.setData({
                user: shopOrder.toJSON()
            })
        },
        // 获取当前绑定的店铺
        getBindStore: async function () {
            let storeID = wx.getStorageSync('storeID');
            let Store = new Parse.Query('ShopStore')
            if (storeID) {
                let store = await Store.get(storeID)
                let storeJSON = store.toJSON()
                this.setData({
                    store: storeJSON
                })
            } else {
                return wx.showToast({
                    title: '快去选择一个店铺吧~',
                    icon: 'none'
                })
            }
        },
        // 跳转至选择店铺页面
        selectStore(e) {
            let store = e.target.dataset.store
            wx.navigateTo({
                url: '/nova-tourism/pages/shop/select-store/index?store=' + store,
            });
        },
        // 获取所有商品分类
        getCategory: async function () {
            let Category = new Parse.Query('Category')
            Category.notEqualTo('isDeleted', "true")
            Category.equalTo('company', company)
            Category.equalTo('type', 'shop')
            Category.descending('createdAt')
            let category = await Category.find()
            let list = []
            category.forEach(val => {
                val = val.toJSON()
                list.push(val)
            })
            this.setData({
                category: list
            })
        },
        // 点击分类添加激活类名,以及显示分类下的商品
        changeCate: async function (e) {
            this.setData({
                loading: true,
                goods: []
            })
            let id = e.currentTarget.dataset.id
            this.setData({
                activeItem: id,
            })
            this.getGoods()
        },
        // 获取商品
        getGoods: async function (value) {
            let storeID = wx.getStorageSync('storeID');
            let Goods = new Parse.Query('ShopGoods')
            Goods.notEqualTo('isDeleted', "true")
            Goods.equalTo('company', company)
            if (this.data.activeItem !== 'all' && !value) {
                Goods.equalTo('category', this.data.activeItem)
            }
            Goods.equalTo('shopStore', storeID)
            Goods.equalTo('status', true)
            Goods.equalTo('type', 'shop')
            Goods.include('category')
            Goods.descending('createdAt')
            if(value) {
                Goods.contains('name', value)
            }
            
            Goods.limit(10)
            Goods.skip(this.data.goods.length)
            let goods = await Goods.find()
            let list = this.data.goods
            goods.forEach(val => {
                val = val.toJSON()
                list.push(val)
            })
            this.setData({
                loading: false,
                goods: list
            })
        },
        // 根据商品objectId获取库存
        getTotal: async function (ID) {
            let Goods = new Parse.Query('ShopGoods')
            let goods = await Goods.get(ID)
            return goods.toJSON().total
        },
        // 将商品添加至购物车,同时该商品显示的库存减少
        addCount(e) {
            let store = wx.getStorageSync('storeID');
            if (!store) {
                return wx.showToast({
                    title: '请先绑定店铺后购买商品！',
                    icon: 'none',
                    duration: 1500,
                    mask: false,
                });
            }
            let index = e.currentTarget.dataset.index
            let goods = this.data.goods[index]
            let shopCart = this.data.shopCart
            goods.total--
            shopCart.push(goods)
            let Goods = this.data.goods
            Goods[index] = goods
            this.setData({
                goods: Goods,
                shopCart: shopCart
            })
        },
        // 查看购物车
        checkCart() {
            let store = wx.getStorageSync('storeID');
            if (!store) {
                return wx.showToast({
                    title: '请先绑定店铺后购买商品！',
                    icon: 'none',
                    duration: 1500,
                    mask: false,
                });
            }
            this.setData({
                show: true,
            })
            let shopGoods = this.data.shopCart
            let list = []
            let result = shopGoods.reduce((init, current, index) => {
                list[current.objectId] ? '' : list[current.objectId] = true && init.push(current)
                return init
            }, [])
            let obj = {}
            for (let i = 0; i < shopGoods.length; i++) {
                if (shopGoods[i].objectId in obj) {
                    obj[shopGoods[i].objectId] = obj[shopGoods[i].objectId] + 1
                } else {
                    obj[shopGoods[i].objectId] = 1
                }
            }
            for (let k in obj) {
                let index = result.findIndex(val => {
                    return val.objectId == k
                })
                result[index].check = false
                result[index].open = true
                result[index].count = obj[k]
                result[index].totalPrice = (obj[k] * result[index].price).toFixed(2)
            }
            this.setData({
                orderGoods: result
            })
            this.checkAll()
        },
        // 点击勾选商品
        checkItem(e) {
            let index = e.currentTarget.dataset.index
            let orderGoods = this.data.orderGoods
            let totalPrice = this.data.totalPrice
            orderGoods[index].check = !orderGoods[index].check
            if (orderGoods[index].check) {
                totalPrice = parseFloat(totalPrice) + parseFloat(orderGoods[index].totalPrice)
                totalPrice = parseFloat(totalPrice).toFixed(2)
            } else {
                totalPrice = parseFloat(totalPrice) - parseFloat(orderGoods[index].totalPrice)
                totalPrice = parseFloat(totalPrice).toFixed(2)
            }
            let result = orderGoods.filter(val => {
                return val.check !== true
            })
            if (result.length > 0) {
                this.setData({
                    allCheck: false
                })
            } else {
                this.setData({
                    allCheck: true
                })
            }
            this.setData({
                totalPrice: totalPrice,
                orderGoods: orderGoods
            })
        },
        // 步进器，单件商品的购买数量增减处理
        onChange: async function (e) {
            let num = e.detail
            let index = e.currentTarget.dataset.index
            let orderGoods = this.data.orderGoods
            let total = await this.getTotal(orderGoods[index].objectId)
            if ((total - num) < 0) {
                wx.showToast({
                    title: '库存不足！',
                    icon: 'none',
                    duration: 1500,
                });
                orderGoods[index].open = false
                num--
            } else {
                orderGoods[index].open = true
            }
            orderGoods[index].count = num
            orderGoods[index].totalPrice = (orderGoods[index].count * orderGoods[index].price).toFixed(2)
            this.setData({
                orderGoods: orderGoods
            })
            this.checkAll()
        },
        // 点击加号按钮触发
        plus(e) {
            let index = e.currentTarget.dataset.index
            let orderGoods = this.data.orderGoods
            orderGoods[index].total--
            // 复制一条与该商品相同的订单数据
            let shopCart = this.data.shopCart
            let cartIndex = shopCart.findIndex(val => {
                return val.objectId == orderGoods[index].objectId
            })
            let goods = shopCart[cartIndex]
            shopCart.push(goods)
            this.setData({
                shopCart: shopCart,
                orderGoods: orderGoods
            })
        },

        //  搜索
        search() {
            console.log(this.data.value)
            if(!this.data.value) {
                return
            }
            this.setData({
                loading: true,
                goods: []
            })
            this.getGoods(this.data.value)
        },

        // 点击减号按钮触发
        minus(e) {
            // 将减少的商品数量加回显示的库存数量
            let index = e.currentTarget.dataset.index
            let orderGoods = this.data.orderGoods
            orderGoods[index].total++
            // 移除对应shopCart数组中一条数据
            let shopCart = this.data.shopCart
            let cartIndex = shopCart.findIndex(val => {
                return val.objectId == orderGoods[index].objectId
            })
            shopCart.splice(cartIndex, 1)
            this.setData({
                shopCart: shopCart,
                orderGoods: orderGoods
            })
        },
        // 删除当前滑动的订单商品
        delete(e) {
            wx.showModal({
                title: '删除商品',
                content: '确认删除该件商品吗',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确定',
                confirmColor: '#e42929',
                success: async (result) => {
                    if (result.confirm) {
                        let index = e.currentTarget.dataset.index
                        let id = e.currentTarget.dataset.id
                        let totalPrice = this.data.totalPrice
                        let orderGoods = this.data.orderGoods
                        let shopCart = this.data.shopCart
                        let goods = this.data.goods
                        shopCart = shopCart.filter(val => {
                            return val.objectId !== id
                        })
                        let goodsIndex = goods.findIndex(val => {
                            return val.objectId == id
                        })
                        goods[goodsIndex].total += orderGoods[index].count
                        totalPrice = parseFloat(totalPrice) - parseFloat(orderGoods[index].totalPrice)
                        totalPrice = parseFloat(totalPrice).toFixed(2)
                        orderGoods.splice(index, 1)
                        this.setData({
                            totalPrice: totalPrice,
                            goods: goods,
                            shopCart: shopCart,
                            orderGoods: orderGoods
                        })
                        this.checkAll()
                    }
                },
            });

        },
        // 点击全选按钮
        checkAll(e) {
            // 1. 选中全部商品
            // 2. 计算总价
            let orderGoods = this.data.orderGoods
            if (e) {
                this.setData({
                    allCheck: !this.data.allCheck
                })
            }
            if (this.data.allCheck) {
                let totalPrice = 0
                orderGoods.forEach(val => {
                    val.check = true
                    totalPrice += parseFloat(val.totalPrice)
                })
                this.setData({
                    totalPrice: totalPrice,
                    orderGoods: orderGoods
                })
            } else if (e && !this.data.allCheck) {
                orderGoods.forEach(val => {
                    val.check = false
                })
                this.setData({
                    totalPrice: 0,
                    orderGoods: orderGoods
                })
            }
        },
        // 点击删除按钮
        onDelete() {
            wx.showModal({
                title: '删除订单',
                content: '确认删除这些商品吗',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确定',
                confirmColor: '#e42929',
                success: (result) => {
                    if (result.confirm) {
                        if (this.data.allCheck) {
                            // 全选之后的删除
                            this.setData({
                                totalPrice: 0,
                                goods: [],
                                shopCart: [],
                                orderGoods: []
                            })
                            this.getGoods()
                        } else {
                            // 选中部分删除
                            let totalPrice = this.data.totalPrice
                            let shopCart = this.data.shopCart
                            let orderGoods = this.data.orderGoods
                            let goods = this.data.goods
                            let list = orderGoods.filter(val => {
                                return val.check == true
                            })
                            list.forEach(val => {
                                shopCart = shopCart.filter(item => {
                                    return item.objectId !== val.objectId
                                })
                                let index = goods.findIndex(value => {
                                    return value.objectId == val.objectId
                                })
                                goods[index].total += val.count
                                totalPrice = parseFloat(totalPrice) - parseFloat(val.totalPrice)
                                totalPrice = parseFloat(totalPrice).toFixed(2)
                            })
                            orderGoods = orderGoods.filter(val => {
                                return val.check !== true
                            })
                            this.setData({
                                totalPrice: totalPrice,
                                goods: goods,
                                shopCart: shopCart,
                                orderGoods: orderGoods
                            })
                        }
                    }
                },
            });
        },
        // 点击结算按钮
        submit() {
            // 生成一条随机订单编号
            let orderNum = "C" +
                String(new Date().getFullYear()) +
                (new Date().getMonth() + 1) +
                new Date().getDate() +
                new Date().getHours() +
                new Date().getMinutes() +
                new Date().getSeconds() +
                Math.random().toString().slice(-6); //生成六位随机数
            // 创建specMap对象以及tagetObject数组
            let specMap = {}
            let targetObject = []
            let orderGoods = this.data.orderGoods
            orderGoods = orderGoods.filter(val => {
                return val.check == true
            })
            if (orderGoods.length == 0) {
                return
            }
            orderGoods.forEach(val => {
                specMap[val.objectId] = val.count
                let option = {
                    '__type': 'Pointer',
                    'className': 'ShopGoods',
                    'objectId': val.objectId
                }
                targetObject.push(option)
            })
            // 生成一条Order记录
            let Order = Parse.Object.extend('Order')
            let order = new Order()

            order.set('orderNum', orderNum)
            order.set('company', {
                '__type': 'Pointer',
                'className': 'Company',
                'objectId': company
            })
            order.set('store', {
                '__type': 'Pointer',
                'className': 'ShopStore',
                'objectId': wx.getStorageSync('storeID')
            })
            order.set('specMap', specMap)
            order.set('totalPrice', this.data.totalPrice)
            order.set('user', {
                '__type': 'Pointer',
                'className': '_User',
                'objectId': Parse.User.current().id
            })
            order.set('targetObject', targetObject)
            order.set('status', '100')
            order.set('type', 'shop')
            order.set('isPay', false)

            order.save().then((res) => {

                let order = res.toJSON()
                wx.navigateTo({
                    url: '/nova-tourism/pages/shop/order/index?id=' + order.objectId,
                    success: () => {
                        this.setData({
                            totalPrice: 0,
                            goods: [],
                            shopCart: [],
                            orderGoods: []
                        })
                        this.onClose()
                    }
                });
            })

            // 跳转至订单支付页面
        },
        // 关闭购物车
        onClose() {
            this.setData({
                show: false,
            })
            this.getGoods()
        },
        // 库存不足
        onTips() {
            wx.showToast({
                title: '商品库存不足',
                icon: 'none',
                image: '',
                duration: 1500,
                mask: false,
            });
        },
        // 当容器滑动至底部时，加载商品数据
        scrolltolower: function () {
            this.getGoods()
        }
    }
})