/*
 * 本时生活
 */

Page({

    /**
     * 页面的初始数据
     */
    data: {
        rightId     : '',    //权益id
        welfareId   : '',    //活动id
        address     : '',    //默认地址
        allAddress  : '',    //收货地址列表
        detail      : '',    //权益详情
        amount      : '',    //总金额
        moreAmount  : '',    //产品金额
        platIndex   : 0,     //选择提交方式下标
        isdeliver   : -1,
        platformCp  : [],   //选择提交数组
        num         : 1,     //购买的数量
        content     : '',    //内容介绍
        notification: '',    //重要提示
        remark      : '',    //使用须知
        score       : '',    //应付总积分
        freight     : '',    //运费
        welfareType : '',    //权益类型
        noticeShow  : true, //须知显示状态
        addressShow : false, //收货地址显示
        payWayIndex : 0,
        unicomPay   : '' //是否有沃支付
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad (options) {
        this.setData({
            rightId  : options.right_id,
            welfareId: options.welfare_id,
            unicomPay: getApp().globalData.unicomPay
        })

        // 获取卡券列表
        this.couponInfo()
    },

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

    },

    /**
     * 卡券列表
     */
    couponInfo() {
        wx.$api.user.washcarBuy(this.data.welfareId, this.data.rightId, this.data.num, this.data.address.id, this.data.isdeliver).then(res=>{
            let obj    = res.data.detail.express
            let defGet = res.data.detail.def_get
            let arr    = new Array
            arr = Object.keys(obj).map(val=>{
                return { ...obj[val], ...{key: val} }
            })

            if(this.data.isdeliver == -1){
                if(res.data.detail.type == 'physical') {
                    this.setData({
                        isdeliver : res.data.detail.def_get
                    })
                }
                if(res.data.detail.type == 'virtual') this.setData({isdeliver : 1})
            }

            this.setData({
                address     : res.data.address,
                allAddress  : res.data.all_address,
                detail      : res.data.detail,
                num         : res.data.qty,
                freight     : res.data.freight,
                platformCp  : arr,
                amount      : res.data.total,
                moreAmount  : res.data.amount,
                score       : res.data.score,
                welfareType : res.data.type,
                remark      : res.data.detail.remark.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'),
                content     : res.data.detail.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
            })
        }).catch(err=>{})
    },

    /**
     * 须知展开收起状态
     */
    noticeTap() {
        this.setData({
            noticeShow : !this.data.noticeShow
        })
    },

    /**
     * 收货地址弹出
     */
    addressTap() {
        this.setData({
            addressShow : !this.data.addressShow
        })
    },

    /**
     * 选择收货地址
     */
    selectAddress(e){
        let new_addressId = e.currentTarget.dataset.id,
            addressId     = this.data.address.id
        if (new_addressId != addressId) {
            this.setData({
                address     : e.currentTarget.dataset.index,
                addressShow : false
            })
        }else{
            this.setData({
                addressShow : false
            })
        }

        // 获取卡券列表
        this.couponInfo()
    },

    /**
     * 支付选择
     */
    payBind(e) {
        this.setData({
            payWayIndex: e.detail.value
        })
    },

    /**
     * 商品数量加减
     */
    goodsNumber(e){
        if(this.data.welfareType == 'welfare') {
            wx.showToast({
                title   : '抱歉，只能购买一张',
                icon    : 'none'
            })
            return
        }
        let num = this.data.num
        if (e.currentTarget.dataset.type == 'plus'){
            num ++;
        }else{
            if (num > 1){
                num --;
            }else{
                wx.showToast({
                    title   : '商品数量不能小于1',
                    icon    : 'none'
                })
            }
        }
        this.setData({
            num : num
        })

        // 获取详情
        this.couponInfo()
    },

    /**
     * 选择提交方式
     */
    platBind(e) {
        this.setData({
            platIndex : e.detail.value,
            isdeliver : this.data.platformCp[e.detail.value].value
        })
        // 获取详情
        this.couponInfo()
    },

    /**
     * 支付提交
     */
    submitOrder() {
        if(this.data.isdeliver.length == 0) {
            this.setData({
                isdeliver: this.data.detail.def_get
            })
        }
        let right_id     = this.data.rightId,
            welfare_id   = this.data.welfareId,
            address_id   = this.data.address.id,
            is_deliver   = this.data.isdeliver,
            qty          = this.data.num

        wx.$api.user.washcarCreate(welfare_id, right_id, qty, address_id, is_deliver).then(res=>{
            // payWayIndex为1的时候为沃支付-直接跳转h5
            if (this.data.payWayIndex == 1) {
                const newUrl     = "https://card.ysd-bs.com/unicom/payment?trade_no=" + res.data.trade_no
                let url= encodeURIComponent(newUrl)
                wx.redirectTo({
                    // 跳转到webview页面
                    url: `/pages/webView/webView?url=${url}`
                });
            }

            // payWayIndex为0的时候为微信支付
            if(this.data.payWayIndex == 0) {
                let dataUrl = '',  //定义接口来源名称
                Newtype = res.data.type //订单来源
                // welfare为福利活动购买
                if(Newtype == 'welfare') dataUrl = wx.$api.index.fridayPay(res.data.trade_no)

                // right为权益购买
                if(Newtype == 'right') dataUrl = wx.$api.index.wechat(res.data.trade_no)

                // 第一步接口调取
                dataUrl.then(payEes=>{
                    let payInfo = JSON.parse(payEes.data)
                    wx.requestPayment({
                        timeStamp: payInfo.timeStamp,
                        nonceStr : payInfo.nonceStr,
                        package  : payInfo.package,
                        paySign  : payInfo.paySign,
                        signType : payInfo.signType,
                        success  : res=>{
                            if(res.errMsg == "requestPayment:ok"){
                                wx.showToast({
                                    title: '支付成功',
                                    icon : 'success'
                                })
                                if(Newtype == 'welfare'){
                                    setTimeout(()=>{
                                        if(this.data.isdeliver == 1) {
                                            wx.reLaunch({
                                                url: '/pages/order/order?orderType=welfareGoods'
                                            })
                                        } else {
                                            wx.reLaunch({
                                                url: '/pages/order/order?orderType=welfare'
                                            })
                                        }
                                    },3000)
                                }
                                if(Newtype == 'right'){
                                    setTimeout(()=>{
                                        if(this.data.isdeliver == 1) {
                                            wx.reLaunch({
                                                url: '/pages/order/order?orderType=rightsCoupons'
                                            })
                                        } else {
                                            wx.reLaunch({
                                                url: '/pages/order/order?orderType=rights'
                                            })
                                        }
                                    },3000)
                                }
                            }
                        },
                        fail  : res=>{
                            if(Newtype == 'welfare'){
                                if(this.data.isdeliver == 1) {
                                    wx.reLaunch({
                                        url: '/pages/order/order?orderType=welfareGoods&stateType=unpay'
                                    })
                                } else {
                                    wx.reLaunch({
                                        url: '/pages/order/order?orderType=welfare&stateType=unpay'
                                    })
                                }
                            }
                            if(Newtype == 'right'){
                                if(this.data.isdeliver == 1) {
                                    wx.reLaunch({
                                        url: '/pages/order/order?orderType=rightsCoupons&stateType=unpay'
                                    })
                                } else {
                                    wx.reLaunch({
                                        url: '/pages/order/order?orderType=rights&stateType=unpay'
                                    })
                                }
                            }
                        }
                    })
                }).catch(err => {});
            }
        }).catch(err => {});
    }
})