<template>
  <view class="m_body">
    <view class="bg">
      <view class="bg_box">
        <image class="bg_img" mode="widthFix"
          src="https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/recharge.webp"></image>
        <view class="bg_border"></view>
      </view>
      <image @click="back" class="bg_back"
        src="https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/back.png"></image>
      <view class="body_card">
        <view class="card1">
          <view class="change_list">
            <view class="change_item" @click="changeItem(item, index)"
              v-for="(item, index) in changeList" :key="index">
              <image class="item_pic" :src="item.pic"></image>
              <view class="item_content">
                <view class="top_left"><text class="c_icon">¥</text> <text class="c_content">{{item.count}}</text></view>
                <view class="top_right">
                  <text>数量: </text>
                  <view @click="reduce(item)">- </view>
                  <view style="width: 80rpx;">{{item.num}} </view>
                  <view @click="append(item)">+ </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="a_tips">
        <view>礼包说明：</view>
        <view>购买1000-4999元礼包，补贴对应金额5%的现金抵扣补贴</view>
        <view>购买5000-9999元礼包，补贴对应金额10%的现金抵扣补贴</view>
        <view>购买10000-49999元礼包，补贴对应金额15%的现金抵扣补贴</view>
        <view>购买50000-100000元礼包，补贴对应金额20%的现金抵扣补贴</view>
      </view>
    </view>
    <view class="footer">
      <view class="f_tip">
        总计购买礼包金额:
        <view class="price">
          <text>{{total}}</text>元
        </view>
      </view>
      <view class="primary_btn" @click="$u.throttle(submitSub, 1500)">立即购买</view>
    </view>
    <uni-popup ref="redTipsRef">
      <view class="ref_ref">
        <view class="ref_top">
          购买礼包金额达到
          <text v-if="red_type==0">1000-4999</text>
          <text v-if="red_type==1">5000-9999</text>
          <text v-if="red_type==2">10000-49999</text>
          <text v-if="red_type==3">50000-100000</text>
        </view>
        <view class="ref_center">
          赠送补贴变为
        </view>
        <view class="ref_bottom">
          <view class="bottom_item" style="width: 100%;">
            <image src="https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/re_redpacket.webp"></image>
            <view class="text">{{tipType[red_type].red1}}</view>
          </view>
        </view>
      </view>
    </uni-popup>
    <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: [
          {
            count: 100, // 面额
            pic: 'https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/a_re_item5.webp',
            num: 0, //购买的个数
          },
          {
            count: 200,
            pic: 'https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/a_re_item6.webp',
            num: 0, //购买的个数
          },
          {
            count: 500,
            pic: 'https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/a_re_item7.webp',
            num: 0, //购买的个数
          },
          {
            count: 1000,
            pic: 'https://lihai001.oss-cn-chengdu.aliyuncs.com/public/uploads/new_activity/a_re_item8.webp',
            num: 0, //购买的个数
          }
        ],
        nowChange: 0,
        nowPrice: 0,
        priceCount: 1,
        isAuto: false, //没有授权的不会自动授权
        isShowAuth: false, //是否隐藏授权
        recordList: [],
        tipType: [
          {
            red1: '5%的现金抵扣补贴',
          },
          {
            red1: '10%的现金抵扣补贴',
          },
          {
            red1: '15%的现金抵扣补贴',
          },
          {
            red1: '20%的现金抵扣补贴',
          },
          {
            red1: '',
          },
        ],
        red_type: 4,
        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() {
      if (this.isLogin) {
        this.getUserInfo()
      } else {
        this.isAuto = true;
        this.isShowAuth = true
      }
    },
    onShow() {
    },
    computed: {
      ...mapGetters(['isLogin', 'viewColor', 'keyColor']),
      total() {
        return this.changeList.reduce((t, obj)=>{
          return t + (obj.count * obj.num);
        }, 0);
      }
    },
    onReachBottom() {
      this.getCommissionInfo();
    },
    methods: {
      back(){
        uni.navigateBack();
      },
      clickTab1(e) {
        this.curNow = e.index;
        if (e.index == 1) {
          this.recordList = [];
          this.where.page = 1;
          this.getCommissionInfo();
        }
      },
      changeItem(e, index) {
        this.nowPrice = e;
        this.nowChange = index;
        if (this.priceCount * this.nowPrice > 100000) {
          this.priceCount = Math.floor(100000 / this.nowPrice);
          return Toast('不可超过10万元');
        }
      },
      append(item) {
        if(this.total + item.count >=0 &&  this.total + item.count <1000) this.red_type = 4;
        else if(this.total + item.count >=1000 &&  this.total + item.count <=4999 && this.red_type != 0){
          this.red_type = 0;
          this.$refs.redTipsRef.open();
        }else if(this.total + item.count >=5000 &&  this.total + item.count <=9999 && this.red_type != 1){
          this.red_type = 1;
          this.$refs.redTipsRef.open();
        }else if(this.total + item.count >=10000 &&  this.total + item.count <=49999 && this.red_type != 2){
          this.red_type = 2;
          this.$refs.redTipsRef.open();
        }else if(this.total + item.count >=50000 &&  this.total + item.count <=100000 && this.red_type != 3){
          this.red_type = 3;
          this.$refs.redTipsRef.open();
        }
        if (this.total + item.count > 100000 || this.total>=100000) {
          return Toast('不可超过10万元');
        } else item.num++;
      },
      reduce(item) {
        if(this.total - item.count >=0 &&  this.total - item.count <1000) this.red_type = 4;
        else if(this.total - item.count >=1000 &&  this.total - item.count <=4999 && this.red_type != 0){
          this.red_type = 0;
          this.$refs.redTipsRef.open();
        }else if(this.total - item.count >=5000 &&  this.total - item.count <=9999 && this.red_type != 1){
          this.red_type = 1;
          this.$refs.redTipsRef.open();
        }else if(this.total - item.count >=10000 &&  this.total - item.count <=49999 && this.red_type != 2){
          this.red_type = 2;
          this.$refs.redTipsRef.open();
        }else if(this.total - item.count >=50000 &&  this.total - item.count <=100000 && this.red_type != 3){
          this.red_type = 3;
          this.$refs.redTipsRef.open();
        }
        if (this.total==0||item.num==0) return Toast('不能再少啦');
        else item.num--;
      },
      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))
                  uni.showToast({
                    icon: 'success',
                    title: '转入成功'
                  })
                  // 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();
            Toast(res.message)
            // return that.$util.Tips({
            // 	title: res.message
            // }, {
            // 	tab: 5,
            // 	url: goPages
            // });
            break;
          case 'success':
            uni.hideLoading();
            uni.showToast({
              icon: 'success',
              title: res.message
            })
            // 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 => {
              uni.showToast({
                icon: 'success',
                title: res.message
              })
              // return that.$util.Tips({
              // 	title: res.message,
              // 	icon: 'success'
              // }, {
              // 	tab: 4,
              // 	url: goPages
              // });
            }).catch(res => {
              uni.showToast({
                icon: 'success',
                title: '取消支付'
              })
              // 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) => {
                this.getUserInfo()
                uni.showToast({
                  icon: 'success',
                  title: '支付成功'
                })
                // 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) {

                  }
                })
              },
              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')
                uni.showToast({
                  icon: 'success',
                  title: '支付成功'
                })
                // return that.$util.Tips({
                // 	title: '支付成功',
                // 	icon: 'success'
                // }, {
                // 	tab: 5,
                // 	url: goPages
                // });
              },
              fail: function(e) {
                uni.hideLoading();
                Toast('取消支付')
                // return that.$util.Tips({
                // 	title: '取消支付'
                // }, {
                // 	tab: 5,
                // 	url: goPages
                // });
              },
            })
            break;
            // #endif
          case "balance":
            uni.hideLoading();
            //余额不足
            Toast(res.msg)
            // 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) => {
                this.getUserInfo()
                uni.showToast({
                  icon: 'success',
                  title: '支付成功'
                })
                // 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">
  page {
    background-color: #fff;
  }
  .bg {
    position: relative;
    padding-bottom: 300rpx;
    
    .bg_box{
      height: 486rpx;
      position: relative;
      overflow: hidden;
      .bg_img {
        width: 750rpx;
        height: 652rpx;
        position: absolute;
        top: 0;
        left: 0;
      }
      .bg_border{
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 30rpx;
        border-radius: 60rpx 60rpx 0 0;
        background-color: #fff;
      }
    }

    .bg_back {
      height: 34rpx;
      width: 20rpx;
      position: absolute;
      top: calc(var(--status-bar-height) + 30rpx);
      left: 30rpx;
    }

      .body_card {
        color: #333;
    
        .card1 {
          background-color: #fff;
    
          .change_list {
            width: 700rpx;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
    
            .change_item {
              width: 335rpx;
              height: 172rpx;
              text-align: center;
              // background-color: #f7f7f7;
              border-radius: 20rpx 20rpx 20rpx 20rpx;
              font-size: 40rpx;
              position: relative;
              margin-bottom: 30rpx;
              
              .item_pic{
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
              }
              
              .item_content{
                padding: 26rpx;
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 172rpx;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                
                .top_left{
                  font-size: 58rpx;
                  color: #ffc53d;
                  display: flex;
                  align-content: center;
                  .tips{
                    font-size: 24rpx;
                    border: 5rpx solid #ffc53d;
                    margin-left: 20rpx;
                    padding: 5rpx 15rpx;
                    border-radius: 60rpx;
                    color: #7C5906;
                  }
                  .c_content{
                    padding-top: 10rpx;
                  }
                  .c_icon {
                    padding-top: 15rpx;
                    font-size: 36rpx;
                  }
                }
                .top_right{
                  display: flex;
                  align-items: center;
                  color: #FF3A32;
                  text{
                    font-size: 28rpx;
                  }
                  view{
                    height: 60rpx;
                    width: 40rpx;
                    text-align: center;
                    line-height: 60rpx;
                  }
                }
                
              }
    
            }
    
            .change_item_active {
              background: rgba(#FF8056, 0.2);
              border: 5rpx solid #FF8056;
              color: #FF8056;
            }
          }
    
        }
    
      }

    .a_tips{
      color: #FF8056;
      padding: 0 30rpx;
      line-height: 40rpx;
    }

  }

  .m_body {

    .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;
      }
    }
  }
  .ref_ref{
    width: 630rpx;
    height: 200rpx;
    background-color: #fff;
    border-radius: 20rpx;
    padding: 20rpx 10rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    .ref_top{
      color: #ffc53d;
    }
    .ref_center{
      font-size: 24rpx;
      border: 5rpx solid #ffc53d;
      margin-left: 20rpx;
      padding: 5rpx 15rpx;
      border-radius: 60rpx;
      color: #7C5906;
    }
    .ref_bottom{
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #FF3A32;
      .bottom_item{
        width: 280rpx;
        display: flex;
        align-items: center;
        image{
          width: 32rpx;
          height: 40rpx;
        }
        .text{
          padding-left: 15rpx;
        }
      }
    }
  }
</style>