<template>
  <view class="withdraw-container">
    <!-- 顶部余额展示 -->
    <view class="balance-section">
      <view class="balance-bg">
        <view class="balance-title">可提现余额</view>
        <view class="balance-amount">¥ {{ appStore?.$userInfo?.nowMoney || 0 }}</view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 到账账户 -->
      <view class="section" v-if="!appStore.$wxConfig?.auditModeEnabled">
        <view class="section-title">到账账户</view>
        <view class="account-item" @click="goToBankManage">
          <view class="account-info">
            <view class="bank-icon">
              <text
                :style="{
                  color:
                    defaultAccount?.accountType === 1 ? '#f2cb51' : '#019FE8',
                }"
                class="iconfont"
                :class="[
                  defaultAccount?.accountType === 1
                    ? 'icon-qianbao'
                    : 'icon-zhifubao',
                ]"
              ></text>
            </view>
            <view class="account-details" v-if="defaultAccount">
              <text
                class="account-number"
                v-if="defaultAccount.accountType === 1"
                >{{ defaultAccount.bankName }}({{
                  formatCardNumber(defaultAccount.accountNumber)
                }})</text
              >
              <text class="account-number" v-else
                >{{ defaultAccount.accountName }}({{
                  formatCardNumber(defaultAccount.accountNumber)
                }})</text
              >
            </view>
          </view>
          <view class="arrow">{{ ">" }}</view>
        </view>
      </view>

      <!-- 提现金额 -->
      <view class="section">
        <view class="section-title">提现金额</view>
        <view class="amount-input-container">
          <view class="currency-symbol">¥</view>
          <input
            class="amount-input"
            type="digit"
            v-model="withdrawAmount"
            placeholder="请输入提现金额"
            @input="onAmountInput"
          />
          <view class="withdraw-all" @click="withdrawAll">全部提现</view>
        </view>
        <view class="balance-info"
          >账户余额{{ appStore.$userInfo.nowMoney }}元</view
        >
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button
          class="submit-btn"
          :class="{ disabled: !canSubmit }"
          @click="submitWithdraw"
        >
          提交申请
        </button>
      </view>
    </view>
    <!-- 协议窗口 -->
    <up-parse :content="content"></up-parse>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { withdrawToCard } from "@/api/user";
import { onShow } from "@dcloudio/uni-app";
import { useAppStore } from "@/stores/app";
import { getDefaultAccount, getUserInfo, agreementGetoneApi } from "@/api/user";

// 响应式数据
const availableBalance = ref("5733.67");
const withdrawAmount = ref("");
const defaultAccount = ref(null);
const appStore = useAppStore();
const content = ref("");
// 计算属性
const canSubmit = computed(() => {
  return withdrawAmount.value && parseFloat(withdrawAmount.value) > 0;
});
// 获取协议
function agreementGetoneFn() {
  // 资产说明
  agreementGetoneApi({ name: "withraw" }).then((res) => {
    content.value = res.data?.content;
  });
}
onShow(() => {
  agreementGetoneFn();
  fetchDefaultAccount();
  fetchUserInfo();
});

async function fetchUserInfo() {
  try {
    const { data } = await getUserInfo();
    appStore.UPDATE_USERINFO(data);
  } catch (error) {
    console.error("getUserInfo", error);
  }
}

// 获取默认账户详情
async function fetchDefaultAccount() {
  try {
    const { data } = await getDefaultAccount();
    defaultAccount.value = data;
  } catch (error) {
    console.error("getDefaultAccount", error);
  }
}

const formatCardNumber = (cardNumber) => {
  // 显示卡号，只显示后4位，其他用*代替
  if (cardNumber.length <= 4) return cardNumber;
  const lastFour = cardNumber.slice(-4);
  return `****${lastFour}`;
};

// 方法
const onAmountInput = (e) => {
  let value = e.detail.value;
  // 限制输入格式，只允许数字和小数点
  value = value.replace(/[^0-9.]/g, "");
  // 限制小数点后两位
  if (value.includes(".")) {
    const parts = value.split(".");
    if (parts[1] && parts[1].length > 2) {
      value = parts[0] + "." + parts[1].substring(0, 2);
    }
  }
  withdrawAmount.value = value;
};

const withdrawAll = () => {
  withdrawAmount.value = appStore.$userInfo.nowMoney;
};

const goToBankManage = () => {
  uni.navigateTo({
    url: "/pages/users/card_page/index",
  });
};

const submitWithdraw = () => {
  if (!canSubmit.value) return;
  if (!defaultAccount.value || !defaultAccount.value.id) {
    uni.showToast({
      title: "请选择提现账户",
      icon: "none",
    });
    return;
  }

  // 提交提现申请
  uni.showModal({
    title: "提示",
    content: `确认提现 ¥${withdrawAmount.value} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          if (
            Number(withdrawAmount.value) > Number(appStore.$userInfo.nowMoney)
          ) {
            return uni.showToast({
              title: "余额不足",
            });
          }
          // 提现方式| alipay=支付宝,bank=银行卡,weixin=微信
          const extractType =
            defaultAccount.value.accountType === 1 ? "bank" : "alipay";
          // 提现金额
          const money = withdrawAmount.value;
          // // 姓名
          const name = defaultAccount.value.accountName;
          const alipayParams = {
            alipayCode: defaultAccount.value.accountNumber, // 支付宝账号
            extractType,
            name,
            money,
          };
          const bankParams = {
            extractType,
            bankName: defaultAccount.value.bankName, // 提现银行名称
            cardum: defaultAccount.value.accountNumber, // 银行卡
            money,
            name,
          };
          const params =
            defaultAccount.value.accountType === 1 ? bankParams : alipayParams;

          await withdrawToCard(params);
          // fetchUserInfo()
          const { data } = await getUserInfo();
          appStore.UPDATE_USERINFO(data);
          uni.showToast({
            title: "提现申请已提交",
            icon: "success",
          });
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/users/vault/index",
            });
          }, 1000);
        } catch (error) {
          console.error("withdrawToCard", error);
          const title = typeof error === "string" ? error : "提现失败";
          uni.showToast({
            title,
            duration: 2000,
          });
        } finally {
          withdrawAmount.value = "";
        }
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.withdraw-container {
  min-height: 90vh;
  width: 100%;

  display: flex;
  flex-direction: column;
  align-items: center;
  .balance-section {
    width: 100%;
    padding: 40rpx 30rpx 140rpx;
    margin: 0 0 -100rpx;
    background-image: linear-gradient(
      to bottom,
      $header-color 0%,
      $header-color 10%,
      #f0dab2 70%,
      transparent 100%
    );

    .balance-bg {
      padding: 50rpx 40rpx;
      position: relative;
      overflow: hidden;

      &::after {
        content: "";
        position: absolute;
        bottom: -30%;
        left: -20%;
        width: 150rpx;
        height: 150rpx;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 50%;
      }

      .balance-title {
        color: rgba(255, 255, 255, 0.9);
        font-size: 28rpx;
        margin-bottom: 16rpx;
        font-weight: 400;
      }

      .balance-amount {
        color: #fff;
        font-size: 56rpx;
        font-weight: 600;
        letter-spacing: 2rpx;
      }
    }
  }

  .main-content {
    width: 100%;
    padding: 40rpx 40rpx;
    box-sizing: border-box;
    background: #fff;
    border-radius: 32rpx 32rpx 0 0;
    margin-top: -20rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);

    .section {
      margin-bottom: 50rpx;

      .section-title {
        color: #333;
        font-size: 32rpx;
        font-weight: 600;
        margin-bottom: 24rpx;
        position: relative;

        &::before {
          content: "";
          position: absolute;
          left: -16rpx;
          top: 50%;
          transform: translateY(-50%);
          width: 6rpx;
          height: 32rpx;
          background: #e9c279;
          border-radius: 3rpx;
        }
      }

      .account-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 24rpx;
        background: #f8f9fa;
        border-radius: 16rpx;
        border: 2rpx solid #e9ecef;
        transition: all 0.3s ease;

        &:active {
          background: #f0f0f0;
          transform: scale(0.98);
        }

        .account-info {
          display: flex;
          align-items: center;

          .bank-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 24rpx;

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

          .account-details {
            .account-number {
              color: #333;
              font-size: 30rpx;
              font-weight: 500;
            }
          }
        }

        .arrow {
          color: #999;
          font-size: 32rpx;
          font-weight: 300;
        }
      }

      .amount-input-container {
        display: flex;
        align-items: center;
        background-color: #ededed;
        border-radius: 15rpx;
        padding: 25rpx 24rpx;

        transition: border-color 0.3s ease;

        &:focus-within {
          border-color: #e9c279;
        }

        .currency-symbol {
          color: #333;
          font-size: 32rpx;
          font-weight: 600;
          margin-right: 16rpx;
        }

        .amount-input {
          height: 100%;
          flex: 1;
          display: flex;
          align-items: center;
          color: #333;
          font-weight: 600;
          font-size: 26rpx;

          &::placeholder {
            color: #999;
            font-weight: 400;
          }
        }

        .withdraw-all {
          color: #e9c279;
          font-size: 28rpx;
          font-weight: 500;
          transition: all 0.3s ease;

          &:active {
            background: #e9c279;
            color: #fff;
          }
        }
      }

      .balance-info {
        color: #666;
        font-size: 24rpx;
        margin-top: 16rpx;
        padding-left: 8rpx;
      }
    }

    .submit-section {
      width: 100%;
      display: flex;
      justify-content: center;

      .submit-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 400rpx;
        height: 75rpx;
        background: linear-gradient(135deg, #e9c279 0%, #d4a853 100%);
        color: #fff;
        border-radius: 50rpx;
        font-size: 30rpx;
        border: none;
        box-shadow: 0 6rpx 20rpx rgba(233, 194, 121, 0.3);
        transition: all 0.3s ease;

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 12rpx rgba(233, 194, 121, 0.2);
        }

        &.disabled {
          background: #e9ecef;
          color: #adb5bd;
          box-shadow: none;

          &:active {
            transform: none;
          }
        }
      }
    }

    .tips-section {
      padding: 30rpx 0;

      .tips-title {
        color: #333;
        font-size: 28rpx;
        font-weight: 600;
        margin-bottom: 16rpx;
      }

      .tips-item {
        color: #666;
        font-size: 26rpx;
        line-height: 40rpx;
        margin-bottom: 8rpx;
      }

      .tips-note {
        color: #999;
        font-size: 24rpx;
        line-height: 36rpx;
        margin-top: 8rpx;
      }
    }
  }
}
</style>
