<template>
  <view class="recharge">
    <view class="rec-box">
      <view class="rec-title">我的余额</view>
      <view class="rec-balance"
        >&yen;{{
          userInfo.show_price && Number(userInfo.show_price)
            ? userInfo.show_price
            : "0.00"
        }}</view
      >
      <view class="rec-desc"
        >余额可用于抽赏交易等功能。充值可以给您带来更好的产品体验</view
      >
    </view>
    <view class="rec-box">
      <view class="rec-title">充值</view>
      <view class="rec-list">
        <view
          v-for="(item, idx) in rechargeList"
          :key="item.num"
          :class="['rec-item', { 'rec-item-selected': idx === selected }]"
          @click="
            selected = idx;
            inputValue = '';
          "
        >
          <view class="rec-money">{{ item.text }}</view>
          <view class="rec-label">{{ item.getNum }}</view>
        </view>
      </view>
      <view class="rec-input">
        <view class="rec-input-label">&yen;</view>
        <input
          v-model="inputValue"
          type="digit"
          placeholder="请输入自定义充值金额"
          @focus="selected = -1"
        />
      </view>
      <button class="rec-btn" @click="handlePay">立即充值</button>
    </view>
  </view>
</template>

<script>
import login from "@/lib/utils/login";
import api from "@/lib/api/api";

export default {
  name: "PageMyRecharge",
  data() {
    return {
      testInt: 1,
      selected: -1,
      rechargeList: [
        {
          text: "充200",
          num: 200,
          type: 1,
          getNum: "得205",
        },
        {
          text: "充300",
          num: 300,
          type: 1,
          getNum: "得310",
        },
        {
          text: "充500",
          num: 500,
          type: 1,
          getNum: "得520",
        },
        {
          text: "充1000",
          num: 1000,
          type: 1,
          getNum: "得1050",
        },
      ],
      userInfo: {},
      inputValue: "",
    };
  },
  watch: {
    inputValue(newValue) {
      if (newValue.trim() === "") {
        return;
      }

      if (isNaN(Number(newValue))) {
        let str = newValue;
        const dot = newValue.match(/\./g);
        if (dot && dot.length > 1) {
          const arr = newValue.split(".");
          arr.length = 2;
          str = arr.join(".");
        }

        if (isNaN(str) && !isNaN(parseFloat(str))) {
          str = `${parseFloat(str)}`;
        }

        if (!isNaN(str)) {
          this.$nextTick(() => {
            this.inputValue = `${Number(Number(str).toFixed(2))}`;
          });
        }
        return;
      }

      if (/\.$/.test(newValue) || /\.0+$/.test(newValue)) {
        return;
      }

      this.$nextTick(() => {
        this.inputValue = `${Number(Number(newValue).toFixed(2))}`;
      });
    },
  },
  onShow() {
    const uinfoStr = uni.getStorageSync("userinfo");
    if (uinfoStr) {
      this.userInfo = JSON.parse(uinfoStr);
      this.getUserInfo();
    } else {
      this.userInfo = {};
    }
  },
  onPullDownRefresh() {
    if (JSON.stringify(this.userInfo) == "{}") {
      uni.stopPullDownRefresh(); //得到数据后停止下拉刷新
      return;
    }
    this.getUserInfo();
  },
  methods: {
    //获取个人信息
    getUserInfo() {
      api
        .userInfo(this.userInfo.session)
        .then((data) => {
          this.userInfo.show_price = data.data.show_price;
          this.userInfo.balance_info = data.data.balance_info;
          uni.setStorageSync("userinfo", JSON.stringify(this.userInfo));
          uni.stopPullDownRefresh(); //得到数据后停止下拉刷新
        })
        .catch((e) => {
          console.error(e);
        });
    },
    handlePay() {
      if (this.selected !== -1 && this.rechargeList[this.selected]) {
        return this.activeChange(this.rechargeList[this.selected].num);
      }
      if (this.inputValue) {
        if (!isNaN(Number(this.inputValue)) && Number(this.inputValue) >= 1) {
          return this.activeChange(this.inputValue);
        }
        if (isNaN(Number(this.inputValue))) {
          uni.showToast({
            title: "请输入正确的金额",
            icon: "none",
          });
        } else {
          uni.showToast({
            title: "充值金额不得小于1元",
            icon: "none",
          });
        }
        return;
      }
      uni.showToast({
        title: "请先登录",
        icon: "none",
      });
    },
    async activeChange(num) {
      if (JSON.stringify(this.userInfo) == "{}") {
        uni.showToast({
          title: "请先登录",
          icon: "none",
        });
        await this.login();
      }

      // 微信充值
      uni.showToast({
        title: "充值中",
        icon: "loading",
        mask: true,
        duration: 10e3,
      });

      try {
        const data = await api.getPrepay({
          session: this.userInfo.session,
          amount: "" + num,
        });

        uni.hideToast();
        uni.requestPayment({
          provider: "wxpay",
          timeStamp: data.data.timeStamp,
          nonceStr: data.data.nonceStr,
          package: data.data.package,
          signType: data.data.signType,
          paySign: data.data.paySign,
          success: (res) => {
            if (res.errMsg === "requestPayment:ok") {
              this.getPrepaySucceed(data.data.order_id);
            }
          },
          fail: (err) => {
            if (err.errMsg === "requestPayment:fail cancel") {
              this.getPrepayStatus("3", data.data.order_id);
            } else {
              this.getPrepayStatus("2", data.data.order_id);
            }
          },
        });
      } catch (e) {}
    },
    getPrepayStatus(type, id) {
      const params = {
        session: this.userInfo.session,
        order_id: "" + id,
        type: "" + type,
      };
      return api
        .getPrepayStatus(params)
        .then(() => {
          uni.showToast({
            title: type == "3" ? "取消支付" : "支付失败",
            icon: "error",
            mask: true,
            duration: 2e3,
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    getPrepaySucceed(id) {
      let timer;
      api
        .getPrepaySucceed({
          session: this.userInfo.session,
          order_id: "" + id,
          times: "" + this.testInt++,
        })
        .then((data) => {
          if (data.errno == 90000) {
            if (this.queryPayIng) {
              this.queryPayIng = false;
              uni.showLoading({
                title: "加载中",
                mask: true,
              });
            }
            timer = setTimeout(() => {
              this.getPrepaySucceed(id);
            }, 1000);
          } else if (data.errno == 10000) {
            this.queryPayIng = true;
            uni.hideLoading();
            uni.showToast({
              title: "支付成功",
              icon: "success",
              mask: true,
              duration: 2e3,
            });
            if (data.data.status == 2) {
              this.getUserInfo();
            }
            clearTimeout(timer); //清理定时任务
          } else {
            this.queryPayIng = true;
            uni.hideLoading();
            uni.showToast({
              title: "订单查询失败",
              icon: "error",
              mask: true,
              duration: 2e3,
            });
            clearTimeout(timer); //清理定时任务
          }
        })
        .catch(() => {
          this.queryPayIng = true;
          uni.hideLoading();
          clearTimeout(timer); //清理定时任务
        });
    },
    // 获取用户头像和昵称
    login() {
      return new Promise((resolve, reject) => {
        login.wxLogin((userInfo) => {
          if (userInfo.session) {
            this.userInfo = userInfo;
            if (userInfo.coupons && userInfo.coupons.is_bind_coupon === 1) {
              uni.showToast({
                icon: "none",
                title: userInfo.coupons.is_bind_info || "登录成功~",
                duration: 2e3,
                mask: true,
              });
              setTimeout(() => {
                resolve();
              }, 2000);
            } else {
              resolve();
            }
          } else reject();
        });
      });
    },
  },
};
</script>

<style lang="scss">
.recharge {
  padding: 20rpx 30rpx;
  min-height: 100vh;
  background: #f6f6f6;
  box-sizing: border-box;
  .rec-box {
    margin-bottom: 20rpx;
    padding: 34rpx 30rpx 36rpx;
    background: #fff;
  }
  .rec-title {
    margin-bottom: 22rpx;
    font-size: 34rpx;
    font-weight: 600;
    color: #222222;
    line-height: 48rpx;
  }
  .rec-balance {
    height: 80rpx;
    font-size: 68rpx;
    font-weight: bold;
    color: #222222;
    line-height: 80rpx;
    text-align: center;
  }
  .rec-desc {
    width: 520rpx;
    font-size: 24rpx;
    color: #888888;
    line-height: 28rpx;
    margin: 24rpx auto 0;
    text-align: center;
  }
  .rec-list {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10rpx;
  }
  .rec-item {
    width: 304rpx;
    height: 132rpx;
    background: #fafafa;
    border: 2rpx solid #dddddd;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin: 10rpx;
    .rec-money {
      height: 48rpx;
      font-size: 34rpx;
      font-weight: 600;
      color: #222222;
      line-height: 48rpx;
    }
    .rec-label {
      box-sizing: border-box;
      min-width: 160rpx;
      height: 38rpx;
      overflow: hidden;
      text-align: center;
      background: #d0d0d0;
      border-radius: 68rpx;
      opacity: 1;
      padding: 0 36rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 8rpx;
    }
    &.rec-item-selected {
      background: rgba(78, 251, 255, 0.1);
      border-color: #27cacb;
      .rec-money {
        color: #08c2c3;
      }
      .rec-label {
        background: #08c2c3;
      }
    }
  }
  .rec-input {
    margin-top: 20rpx;
    height: 94rpx;
    display: flex;
    border-bottom: 1rpx solid #dddddd;
    .rec-input-label {
      align-self: center;
      font-size: 44rpx;
      color: #222222;
      line-height: 52rpx;
      margin-right: 20rpx;
    }
    input {
      display: block;
      appearance: none;
      height: 100%;
      width: 0;
      flex: 1;
      font-size: 38rpx;
      color: #222;
      font-weight: bold;
      &::placeholder {
        font-weight: normal;
        color: #aaaaaa;
      }
    }
  }
  .rec-btn {
    display: block;
    width: 100%;
    height: 96rpx;
    background: url(@/assets/my/icon-btn.png) no-repeat center;
    background-size: 100% 100%;
    border: 0 none;
    margin-top: 42rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #292d3b;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;

    &::after {
      display: none;
    }
  }
}
</style>
