<template>
  <view class="m_body">
    <view class="head_card">
      <view class="card_img">
        <image class="image" src="https://lihai001.oss-cn-chengdu.aliyuncs.com/def/22c6320240125134855740.png"></image>
        <view class="c_content">
          <view class="c_title">当前余额</view>
          <view class="c_count"> <text class="c_icon">¥</text> {{userInfo.now_money||'0.00'}}</view>
        </view>
      </view>
      <view class="c_tab">
        <u-tabs :list="list1" :current="curNow" @click="clickTab1" lineWidth="60rpx" lineColor="#FF8056"
          :itemStyle="{width: '200rpx', height: '80rpx'}"></u-tabs>
      </view>
    </view>
    <view class="body_card">
      <view class="card1" v-if="curNow==0">
        <view class="change_list">
          <view class="change_item" :class="{'change_item_active': nowChange==index}" @click="changeItem(item, index)"
            v-for="(item, index) in changeList" :key="index">
            <text class="c_icon">¥</text> {{item}}
          </view>
        </view>
        <view class="c_tab">
          <u-tabs :list="[{name: '充值数量'}]" lineWidth="60rpx" lineColor="#FF8056"
            :itemStyle="{width: '200rpx', height: '80rpx'}"></u-tabs>
        </view>
        <view class="change_count">
          <view>当前选择面额 ¥{{nowPrice}}</view>
          <view class="c_btn">
            <view @click="reduce">-</view>
            <view>{{priceCount}}</view>
            <view @click="append">+</view>
          </view>
        </view>
        <view class="c_tips">
          <view class="tips_title">注意事项:</view>
          <view>充值后金额不能提现，仅可用于商城商品消费</view>
        </view>
      </view>
      <view class="card2" v-if="curNow==1">
        <view class="record" v-for="(item, index) in recordList" :key="index">
          <view class="left">
            <image src="https://lihai001.oss-cn-chengdu.aliyuncs.com/def/e807a202401251520462666.png"></image>
            <view>
              <view>{{item.title}}</view>
              <view class="tips">{{item.create_time}}</view>
            </view>
          </view>
          <view class="right">{{item.number}}</view>
        </view>
        <view class="no_data" v-if="recordList.length==0">暂无充值记录</view>
      </view>
    </view>
    <view class="footer" v-if="curNow==0">
      <view class="f_tip">
        总计充值金额:
        <view class="price">
          <text>{{total}}</text>元
        </view>
      </view>
      <view class="primary_btn" @click="$u.throttle(submitSub, 1500)">确认充值</view>
    </view>
    <payment :payMode="payMode" :order_id="rechar_id" :pay_close="pay_close" :is-call="true" @onChangeFun="onChangeFun"
    	 :totalPrice="totalPrice"></payment>
    <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
  </view>
</template>

<script>
  import { getCommissionInfo } from "@/api/user.js"
  import { Toast } from "../../../libs/uniApi";
  import {
    mapGetters
  } from "vuex";
  import {
    getUserInfo,
    spreadInfo,
    rechargeWechat
  } from '@/api/user.js';
	import authorize from '@/components/Authorize';
	import payment from '@/components/payment';
  export default {
    components:{
      authorize,
      payment
    },
    data() {
      return {
        userInfo: {},
        curNow: 0,
        list1: [{
          name: '余额充值'
        }, {
          name: '充值记录'
        }],
        changeList: [10, 15, 20, 50, 100],
        nowChange: 0,
        nowPrice: 0,
        priceCount: 1,
        isAuto: false, //没有授权的不会自动授权
        isShowAuth: false, //是否隐藏授权
        recordList: [],
        where: {
          page: 1,
          limit: 15,
          type: 2
        },
        otherValue: '其他',
        now_money: 0,
        navRecharge: ['账户充值', '佣金转入'],
        active: 0,
        number: '',
        from: '',
        placeholder: "0.00",
        picList: [],
        activePic: 0,
        money: "",
        numberPic: '',
        rechar_id: '0',
        rechargeAttention: [],
        pay_close: false,
        totalPrice: '0',
        payMode: [{
        	name: '微信支付',
        	icon: 'icon-weixinzhifu',
        	// #ifdef H5
        	value: 'h5',
        	// #endif
        	// #ifdef MP
        	value: 'routine',
        	// #endif
        	// #ifdef APP-PLUS
        	value: 'weixin',
        	// #endif
        	title: '微信快捷支付',
        	payStatus: true
        	}
        ],
      }
    },
    onLoad() {
      this.nowPrice = this.changeList[0];
      if (this.isLogin) {
        this.getUserInfo()
      } else {
        this.isAuto = true;
        this.isShowAuth = true
      }
    },
    onShow() {},
    computed: {
      ...mapGetters(['isLogin', 'viewColor', 'keyColor']),
      total() {
        return this.nowPrice * this.priceCount;
      }
    },
    onReachBottom() {
      this.getCommissionInfo();
    },
    methods: {
      clickTab1(e) {
        this.curNow = e.index;
        if (e.index == 1) {
          this.where.page = 1;
          this.getCommissionInfo();
        }
      },
      changeItem(e, index) {
        this.nowPrice = e;
        this.nowChange = index;
        if (this.priceCount * this.nowPrice > 20000) {
          this.priceCount = Math.floor(20000 / this.nowPrice);
          return Toast('不可充值超过2万元');
        }
      },
      append() {
        if (this.priceCount * this.nowPrice > 20000) {
          this.priceCount = Math.floor(20000 / this.nowPrice);
          return Toast('不可充值超过2万元');
        } else this.priceCount++;
      },
      reduce() {
        if (this.priceCount <= 1) return Toast('最少充值一份');
        else this.priceCount--;
      },
      getCommissionInfo() {
        getCommissionInfo(this.where).then((res) => {
          if(res.data.list.length>0) {
            this.recordList = [...this.recordList, ...res.data.list];
            if(res.data.list.length>=15) this.where.page++;
          }
        })
      },
      /**
       * 选择金额
       */
      picCharge(idx, item) {
      	this.activePic = idx;
      	if (item === undefined) {
      		this.rechar_id = '0';
      		this.numberPic = "";
      		this.otherValue = ''
      	} else {
      		this.otherValue = '其他'
      		this.total = "";
      		this.rechar_id = item.id.toString();
      		this.numberPic = item.data.price;
      	}
      },
      /**
       * 充值额度选择
       */
      getRecharge() {
      	getRechargeApi()
      		.then(res => {
      			this.picList = res.data.recharge_quota;
      			if (this.picList[0]) {
      				this.rechar_id = this.picList[0].id.toString();
      				this.numberPic = this.picList[0].data.price;
      			}
      			this.rechargeAttention = res.data.recharge_attention || [];
      		})
      		.catch(res => {
      			this.$dialog.toast({
      				mes: res
      			});
      		});
      },
      onLoadFun: function() {
      	this.isShowAuth = false;
      	this.getUserInfo();
      	this.getRecharge();
      },
      // 授权关闭
      authColse: function(e) {
      	this.isShowAuth = e
      },
      navRecharges: function(index) {
      	this.active = index;
      },
      /**
       * 获取用户信息
       */
      getUserInfo: function() {
      	let that = this;
      	spreadInfo().then(res => {
      		that.$set(that, 'userInfo', res.data);
      	})
      },
      payClose: function() {
      	this.pay_close = false;
      },
      payCheck: function(type) {
      	this.createOrder(type);
      },
      
      /*
       * 用户充值
       */
      submitSub: function(e) {
      	let that = this
      	let value = this.total;
      	// 转入余额
      	if (that.active) {
      		if (parseFloat(value) < 0 || parseFloat(value) == NaN || value == undefined || value == "") {
      			return that.$util.Tips({
      				title: '请输入金额'
      			});
      		}
      		uni.showModal({
      			title: '转入余额',
      			content: '转入余额后无法再次转出，确认是否转入余额',
      			success(res) {
      				if (res.confirm) {
      					rechargeBrokerage({
      						brokerage: parseFloat(value),
      					}).then(res => {
      							// that.$set(that, 'userInfo.now_money', that.$util.$h.Add(value, that.userInfo.now_money))
      							return that.$util.Tips({
      								title: '转入成功',
      								icon: 'success'
      							}, {
      								tab: 5,
      								url: '/pages/users/user_money/index'
      							});
      						}).catch(err => {
      							return that.$util.Tips({
      								title: err
      							})
      						});
      				} else if (res.cancel) {
      					return that.$util.Tips({
      						title: '已取消'
      					});
      				}
      			},
      		})
      	} else {
      		if (this.rechar_id == 0) {
      			if (parseFloat(that.total)=== 0) {
      				return that.$util.Tips({
      					title: '充值金额金额不能为0！'
      				});
      			}
      			if (!that.total) {
      				return that.$util.Tips({
      					title: '请填写充值金额！'
      				});
      			}
      			if (!Number(that.total)) {
      				return that.$util.Tips({
      					title: '请填写正确的金额！'
      				});
      			}
      		}
      		this.pay_close = true
      	}
      },
      createOrder(type) {
      	let that = this;
      	let query = {
      		price: that.rechar_id == 0 ? that.total : that.numberPic,
      		recharge_id: that.rechar_id,
      		type: type,
      		// #ifdef H5
      		return_url: location.port ? location.protocol + '//' + location.hostname + ':' + location.port +
      			'/pages/users/user_money/money' : location.protocol + '//' + location.hostname +
      			'/pages/users/user_money/money'
      		// #endif
      	};
      	// #ifdef MP
      	// openPaySubscribe().then(() => {
      		rechargeWechat(query).then(res => {
      			that.callPay(res);
      		}).catch(err => {
      			uni.showToast({
      				title: err,
      				icon: 'none'
      			});
      		});
      	// });
      	// #endif
      	// #ifndef MP
      	rechargeWechat(query).then(res => {
            console.log('res', res);
      		that.callPay(res);
      	}).catch(err => {
            console.log('err', err);
      		uni.showToast({
      			title: err,
      			icon: 'none'
      		});
      	});
      	// #endif
      },
      // 调用支付
      callPay(res) {
      	let that = this, status = res.data.type,
      		orderId = res.data.recharge_id,
      		callback_key = res.data.pay_key,
      		jsConfig = res.data.config,
      		goPages = '/pages/users/user_money/money';
      	switch (status) {
      		case 'ORDER_EXIST':
      		case 'EXTEND_ORDER':
      		case 'PAY_ERROR':
      		case 'error':
      			uni.hideLoading();
      			return that.$util.Tips({
      				title: res.message
      			}, {
      				tab: 5,
      				url: goPages
      			});
      			break;
      		case 'success':
      			uni.hideLoading();
      			if (that.seckillId)
      				return that.$util.Tips({
      					title: res.message,
      					icon: 'success'
      				}, {
      					tab: 4,
      					url: goPages
      				});
      			return that.$util.Tips({
      				title: res.message,
      				icon: 'success'
      			}, {
      				tab: 5,
      				url: goPages
      			});
      			break;
      		case 'alipay':
      		case "alipayQr":
      			uni.hideLoading();
      			that.$emit('onChangeFun', {
      				action: 'payClose'
      			});
      			uni.navigateTo({
      				url: '/pages/order_pay_back/index?keyCode='+callback_key+'&url='+jsConfig+'&type=10'
      			})
      			return;
      			break;
      			// #ifndef MP
      		case "wechat":
      		case "weixin":
      		case "weixinApp":
      			jsConfig.timeStamp = jsConfig.timestamp;
      			// #ifndef APP-PLUS
      			that.$wechat.pay(jsConfig).then(res => {
      				return that.$util.Tips({
      					title: res.message,
      					icon: 'success'
      				}, {
      					tab: 4,
      					url: goPages
      				});
      			}).catch(res => {
      				if (res.errMsg == 'chooseWXPay:cancel') return that.$util.Tips({
      					title: '取消支付'
      				}, {
      					tab: 5,
      					url: goPages
      				});
      			})
      			// #endif
      			// #ifdef APP-PLUS
      			let mp_pay_name=''
      			if(uni.requestOrderPayment){
      				mp_pay_name='requestOrderPayment'
      			}else{
      				mp_pay_name='requestPayment'
      			}
      			uni[mp_pay_name]({
      				provider: 'wxpay',
      				orderInfo: jsConfig,
      				success: (e) => {
      					let url = '/pages/users/user_money/money';
      					return that.$util.Tips({
      						title: '支付成功',
      						icon: 'success'
      					}, {
      						tab: 4,
      						url: url
      					});
      				},
      				fail: (e) => {
                console.log(e);
      					uni.showModal({
      						content: "支付失败",
      						showCancel: false,
      						success: function(res) {
      							let url = '/pages/users/user_money/money';
      							uni.redirectTo({
      								url: url
      							})
      						}
      					})
      				},
      				complete: () => {
      					uni.hideLoading();
      				},
      			});
      			// #endif
      			break;
      			// #endif
      			// #ifdef MP
      		case "routine":
      			jsConfig.timeStamp = jsConfig.timestamp;
      			let mp_pay_name=''
      			if(uni.requestOrderPayment){
      				mp_pay_name='requestOrderPayment'
      			}else{
      				mp_pay_name='requestPayment'
      			}
      			uni[mp_pay_name]({
      				...jsConfig,
      				success: function(res) {
      					uni.hideLoading();
      					that.getUserInfo();
      					that.getRecharge();
      					// console.log('12323424')
      					return that.$util.Tips({
      						title: '支付成功',
      						icon: 'success'
      					}, {
      						tab: 5,
      						url: goPages
      					});
      				},
      				fail: function(e) {
      					uni.hideLoading();
      					return that.$util.Tips({
      						title: '取消支付'
      					}, {
      						tab: 5,
      						url: goPages
      					});
      				},
      			})
      			break;
      			// #endif
      		case "balance":
      			uni.hideLoading();
      			//余额不足
      			return that.$util.Tips({
      				title: res.msg
      			}, {
      				tab: 5,
      				url: goPages
      			});
      			break;
      			// #ifdef H5
      		case 'h5':
      			let host = window.location.protocol + "//" + window.location.host;
      			let url = `${host}/pages/users/user_money/money`
      			let eUrl = encodeURIComponent(url)
      			let jsurl = jsConfig.mweb_url || jsConfig.h5_url
      			let locations = `${jsurl}&redirect_url=${eUrl}`
      			setTimeout(() => {
      				location.href = locations;
      			}, 100);
      			break;
      			// #endif
      			// #ifdef APP-PLUS
      		case 'alipayApp':
      			uni.requestPayment({
      				provider: 'alipay',
      				orderInfo: jsConfig,
      				success: (e) => {
      					return that.$util.Tips({
      						title: '支付成功',
      						icon: 'success'
      					}, {
      						tab: 5,
      						url: goPages
      					});
      				},
      				fail: (e) => {
      					uni.showModal({
      						content: "支付失败",
      						showCancel: false,
      						success: function(res) {
      							uni.redirectTo({
      								url: goPages
      							})
      						}
      					})
      				},
      				complete: () => {
      					uni.hideLoading();
      				},
      			});
      			break;
      			// #endif
      	}
      },
      onChangeFun: function(e) {
      	let opt = e;
      	let action = opt.action || null;
      	let value = opt.value != undefined ? opt.value : null;
      	action && this[action] && this[action](value);
      },
    },
    onPullDownRefresh() {
      uni.stopPullDownRefresh()
    }
  }
</script>

<style lang="scss">
  .m_body {
    .head_card {
      position: relative;
      height: 430rpx;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: #fff;

      .card_img {
        width: 724rpx;
        height: 362rpx;
        position: relative;

        .image {
          width: 100%;
          height: 100%;
        }

        .c_content {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          padding: 110rpx 60rpx;
          color: #fff;
          display: flex;
          flex-direction: column;
          justify-content: space-around;

          .c_title {
            font-size: 32rpx;
          }

          .c_count {
            font-size: 50rpx;
            font-weight: bold;

            .c_icon {
              font-size: 32rpx;
            }
          }
        }
      }

      .c_tab {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 130rpx;
        padding: 20rpx 0;
        background-color: #fff;
        border-radius: 60rpx 60rpx 0 0;
      }
    }

    .body_card {
      color: #333;

      .card1 {
        background-color: #fff;

        .change_list {
          width: 720rpx;
          margin: 0 auto;
          display: flex;
          flex-wrap: wrap;

          .change_item {
            width: 220rpx;
            margin: 10rpx;
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            background-color: #f7f7f7;
            border-radius: 20rpx 20rpx 20rpx 20rpx;
            font-size: 40rpx;

            .c_icon {
              font-size: 28rpx;
            }
          }

          .change_item_active {
            background: rgba(#FF8056, 0.2);
            border: 5rpx solid #FF8056;
            color: #FF8056;
          }
        }

        .change_count {
          width: 700rpx;
          margin: 0 auto;
          border-radius: 20rpx;
          border: 5rpx solid #FF8056;
          color: #FF8056;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-left: 30rpx;
          margin-top: 30rpx;
          margin-bottom: 50rpx;

          .c_btn {
            display: flex;

            view {
              height: 80rpx;
              width: 60rpx;
              text-align: center;
              line-height: 80rpx;
            }
          }
        }

        .c_tips {
          width: 700rpx;
          margin: 0 auto;
          font-size: 26rpx;
          color: #616161;
          padding-bottom: 30rpx;

          .tips_title {
            font-size: 30rpx;
          }
        }
      }

      .card2 {
        background-color: #fff;

        .record {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 26rpx 20rpx;
          border-bottom: 1rpx solid #f7f7f7;

          .left {
            display: flex;

            image {
              height: 76rpx;
              width: 76rpx;
              margin-right: 20rpx;
            }

            .tips {
              font-size: 26rpx;
              color: #616161;
            }
          }

          .right {
            font-size: 36rpx;
          }
        }
        
        .no_data{
          padding: 60rpx 0;
          text-align: center;
          border-top: 1rpx solid #f7f7f7;
          color: #999;
          font-size: 26rpx;
        }
      }
    }

    .footer {
      position: fixed;
      left: 0;
      bottom: 0;
      height: 120rpx;
      width: 100vw;
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20rpx;

      .f_tip {
        display: flex;
        align-items: flex-end;
        font-style: 26rpx;

        .price {
          color: #FF8056;

          text {
            font-size: 44rpx;
            margin-left: 20rpx;
            margin-right: 5rpx;
          }
        }

      }

      .primary_btn {
        background-color: #fa8147;
        height: 80rpx;
        border-radius: 80rpx;
        width: 180rpx;
        color: #fff;
        line-height: 80rpx;
        text-align: center;
      }
    }
  }
</style>