const Parse = getApp().Parse;
const company = getApp().globalData.company
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        realName: '',
        mobile: '',
        address: '',
        id: '',
        order: [],
        goods: [],
        show: false,
        activeColor:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        this.setData({
            activeColor:getApp().globalData.activeColor || '#229293'
        })
        let id = options.id
        this.setData({
            id
        })
        await this.getOrder()
        await this.getGoods()
    },

    // 根据订单id获取当前订单
    getOrder: async function () {
        let Order = new Parse.Query('Order')
        let order = await Order.get(this.data.id)
        let orderJSON = order.toJSON()
        orderJSON.totalPrice = parseFloat(orderJSON.totalPrice).toFixed(2)
        orderJSON.totalPrice = parseFloat(orderJSON.totalPrice)
        let { info } = orderJSON
        if (info) {
            let { name, mobile, address } = info
            this.setData({
                realName: name,
                mobile: mobile,
                address: address
            })
        }
        this.setData({
            order: orderJSON,
        })
    },

    // 根据订单中specMap字段获取商品数据
    getGoods: async function () {
        let { specMap } = this.data.order
        let list = []
        for (let k in specMap) {
            let goods = await this.getShopGoods(k)
            if (goods.total < specMap[k] && this.data.order.status == '100') {
                wx.showToast({
                    title: goods.name + '商品库存不足, 已自动调整购买数量',
                    icon: 'none',
                    duration: 1500,
                });
                goods.count = goods.total
            } else if (!goods.total && this.data.order.status == '100') {
                return wx.showToast({
                    title: goods.name + '商品库存不足, 已自动移出订单',
                    icon: 'none',
                    duration: 1500,
                });
            } else {
                goods.count = specMap[k]
            }
            goods.price = parseFloat(goods.price).toFixed(2)
            goods.originalPrice = parseFloat(goods.originalPrice).toFixed(2)
            list.push(goods)
        }
        this.setData({
            goods: list
        })
    },

    // 获取ShopGoods商品数据
    getShopGoods: async function (ID) {
        let ShopGoods = new Parse.Query('ShopGoods')
        let shopGoods = await ShopGoods.get(ID)
        let shopGoodsJSON = shopGoods.toJSON()
        return shopGoodsJSON
    },

    // 调起支付弹窗
    payMoney() {
        let reg_user = /^[\u4e00-\u9fa5]{2,4}$/;
        let reg_tel = /^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/
        if (!reg_tel.test(this.data.mobile)) {
            return wx.showToast({
                title: '请正确填写手机号码！',
                icon: 'none'
            })
        }
        if (!reg_user.test(this.data.realName)) {
            return wx.showToast({
                title: '请正确填写姓名！',
                icon: 'none'
            })
        }
        if (!this.data.realName || !this.data.mobile || !this.data.address) {
            return wx.showToast({
                title: '请检查配送信息填写，不得为空！',
                icon: 'none',
            });
        }
        let money = this.data.order.totalPrice
        this.setData({
            tradeNo:this.data.order.orderNum,
            show: true,
            money: money
        })
    },

    // 支付当前订单
    acceptResult: async function (e) {
        // 同时储存一条AccountLog记录
        let user = Parse.User.current()
        let userJSON = user.toJSON()
        // 1. 查询Account账号
        let Account = new Parse.Query('Account')
        Account.equalTo('company', company)
        Account.equalTo('user', userJSON.objectId)
        let account = await Account.first()
        // 获取当前订单的Parse对象
        let Order = new Parse.Query('Order')
        let order = await Order.get(this.data.id)
        let {
            params,
            no
        } = e.detail;
        this.setData({
            show: false
        })
        try {
            if (params == "ok") {
                // 支付完成后将订单状态改变
                order.set('info', {
                    'name': this.data.realName,
                    'mobile': this.data.mobile,
                    'address': this.data.address
                })
                order.set("status", '200')
                order.set("isPay", true)
                order.save().then(() => {
                    // 减去购买量的店铺商品库存
                    let { specMap } = this.data.order
                    for (let k in specMap) {
                        this.subGoodsStock(k, specMap[k])
                    }
                    let AccountJSON = account.toJSON()
                    let AccountLog = Parse.Object.extend('AccountLog')
                    let accountLog = new AccountLog()

                    accountLog.set('fromAccount', {
                        '__type': 'Pointer',
                        'className': 'Account',
                        'objectId': AccountJSON.objectId
                    })
                    accountLog.set('orderType', 'shopgoods-balance')
                    accountLog.set('assetType', 'balance')
                    accountLog.set('desc', '余额支付')
                    accountLog.set('fromName', userJSON.nickname)
                    accountLog.set('orderNumber', this.data.order.orderNum)
                    accountLog.set('targetName', 'system')
                    accountLog.set('company', {
                        '__type': 'Pointer',
                        'className': 'Company',
                        'objectId': company
                    })
                    accountLog.set('assetCount', this.data.order.totalPrice)
                    accountLog.set('isVerified', false)

                    accountLog.save().then((res) => {
                        res.set('isVerified', true)
                        res.save().then(() => {
                            // 发送打印订单请求
                            this.printOrder()
                            // 返回上一级页面
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 1,
                                });
                            }, 300)
                            // 刷新数据
                            const Page = getCurrentPages();
                            const prePage = Page[Page.length - 2]
                            let store = prePage.selectComponent("#comp3")
                            store.data.goods = []
                            store.getmy()
                            store.getBindStore()
                            store.getCategory()
                            store.getGoods()
                        })
                    }).catch(error => {
                        wx.showToast({
                            title: "支付失败",
                            icon: "error",
                            duration: 1500,
                        });
                        wx.hideLoading()
                    })
                })
            } 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()
        }
    },

    // 打印订单的处理函数
    printOrder: async function() {
        // 获取打印设备终端编号
        let code = ''
        let query = new Parse.Query('PrintDevice')
        query.equalTo('company', '1AiWpTEDH9')
        let result = await query.first()
        if(result && result.id) {
            code = result.get('code')
        }
        // 处理订单商品数组
        let goods = this.data.goods
        let orders = []
        goods.forEach(val => {
            let item = {
                name: val.name,
                num: val.count,
                price: val.price
            }
            orders.push(item)
        })
        // 定义打印订单所需数据数组
        let data = {
            dev_code : code,
            cid: company,
            order_id: this.data.order.objectId,
            orderNumber: this.data.order.orderNum,
            price: this.data.order.totalPrice,
            orders: orders,
            name: this.data.realName,
            mobile: this.data.mobile,
            address: this.data.address,
        }
        console.log(data);
        // 发送打印请求
        wx.request({
            url: 'https://test.fmode.cn/api/print-dev/dev',
            data: data,
            header: {'content-type':'application/json'},
            method: 'POST',
            dataType: 'json',
            responseType: 'text',
            success: (result)=>{
                console.log('----订单打印成功----');
            },
            fail: ()=>{},
            complete: ()=>{}
        });
    },

    // 订单支付完成后减去当前店铺商品的库存
    subGoodsStock: async function (ID, num) {
        let ShopGoods = new Parse.Query('ShopGoods')
        let shopGoods = await ShopGoods.get(ID)
        let shopGoodsJSON = shopGoods.toJSON()
        shopGoods.set('total', shopGoodsJSON.total - num)
        shopGoods.set('sales', shopGoodsJSON.sales + num)
        shopGoods.save().then((res) => {
        })
    },

    // 订单退款
    refund: async function () {
        wx.showModal({
            title: '发起退款',
            content: '确认对该笔订单发起退款吗',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '确定',
            confirmColor: '#fe4a4a',
            success: async (result) => {
                if (result.confirm) {
                    // 将订单状态改变为 500
                    let Order = new Parse.Query('Order')
                    let order = await Order.get(this.data.order.objectId)

                    order.set('status', '500')

                    order.save().then(() => {
                        Toast.loading({
                            message: '提交申请...',
                            forbidClick: true,
                            onClose: () => {
                                this.setData({
                                    order: []
                                })
                                this.getOrder()
                            }
                        })
                    })
                }
            },
        });

    },



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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})