let Parse = getApp().Parse;
const company = getApp().globalData.company
const util = require('../../../../../utils/util.js')
const dateF = require('../../../../../utils/date')
const req = require('../../../../../utils/request')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        time: null,
        store: null,
        merchant: null,
        totalCount: 0,
        todayCount: 0,
        totalPrice: 0,
        todayPrice: 0,
        withdraw: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)
        var TIME = util.formatTime(new Date()); //当前时间
        console.log(TIME);
        let time = dateF.formatTime("YYYY-mm-dd", TIME)
        this.setData({
            time: time
        });

        let merchant = wx.getStorageSync('merchant'); //用户
        this.setData({ merchant: merchant })
        if (!merchant) {
            wx.redirectTo({
                url: '/nova-tourism/pages/my/merchant/login/index'
            });
        }
        this.getShopStore()
    },


    async getShopStore() {
        let ShopStore = new Parse.Query('ShopStore')
        ShopStore.equalTo('company', company)
        ShopStore.equalTo('user', this.data.merchant.objectId)
        let shopStore = await ShopStore.first()
        if (shopStore && shopStore.id) {
            let id = shopStore.toJSON().objectId
            this.setData({
                store: shopStore.toJSON()
            })
            console.log(this.data.store, 11111);
            await this.getShopOrder(id)
            await this.getTodayOrder(id)
        } else {
            wx.setStorageSync('store', undefined)
            wx.setStorageSync('merchant', undefined)
        }
    },
    async getShopOrder(id) {

        let sql = ''
        if (this.data.store.type == 'stay') {
            sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "RoomOrder"
           where "company" = '${company}' and "shopStore" = '${id}' and "isPay" = true 
           group by "shopStore"`
        } else {
            sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "ShopOrder"
            where "company" = '${company}' and "shopStore" = '${id}' and "status" <> 100
            group by "shopStore"`
        }
        let data = await req.customSQL(sql)
        console.log(data)
        if (data && data.length > 0) {
            this.setData({
                totalCount: data[0].count,
                totalPrice: data[0].totalPrice,
            })
        }
        await this.getWithdraw()
    },

    async getWithdraw() {
        let sql = `select sum("count") as "withdraw" from "UserAgentWithdraw"
        where "company" = '${company}' and "user" = '${this.data.merchant.objectId}' 
        group by "user"`

        let data = await req.customSQL(sql)
        console.log(data)
        if (data && data.length > 0) {
            this.setData({
                withdraw: data[0].withdraw,
                earnings: (this.data.totalPrice - data[0].withdraw).toFixed(2)
            })
        } else {
            this.setData({
                earnings: this.data.totalPrice
            })
        }
        console.log(this.data.earnings)
    },

    async getTodayOrder(id) {
        var TIME = util.formatTime(new Date()); //当前时间
        console.log(TIME);
        let time = dateF.formatTime("YYYY-mm-dd 00:00:10", TIME)
        console.log(time);
        let sql = ''
        if (this.data.store.type == 'stay') {
            sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "RoomOrder"
           where "company" = '${company}' and "shopStore" = '${id}' and "isPay" = true and "createdAt" > '${time}'
           group by "shopStore"`
        } else {
            sql = `select count("objectId") as "count", sum("price") as "totalPrice"  from "ShopOrder"
            where "company" = '${company}' and "shopStore" = '${id}' and "status" <> 100 and "createdAt" > '${time}'
            group by "shopStore"`
        }
        let data = await req.customSQL(sql)
        if (data && data.length > 0) {
            this.setData({
                todayCount: data[0].count,
                todayPrice: data[0].totalPrice,
            })
        }

    },

    orderlist() {
        let storeId = this.data.store.objectId
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/order-list/index?storeId=' + storeId
        });
    },
    order2list() {
        let storeId = this.data.store.objectId
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/order2-list/index?storeId=' + storeId
        });
    },
    order3list() {
        let storeId = this.data.store.objectId
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/order3-list/index?storeId=' + storeId
        });
    },
    goods() {
        let id = this.data.store.objectId
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/goods/index?id=' + id
        });

    },

    logout() {
        wx.showModal({
            title: '确认要退出吗？',
            showCancel: true,
            success(res) {
                if (res.confirm) {
                    wx.removeStorageSync('merchant')
                    wx.removeStorageSync('store')
                    wx.navigateTo({
                        url: '/nova-tourism/pages/index/index'
                    })
                } else {

                }
            }
        })
    },
    package() {

        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/package/index'
        });

    },
    dishes() {
        let id = this.data.store.objectId
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/dishes/index?id=' + id
        });

    },
    tables() {
        let id = this.data.store.objectId
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/tables/index?id=' + id
        });

    },
    category() {
        let id = this.data.store.objectId
        let type = this.data.store.type
        wx.navigateTo({
            url: `/nova-tourism/pages/my/merchant/merchant-home/category/index?id=${id}&&type=${type}`
        });

    },
    roommanage() {
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/room-manage/index'
        });

    },
    account() {
        wx.navigateTo({
            url: '/nova-tourism/pages/my/merchant/merchant-home/account/index'
        });

    },

    comments() {
        switch (this.data.store.type) {
            case 'stay':
                wx.navigateTo({
                    url: '/nova-tourism/pages/my/merchant/comments/hotel/index'
                });
                break;
            case 'catering':
                wx.navigateTo({
                    url: '/nova-tourism/pages/my/merchant/comments/setmeal/index'
                });
                break;
            case 'shop':
                wx.navigateTo({
                    url: '/nova-tourism/pages/my/merchant/comments/setmeal/index'
                });
                break;
            default:
                break;
        }

    },


    async codeVerify() {
        console.log(this.data.store.type);
        let that = this
        wx.scanCode({
            success(res) {
                let content = res.result
                console.log(content)
                let code1 = content.match(/\id=(.*)/)[1]
                console.log(code1);
                switch (that.data.store.type) {
                    case 'stay':
                        wx.navigateTo({
                            url: `/nova-tourism/pages/my/merchant/code-verify/index?id=${code1}`
                        });
                        break;
                    case 'catering':
                        wx.navigateTo({
                            url: `/nova-tourism/pages/shop-admin/index?id=${code1}`
                        });
                        break;
                    case 'shop':
                        wx.navigateTo({
                            url: `/nova-tourism/pages/shop-admin/index?id=${code1}`
                        });
                        break;
                    default:
                        break;
                }
                // wx.navigateTo({
                //     url: `/nova-tourism/pages/my/merchant/code-verify/index?id=${res.id}`
                // });
            },
            fail(err) {
                console.log(err)
                wx.showToast({
                    title: '扫码失败，请确认二维码信息正确',
                    icon: 'none'
                })
            }
        })
    },
    toWithdraw() {
        let id = this.data.store.storeName
        wx.navigateTo({
            url: `/nova-tourism/pages/my/merchant/merchant-home/store-withdraw/index?earnings=${this.data.earnings}&&id=${id}`,
        })
    },



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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})