<template>
  <view class="withdraw" catchtouchmove="true">
    <view class="withdraw_content">
      <view class="title">提现金额</view>
      <view class="content">
        <view>￥</view>
        <input type="digit" class="input" v-model="withdrawAmount" @blur="_valiteMoney" />
      </view>
      <view class="bottom">
        <text>当前可提现余额{{ maxWithdrawAmount }}元</text>
        <view style="color: #5baff4" @click="_getAll">全部提现</view>
      </view>
    </view>
    <button class="withdraw_btn" :class="isDisabled ? 'disabled' : ''" @click="_getMoney">确定提现</button>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import http from "@/utils/request";
import common from "@/utils/common";

const withdrawAmount = ref(0);
const maxWithdrawAmount = ref(0);
const isDisabled = ref(true);
const userInfo = ref({});
const loading = ref(false);

onMounted(() => {
  userInfo.value = uni.getStorageSync("userInfo");
  maxWithdrawAmount.value = userInfo.value.amount;
});

const _valiteMoney = (e) => {
  if (!isNaN(e.target.value)) {
    if (maxWithdrawAmount.value < e.target.value) {
      withdrawAmount.value = maxWithdrawAmount.value;
    } else withdrawAmount.value = e.target.value;
  } else {
    // 如果不是数字，可以设置为0或者其他默认值
    withdrawAmount.value = 0;
  }
};

const _getAll = () => {
  withdrawAmount.value = maxWithdrawAmount.value;
};

const _getMoney = common.debounce(async () => {
  if (isDisabled.value || loading.value) return;

  if (withdrawAmount.value < 0.1) {
    uni.showToast({ icon: "none", title: "提现金额不能小于0.1元" });
    return;
  }

  loading.value = true;
  uni.showLoading({ title: "正在发起提现..." });

  try {
    const loginRes = await uni.login({ provider: "weixin" });
    const response = await http.request("/api/wechat_transfer/transfer", { code: loginRes.code, amount: withdrawAmount.value }, "POST");

    if (response.code !== "success") {
      throw new Error(response.msg);
    }

    const systemInfo = uni.getSystemInfoSync();
    if (systemInfo.uniPlatform !== "mp-weixin" || !wx.canIUse("requestMerchantTransfer")) {
      throw new Error("你的微信版本过低，请更新至最新版本。");
    }

    await new Promise((resolve, reject) => {
      wx.requestMerchantTransfer({
        mchId: "1612111355",
        appId: wx.getAccountInfoSync().miniProgram.appId,
        package: response.data.package_info,
        success: resolve,
        fail: reject,
      });
    });

    uni.showModal({
      title: "温馨提示",
      content: "您已成功提现，请注意查看信息",
      showCancel: false,
      confirmText: "确认",
      success: (res) => {
        if (res.confirm) {
          _getUserInfo();
        }
      },
    });
  } catch (error) {
    uni.showModal({
      title: "温馨提示",
      content: error.message || "提现失败，请稍后再试",
      showCancel: false,
      confirmText: "确认",
    });
  } finally {
    loading.value = false;
    uni.hideLoading();
  }
}, 300);

const _getUserInfo = () => {
  http.request("api/custom/get_info").then((callback) => {
    if (callback.code == "success") {
      maxWithdrawAmount.value = callback.data.amount;
      console.log("callback.data", callback.data.amount);
      uni.setStorageSync("userInfo", callback.data);
    }
  });
};

watch(withdrawAmount, (newValue) => {
  isDisabled.value = isNaN(newValue) || newValue == 0;
});
</script>

<style lang="less" scoped>
.withdraw {
  width: 100vw;
  height: 100vh;
  padding: 46rpx 26rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  background-color: #ffffff;
  .withdraw_content {
    border: 1px solid #f3f3f3;
    border-radius: 6px;
    width: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    .title {
      font-weight: bold;
      margin-bottom: 36rpx;
    }
    .content {
      position: relative;
      border-bottom: 2rpx solid #f3f3f3;
      padding: 10rpx 0;
      box-sizing: border-box;
      input {
        width: 100%;
        height: 60rpx;
        font-size: 36rpx;
        border-radius: 6px;
        padding-left: 45rpx;
      }
      view {
        position: absolute;
        left: 5rpx;
        top: 50%;
        transform: translateY(-50%);
        font-size: 36rpx;
      }
    }
    .bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 28rpx;
      margin-top: 20rpx;
    }
  }
  .withdraw_btn {
    width: 100%;
    height: 70rpx;
    background-color: #169bd5;
    color: #ffffff;
    font-size: 36rpx;
    border-radius: 10rpx;
    line-height: 70rpx;
    box-shadow: 0rpx 5rpx 10rpx #169bd5;
    &.disabled {
      background-color: #97d2ec;
      color: #fff;
      box-shadow: none;
    }
  }
}
</style>
