// pages/groupmeallist/submitOrder/submitOrder.js
import storeGoods from '../../../api/storeGoods'
const cache = require('../../../utils/cache.js');
import Activity from '../../../api/activity';
const user = require('../../../utils/user.js');
import base from '../../../utils/base'

const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderGoodList: [{}, {}, {}, {}],
        store: {},
        phone: '',
        storeWay: '',
        addressvaule: '',
        addressId: '',
        coupon: '',
        couponSn: '',
        hallFood: '',
        invoiceValue: '',
        invoiceId: '',
        hidden: true,
        inputValue: '',
        remark: '',




        showAllSku: false,
        isShowPannel: false,
        forSelectList: [],
        discoutTitle: '',
        couponSn: '',
        orderMode: '',
        discountPriceY: ''
    },
    //全部显示和收起
    handleFlodExtend() {
        this.setData({
            showAllSku: !this.data.showAllSku
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let coupon = options.coupon


        if (coupon != null) {
            let jsoncoupon = JSON.parse(coupon)
            this.setData({
                coupon: jsoncoupon,
                couponSn: jsoncoupon.sn
            })
        }


        let invoiceValue = options.invoiceValue
        let invoiceId = options.invoiceId
        if (invoiceValue != null && invoiceId != null) {
            this.setData({
                invoiceValue: invoiceValue,
                invoiceId: invoiceId
            })

        }

        let addressvaule = options.addressvalue
        let addressId = options.addressId
        if (addressvaule != null && addressId != null) {
            let address = {
                addressvaule: addressvaule,
                addressId: addressId
            }
            // 设置地址缓存
            cache.setaddress(address)

            this.setData({
                addressvaule: addressvaule,
                addressId: addressId

            })

        }

    },


    /**
     * 取消
     */
    cancel: function () {
        this.setData({
            hidden: true,
            inputValue: '',
            remark: '',
        });
    },


    /**
     * 提交
     */
    confirm: function (e) {
        let inputValue = e.detail.value
        this.setData({
            hidden: true,
            inputValue: inputValue,
            remark: inputValue,
        });
    },
    /**
     * 备注
     */
    getReason: function (e) {
        this.setData({
            inputValue: e.detail.value
        })
    },

    remarkShow() {
        this.setData({
            hidden: false,
            // inputValue: '',
            // remark: '',
        });
    },

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

    },
    listenInput(e) {
        this.setData({
            phone: e.detail.value

        })


    },
    // 提交订单
    submitOrder() {
        console.log("进入创建订单方法")
        let parms = {}
        if (!this.data.isValid) {
            app.showToast("购物车无商品")
            return
        }


        // parms={
        //     mobile:cache.getMobile(),
        //     storeId:cache.getStoreId(),
        //     couponSn:this.data.couponSn,
        //     dinnerType:this.data.storeWay,
        //     addressId:this.data.addressId,
        //     invoiceId:this.data.invoiceId,
        //     phone:this.data.phone,
        //     remark:this.data.remark
        // }
        storeGoods.creatOrder({
            mobile: cache.getMobile(),
            storeId: cache.getStoreId(),
            couponSn: this.data.couponSn,
            dinnerType: this.data.storeWay,
            addressId: this.data.addressId,
            invoiceId: this.data.invoiceId,
            phone: this.data.phone,
            remark: this.data.remark
        }).then(res => {
            if (res.code == 200 && res.data.state != -2) {
                // 唤起收银台
                this.goToPay(res.data)
            } else if (res.data.state != -2) {
                wx.redirectTo({
                    url: '/pages/userOrderList/userOrderList',
                })

            }
        }).catch(_ => {
            // this.setData({
            //     isShowPannel: true
            // })

            this.tapSex()
            console.log(_)
        })


    },
    tapSex:function(res){
        var that = this
        wx.showModal({
          title: '提示',
          content: '订单创建失败，确认之后返回购物栏',
          showCancel: false,
          confirmText:'确认',
          success(res){
        if(res.confirm){
                that.goToStoreGoods()
            }
          }
        })
    
    },
    
    goToPay(order) {
        const storeInfo = cache.getCurrStore()

        // console.log(user.getUserInfo().openid,)
        console.log(storeInfo)
        storeGoods.getPayParams({
            orderSn: order.orderSn,
            payCode: storeInfo.payCode,
            openId: Activity.getOpenId(),
            isOrderPayment: true,
            orderInfoPath: "../orderDetail/orderDetail?sn=" + order.orderSn,
            productDetailPath: "../storeGoods/storeGoods",   
        }).then(res => {
            if (res.code == 200) {
                this.rousePayment(res.data, order)
            }
        }).catch(_ => {
            console.log(_)
        })

    },
    rousePayment(payParam, order) {
        wx.requestOrderPayment({
            timeStamp: payParam.wxPrePay.timeStamp,
            package: payParam.wxPrePay.pack,
            nonceStr: payParam.wxPrePay.nonceStr,
            signType: payParam.wxPrePay.signType,
            paySign: payParam.wxPrePay.paySign,
            orderInfo:payParam.orderInfo,
            success: function (res) {
              //支付成功，跳转领取成功页面
              console.log("支付成功，跳到订单详情页面")
              storeGoods.getPayStatus(order.orderSn);
              app.showToast("支付成功")
              wx.redirectTo({
                url: '../orderDetail/orderDetail?sn=' + order.orderSn,
              })
            },
            fail: function (res) {
                console.log("未支付")
                app.showToast("支付失败")
                wx.redirectTo({
                    url: '../orderDetail/orderDetail?sn=' + order.orderSn,
                })
            }
          })
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let store = cache.getCurrStore();
        console.log(store)
        let storeWay = cache.getStoreWay();

        let address = cache.getaddress();
        if (address != null) {
            this.setData({
                addressvaule: address.addressvaule,
                addressId: address.addressId,
            })
        }
        if (store != null) {
            this.setData({
                store: store,
                storeWay: storeWay,
                hallFood: store.hallFood
            })

        }

        this.loadCartData();
        this.getUseConfirmOrderCoupon()


    },
    //发票列表
    gotoinvoice() {
        wx.redirectTo({
            url: '../invoicesList/invoicesList?way=' + 'order',
        })

    },
    // 自动获取手机号

    getPhone() {
        let phone = cache.getMobile()
        this.setData({
            phone: phone
        })


    },
    // 选择收货地址
    chooseAdress() {
        wx.redirectTo({
            url: '../address/address?isreturn=' + 'true',
        })

    },

    getUseConfirmOrderCoupon() {
        storeGoods.orderCouponForSelect({
            storeId: cache.getStoreId(),
            mobile: cache.getMobile(),
            // tableId: 1
        }).then(res => {
            if (res.code == 200) {
                this.setData({
                    forSelectList: res.data
                })
            }
        }).catch(_ => {
            // // this.setData({
            // //     isShowPannel: true
            // // })

            // this.tapSex()
            console.log(_)
        })
    },
    //选择卡券
    gotoselectcoupon() {
        wx.navigateTo({
            url: '../couponlist/couponlist',
        })

    },

    /**
     * 加载购物车数据
     */
    loadCartData() {
        storeGoods.getCartData(cache.getStoreId(), cache.getMobile(), null, this.data.couponSn, ).then(res => {
            if (res.code == 200) {
                this.cartDataMapToView(res.data)
            }
        }).catch(_ => {
            console.log(_)
        })
    },


    cartDataMapToView(data) {

        var isShowCartPannel = true;
        if (base.isEmpty(data.skuList) || data.skuList.length == 0) {
            isShowCartPannel = false
            data.totalPriceY = "0.00"
            data.totalNum = 0
        }
        // let skuList = data.skuList || []
        // skuList.forEach(sku => {
        //     if (!base.isEmpty(sku.specList)) {
        //         let specValueList = []
        //         sku.specList.forEach(spec => {
        //             specValueList.push(spec.specValue)
        //         })
        //         sku.specDes = specValueList.join("、")
        //     } else {
        //         sku.specDes = ""
        //     }
        //     sku.allFee = base.fenToYuan(sku.num * sku.price)
        //     sku.allOriFee = base.fenToYuan(sku.num * sku.oriPrice)
        // })


        this.setData({
            isValid: data.skuList.length > 0,
            skuList: data.skuList,
            areaName: data.areaName,
            tableCode: data.tableCode,
            totalNum: data.totalNum,
            totalOriPriceY: data.totalOriPriceY,
            totalPriceY: data.totalPriceY - data.discountPriceY,
            totalPrice: data.totalPrice,
            totalOriPrice: data.totalOriPrice,
            discountPriceY: data.discountPriceY
        })
    },
    // 详情和收起
    changeCollapseOrDetail: function (e) {
        let idx = e.currentTarget.dataset.idx;
        var that = this;
        that.data.skuList[idx].show = !that.data.skuList[idx].show
        that.setData({
            skuList: that.data.skuList
        });
        console.log("购物车详情");
        console.log(that.data.skuList);
    },

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

    },

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

    },

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

    },

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

    },

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

    }
})