<template>
    <view class="content">
        <view class="borderBottom">
            <view class="title">
                <image class="title-img" src="/static/img/draw_choose.png"></image>
                <view class="title-top">
                    选择商品兑换
                </view>
            </view>
            <view class="choose">
                <view class="choose-radio-group">
                    <radio-group class="choose-label" :class="{active : current == 1}" @change="(e) => radioChange(e,index,item)" v-for="(item, index) in goodsArr" :key="index">
                        <view class="choose-label-name">
                            <image class="choose-label-img" :src="item.cover"></image>
                            <view class="choose-label-text">
                                <view class="choose-label-title">
                                    {{item.title}}
                                    <text>基于能监测健康的手环</text>
                                </view>
                                <view class="choose-label-price">
                                    <text>￥</text>{{item.price}}
                                </view>
                            </view>
                        </view>
                        <radio class="radio" :value="String(item.exchagne_item_goods_id)" :checked="index == current"></radio>
                    </radio-group>
                </view>
                <view class="chooseForm">
                    <view class="site-input">
                        <label>收货人姓名</label>
                        <input class="campus-form-input" maxlength="4" type="text" placeholder="请输入收货人姓名" @input="getNameValue" name="name" placeholder-style="color:#c9c9c9;"></input>
                    </view>
                    <view class="site-input">
                        <label>收货人手机</label>
                        <input class="campus-form-input" maxlength="11" type="number" placeholder="请输入收货人手机号" @input="getTelValue" name="mobile" placeholder-style="color:#c9c9c9;"></input>
                    </view>
                    <!-- <view class="site-input">
                        <label>所在省份</label>
                        <picker @change="areasChange" :value="area.areaIndex" :range="area.areas" :range-key="'name'" name="province_id">
                            <view class="picker" v-if="area.areas[area.areaIndex]">
                                {{ area.areas[area.areaIndex].name }}
                            </view>
                    		<image src="/static/icon/rightsArrow.png"></image>
                        </picker>
                    </view>
                    <view class="site-input">
                        <label>所在城市</label>
                        <picker @change="cityDrop" :value="city.cityIndex" :range="city.cityList" :range-key="'name'" class="conneColor" name="city_id">
                            <view class="picker" v-if="city.cityList[city.cityIndex]">
                                {{ city.cityList[city.cityIndex].name }}
                            </view>
                    		<image src="/static/icon/rightsArrow.png"></image>
                        </picker>
                    </view>
                    <view class="site-input">
                        <label>所在区域</label>
                        <picker @change="regiDrop" :value="regi.regiIndex" :range="regi.regiList" :range-key="'name'" class="conneColor" name="district_id">
                            <view class="picker" v-if="regi.regiList[regi.regiIndex]">
                                {{ regi.regiList[regi.regiIndex].name }}
                            </view>
                    		<image src="/static/icon/rightsArrow.png"></image>
                        </picker>
                    </view> -->
                    <view class="site-input">
                    	<label>收货地址</label>
                    	<input placeholder="请输入收货详细地址" name="address" @input="getAddressValue" placeholder-style="color:#c9c9c9;"></input>
                    </view>
                </view>
            </view>
        </view>
        <view class="chooseBuy">
            <view class="chooseBuy-price">
                {{goodTitle}}<text>{{goodPay == 0 ? '免费兑换' : '支付金额： ￥' + goodPrice}}</text>
            </view>
            <button type="default" class="chooseBuy-btn" @click="siteform">
                兑换
            </button>
        </view>
    </view>
</template>

<script>
    import { exchanges, exchangesBuy } from '@/apis/interfaces/draw'
    import { create, children } from '@/apis/interfaces/address'
    import { getAuthUrl, wpayH5Info, h5Pay } from '@/apis/interfaces/rights'
    const jweixin = require('jweixin-module');  //获取微信支付
    export default {
        data() {
            return {
                logId      : '', //抽奖记录
                tradeNo    : '', //产品支付订单号
                goodsArr   : [], //产品列表
                goodId     : '', //产品id
                goodTitle  : '', //产品名称
                goodPrice  : '', //产品金额
                goodPay    : '', //产品是否支付
                current    : 0 , //支付下标
                address    : '', // 地址内容
                name       : '', // 姓名
                mobile     : '', // 手机号
                // 省份选择
                area: { 
                    areas      : [],
                    areaSn     : '',
                    areaIndex  : 0,
                },
                        
                // 市级选择
                city: {
                    cityList   : [],
                    cityId     : 0,
                    cityIndex  : 0,
                },
                        
                // 区域选择
                regi: {
                    regiList   : [],
                    regiId     : 0,
                    regiIndex  : 0,
                }
            }
        },
        
        // 生命周期函数--监听页面加载
        onLoad(options) {
            // 判断是否微信授权登录过  只有外部游览器才用到（支付需要授权微信环境）
            let status = navigator.userAgent.toLowerCase();
            if (status.match(/MicroMessenger/i) == "micromessenger" && !options.code) {
                let locationUrl = window.location.pathname.substr(1) + window.location.search
                getAuthUrl(locationUrl).then(res=> {
                    window.location.href = res
                })
            }
            this.openid  = options.openid || ''
            this.code    = options.code || ''  //用code换取oppid
            
            // 获取商品选择
            this.exchangesShow(options.id)
        },
        
        onShow() {
            // 存储环境-用户抽奖活动
            getApp().globalData.envType = 'drawEnv'
            
            // 获取省信息
            // this.getProvince()
        },
		
        methods: {
            // 微信支付数据
            wechatPayment() {
                let status = navigator.userAgent.toLowerCase();
                if (status.match(/MicroMessenger/i) == "micromessenger") {
                    // 微信浏览器-获取
                    this.wxBrowser();
                }else {
                    // 普通浏览器(网址游览器)
                    this.outBrowser();
                }
            },
            
            // 商品选择
            exchangesShow(id){
                exchanges(id).then(res=>{
                    this.logId     = res.exchage_log_id
                    this.goodsArr  = res.exchange_item.goods
                    this.goodId    = res.exchange_item.goods[0].exchagne_item_goods_id
                    this.goodTitle = res.exchange_item.goods[0].title
                    this.goodPrice = res.exchange_item.goods[0].price
                    this.goodPay   = res.exchange_item.goods[0].is_buy
                })
            },
            
			// 支付方式选择
			radioChange(evt, index, item) {
                this.goodTitle = item.title
                this.goodPay   = item.is_buy
                this.goodPrice = item.amount
                this.current   = index
                this.goodId    = evt.detail.value
			},
            
            // 省信息
            getProvince() {
                create().then(res=>{
                    let areaArr    =  res.provinces,
                        areaIndex  =  this.area.areaIndex
                    this.area.areaSn   = areaArr[areaIndex].code
                    this.area.areas    = areaArr
                    this.citylist(areaArr[areaIndex].code)
                })
            },
            
            // 所在省份
            areasChange(e) {
                let area     = this.area.areas,
                    index    = e.detail.value,
                    atcode   = area[index].code
                if (index != this.area.areaIndex) {
                    this.area.areaIndex  = index
                    this.area.areaSn     = atcode
                    
                    // 获取市级列表
                    this.citylist(atcode)
                }
            },
            
            // 市级列表
            citylist(code) {
                children(code).then(res=>{
                    let cityArr = res
                    this.city.cityId    = cityArr[0].code
                    this.city.cityList  = cityArr
                    this.city.cityIndex = 0
                    this.regilist(cityArr[0].code)
                })
            },
            
            // 市级下拉筛选
            cityDrop(e) {
                let city     = this.city.cityList,
                    index    = e.detail.value,
                    citycode = city[index].code
                if (index != this.area.areaIndex) {
                    this.city.cityIndex = index
                    this.city.cityId    = citycode
                    
                    // 获取市级列表
                    this.regilist(citycode)
                }
            },
            
            // 区列表
            regilist(areaCode) {
                children(areaCode).then(res=>{
                    this.regi.regiList  = res
                    this.regi.regiId    = res[0].code
                    this.regi.regiIndex = 0
                })
            },
            
            // 区下拉筛选
            regiDrop(e) {
                let newIndex = e.detail.value
                this.regi.regiIndex  = newIndex
                this.regi.regiId     = this.regi.regiList[newIndex].code
            },
            
            // 获取用户名
            getNameValue(e) {
                this.name = e.detail.value
            },
            
            // 获取手机号
            getTelValue(e) {
                this.mobile = e.detail.value
            },
            
            // 获取详细地址
            getAddressValue(e) {
                this.address = e.detail.value
            },
            
            // 提交表单
            siteform() {
                exchangesBuy({
                    name        : this.name,
                    mobile      : this.mobile,
                    address     : this.address,
                    activity_exchange_log_id: this.logId,
                    activity_exchange_item_goods_id: this.goodId,
                    qty         : 1
                }).then(res=>{
                    if(res.need_buy) {
                        this.tradeNo = res.trade_no
                        this.wxBrowser()
                        return
                    }
                    // 跳转兑换成功页
                    uni.redirectTo({
                        url: 'success'
                    })
                }).catch(err => {
                    uni.showToast({
                        title: err.message,
                        icon: 'none'
                    })
                })
            },
            
            // 当支付环境为微信游览器情况下
            wxBrowser() {
                wpayH5Info({
                    url: location.href.split('#')[0],
                    list:'chooseWXPay'
                }).then(wechatConfig => {
                    let wxConfig = JSON.parse(wechatConfig)
                    jweixin.config({
                        appId: wxConfig.appId,
                        debug: false,
                        jsApiList: wxConfig.jsApiList,
                        signature: wxConfig.signature,
                        nonceStr: wxConfig.nonceStr,
                        timestamp: wxConfig.timestamp
                    })
                    jweixin.ready(() => {
                        let wechaUrl = 'payments/wechat'
                        h5Pay(wechaUrl, {
                            channel: 'h5',
                            trade_no: this.tradeNo,
                            code: this.code
                        }).then(wechatRes => {
                            let wechatPay = JSON.parse(wechatRes)
                            console.log("wechatPay")
                            jweixin.chooseWXPay({
                                timestamp: wechatPay.timeStamp,
                                nonceStr: wechatPay.nonceStr, 
                                package: wechatPay.package,
                                signType: wechatPay.signType,
                                paySign: wechatPay.paySign,
                                success: payRes => {
                                    console.log(payRes)
                                },
                                cancel: () =>{
                                }
                            })
                        })
                    })
                }).catch(err => {
                    uni.showToast({
                        title: err.message,
                        icon: 'none'
                    })
                    if (!err.login) {
                        uni.reLaunch({
                            url: '/pages/draw/signin'
                        });
                    }
                })
            },
        }
    }
</script>

<style lang="scss">
    .content {
        padding: 30rpx 20rpx;
        box-sizing: border-box;
    }
    
    .borderBottom {
        border-bottom: 110rpx solid transparent;
    }
    
    .title {
        position: relative;
        width: 100%;
        background-color: #2564ff;
        height: 100rpx;
        border-radius: 10rpx;
        .title-img {
            width: 100%;
            height: 100%;
            position: absolute;
            height: 100rpx;
            left: 0;
            top: 0;
        }
        .title-top {
            width: 100%;
            height: 100%;
            line-height: 100rpx;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 9;
            text-align: center;
            font-size: 32rpx;
            font-weight: 600;
            color: #FFFFFF;
        }
    }
    
    .choose {
        margin: 30rpx -10rpx 0;
        overflow: hidden;
        .choose-radio-group {
            overflow: hidden;
        }
        .choose-label {
            width: calc(50% - 20rpx);
            float: left;
            margin: 0 10rpx;
            border-radius: 10rpx;
            background-color: #FFFFFF;
            margin-bottom: 30rpx;
            padding: 30rpx 20rpx;
            box-sizing: border-box;
            position: relative;
            .choose-label-name {
                .choose-label-img {
                    width: 100rpx;
                    height: 100rpx;
                }
            }
            .radio {
                position: absolute;
                top: 20rpx;
                right: 10rpx;
            }
            .choose-label-text {
                margin-top: 20rpx;
                font-weight: 600;
                .choose-label-title {
                    margin-bottom: 30rpx;
                    font-size: 30rpx;
                    text {
                        font-weight: normal;
                        color: #bac0d7;
                        display: block;
                        font-size: 26rpx;
                        line-height: 54rpx;
                    }
                }
                .choose-label-price {
                    color: #fd7164;
                    font-size: 34rpx;
                    text {
                        font-size: 26rpx;
                    }
                }
            }
        }
    }
    
    .chooseBuy {
        position: fixed;
        width: 100%;
        height: 110rpx;
        left: 0;
        bottom: 0;
        display: flex;
        background-color: #FFFFFF;
        padding: 30rpx;
        box-sizing: border-box;
        .chooseBuy-btn {
            position: absolute;
            right: 20rpx;
            top: 26rpx;
            background-color: #f24b44;
            color: #FFFFFF;
            height: 62rpx;
            line-height: 60rpx;
            margin: 0;
            font-size: 28rpx;
            padding: 0 35rpx;
        }
        .chooseBuy-name {
            font-size: 32rpx;
            line-height: 48rpx;
        }
        .chooseBuy-price {
            font-size: 28rpx;
            line-height: 50rpx;
            color: #777b85;
            text {
                color: #f14646;
                padding-left: 20rpx;
            }
        }
    }
    
    .chooseForm {
        background-color: #FFFFFF;
        margin: 0 15rpx;
        border-radius: 10rpx;
        .site-input {
            font-size: 30rpx;
            padding: 0 30rpx 0 220rpx;
            box-sizing: border-box;
            position: relative;
            line-height: 100rpx;
            min-height: 100rpx;
            &::before {
                position: absolute;
                bottom: 0;
                width: 100%;
                left: 0rpx;
                right: 0;
                height: 1rpx;
                content: "";
                background: #e4e6f2;
            }
            &:last-child::before {
                display: none;
            }
            label {
                position: absolute;
                left: 30rpx;
                top: 0;
            }
            input {
                font-size: 30rpx;
                height: 110rpx;
            }
            image {
                width: 38rpx;
                height: 38rpx;
                position: absolute;
                right: 20rpx;
                top: 32rpx;
            }
        }
    }
</style>
