Page({

    /**
     * 页面的初始数据
     */
    data: {
        parentId    : '',    //分享者ID
        address     : '',    //默认收货地址
        allAddress  : '',    //收货地址列表
        groupId     : '',    //权益id
        detail      : '',    //权益详情
        amount      : '',    //总金额
        moreAmount  : '',    //产品金额
        score       : '',    //应付总积分
        freight     : '',    //运费
        num         : 1,     //购买的数量
        content     : '',    //内容介绍
        notification: '',    //重要提示
        remark      : '',    //使用须知
        noticeShow  : true, //须知显示状态
        addressShow : false, //收货地址显示
        getType     : '',    //是否显示自提
        platIndex   : 0,     //选择提交方式下标
        isdeliver   : -1,
        platformCp  : [],   //选择提交数组
        pointMoreShow: false,
        from        : '',
        typeNo      : '',
        uniUrl      : '',     //跳转h5页面
        openid      : '',
        webShow     : false,
        rightsTap   : false,
        disabled    : false,
        payWayIndex : 0,
        payWay      :[
            {value: 0, name: "微信支付"},
            {value: 1, name: "沃钱包支付"}
        ],
        orderType   : '' //订单类型
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            groupId   : options.rightsId || options.id,
            typeWeb   : options.type,
            getType   : options.getType,
            openid    : options.openid || '',
            orderType : options.orderType
        })

        console.log(getApp().globalData.shareObj)
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 获取详情
        this.rightsInfo();
    },

    /**
     * 详情
     */
    rightsInfo() {
        wx.$api.index.rightShow(this.data.groupId, this.data.address.id, this.data.num, 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.num,
                freight     : res.data.freight,
                platformCp  : arr,
                from        : res.data.detail.from,
                amount      : res.data.total,
                moreAmount  : res.data.amount,
                score       : res.data.score,
                typeNo      : res.data.detail.type_no,
                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;"'),
                notification: res.data.detail.notification.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'),
            })

            if(this.data.openid == '') {
                this.setData({
                    openid: res.data.detail.union_openid
                })
            }

            if(res.data.detail.from == 'unionpay') {
                if(res.data.detail.union_openid == '') {
                    wx.$api.index.unionpay('/pages/rights/rights?id=' + res.data.detail.right_id, 'wxmini', this.data.groupId).then(res=>{
                        this.setData({
                            uniUrl : encodeURIComponent(res.data)
                        })
                    }).catch(err => {});
                }
            }
        }).catch(err=>{})
    },

    /**
     * 商品数量加减
     */
    goodsNumber(e){
        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.rightsInfo()
    },
    /**
     * 输入商品数量
     */
    goodsNumberInput(e){
        let goodsNum   = e.detail.value
        if (goodsNum > 0){
            this.setData({
                num : goodsNum
            })
        }else{
            wx.showToast({
                title   : '商品数量不能小于1',
                icon    : 'none'
            })
            this.setData({
                num : goodsNum
            })
        }
        
        // 获取详情
        this.rightsInfo()
    },

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

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

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

    /**
     * 收货地址收起
     */
    addressHide() {
        this.setData({
            addressShow : false
        })
    },

    /**
     * 选择收货地址
     */
    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.rightsInfo()
    },

    /**
     * 普通商品支付提交
     */
    ordinary() {
        this.submitOrder();
        this.setData({
            disabled : true
        })
    },

    /**
     * 只有银联商品获取
     */
    unionOrder() {
        // 更新openid
        wx.$api.index.unionCode(this.data.openid).then(res=>{})
        this.submitOrder();
    },

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

    /**
     * 支付提交
     */
    submitOrder() {
        if(this.data.isdeliver.length == 0) {
            this.setData({
                isdeliver: this.data.detail.def_get
            })
        }

        let right_id     = this.data.detail.right_id,
            address_id   = this.data.address.id,
            is_deliver   = this.data.isdeliver,
            qty          = this.data.num,
            newParent    = '',
            shareObj     = getApp().globalData.shareObj
        
        if(shareObj.type == 'shareStored' && shareObj.type == this.data.orderType){
            newParent = shareObj.userId
        }
        
        if(shareObj.type == 'shareGoods' && shareObj.goodsId == right_id){
            console.log(22222)
            newParent = shareObj.userId
        }

        wx.$api.index.rightStore(right_id, address_id, is_deliver, qty, newParent).then(res=>{
            if(res.data.canPay == false) {
                wx.showToast({
                    title   : '支付成功',
                    icon    : 'success',
                    duration: 2000
                })
                setTimeout(()=>{
                    if(this.data.isdeliver == 1) {
                        wx.reLaunch({
                            url: '/pages/order/order?orderType=rightsCoupons'
                        })
                    } else {
                        wx.reLaunch({
                            url: '/pages/order/order?orderType=rights'
                        })
                    }
                },3000)
                this.setData({
                    rightsTap: true
                })
            }else {
                // 储值
                if(shareObj.type == 'shareStored'){
                    getApp().globalData.shareObj = {
                        type    : '',
                        goodsId : '',
                        userId  : ''
                    }
                }

                // 商品
                if(shareObj.type == 'shareGoods' && shareObj.goodsId == right_id){
                    getApp().globalData.shareObj = {
                        type    : '',
                        goodsId : '',
                        userId  : ''
                    }
                }

                // 跳转收银台
                wx.navigateTo({
                    url: "/pages/cashier/cashier?trade_no=" + res.data.trade_no + "&amount=" + this.data.amount + "&is_deliver=" + is_deliver + "&pay_type=rightsPay"
                })
            }
        }).catch(err => {});
    },


    /**
     * 新增收货地址
     */
    addSelect() {
        wx.navigateTo({
          url: '/pages/address/address?type=selectAddress'
        })
        this.setData({
            addressShow : false
        })
    },

    /**
     * 重要提示显示
     */
    pointMoreTap() {
        this.setData({
            pointMoreShow : !this.data.pointMoreShow
        })
    }
})