<template>
  <view class="page-withdraw">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @tap="goBack">
        <u-icon name="arrow-left" :size="20" color="#1A1A1A" />
      </view>
      <text class="navbar-title">申请提现</text>
      <view class="navbar-right"></view>
    </view>

    <scroll-view scroll-y class="withdraw-content">
      <!-- 可用余额 -->
      <view class="balance-card">
        <text class="balance-label">可提现金额（元）</text>
        <text class="balance-value">¥{{ formatMoney(availableBalance) }}</text>
      </view>

      <!-- 提现表单 -->
      <view class="form-card">
        <!-- 提现金额 -->
        <view class="form-item">
          <text class="item-label">提现金额</text>
          <view class="amount-input-wrapper">
            <text class="amount-symbol">¥</text>
            <input
              v-model="form.amount"
              type="digit"
              class="amount-input"
              placeholder="请输入提现金额"
              :maxlength="10"
            />
            <view class="all-btn" @tap="withdrawAll">
              <text class="all-text">全部</text>
            </view>
          </view>
          <text v-if="amountError" class="error-text">{{ amountError }}</text>
        </view>

        <!-- 账户类型 -->
        <view class="form-item">
          <text class="item-label">账户类型</text>
          <view class="account-types">
            <view
              v-for="type in accountTypes"
              :key="type.value"
              :class="['type-item', { active: form.accountType === type.value }]"
              @tap="form.accountType = type.value"
            >
              <u-icon :name="type.icon" :size="24" :color="form.accountType === type.value ? '#FF6B35' : '#999'" />
              <text class="type-text">{{ type.label }}</text>
            </view>
          </view>
        </view>

        <!-- 账户信息 -->
        <view class="form-item">
          <text class="item-label">账户姓名</text>
          <input
            v-model="form.accountName"
            class="text-input"
            placeholder="请输入账户姓名"
            :maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="item-label">账户号码</text>
          <input
            v-model="form.accountNumber"
            class="text-input"
            placeholder="请输入账户号码"
            :maxlength="30"
          />
        </view>

        <view v-if="form.accountType === 'bank'" class="form-item">
          <text class="item-label">开户银行</text>
          <input
            v-model="form.bankName"
            class="text-input"
            placeholder="请输入开户银行"
            :maxlength="50"
          />
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="tips-card">
        <view class="tips-header">
          <u-icon name="info-circle" :size="16" color="#FF6B35" />
          <text class="tips-title">提现说明</text>
        </view>
        <view class="tips-list">
          <text class="tips-item">• 提现金额将在1-3个工作日内到账</text>
          <text class="tips-item">• 单笔提现金额不得低于100元</text>
          <text class="tips-item">• 请确保账户信息准确，否则可能导致提现失败</text>
          <text class="tips-item">• 提现申请提交后不可撤销</text>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 提交按钮 -->
    <view class="submit-bar">
      <view class="submit-btn" :class="{ disabled: submitting }" @tap="handleSubmit">
        <text class="submit-text">{{ submitting ? '提交中...' : '提交申请' }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { financeApi } from '@/api/seller/finance';

const availableBalance = ref(0);
const submitting = ref(false);

const form = ref({
  amount: '',
  accountType: 'alipay',
  accountName: '',
  accountNumber: '',
  bankName: '',
});

const accountTypes = [
  { label: '支付宝', value: 'alipay', icon: 'pay-circle' },
  { label: '微信', value: 'wechat', icon: 'weixin' },
  { label: '银行卡', value: 'bank', icon: 'credit-card' },
];

const amountError = computed(() => {
  if (!form.value.amount) return '';
  const amount = Number(form.value.amount);
  if (isNaN(amount) || amount <= 0) return '请输入有效金额';
  if (amount < 100) return '单笔提现金额不得低于100元';
  if (amount > availableBalance.value) return '提现金额不能超过可用余额';
  return '';
});

onMounted(() => {
  fetchWallet();
});

async function fetchWallet() {
  try {
    const res = await financeApi.getWallet();
    availableBalance.value = res.data.availableBalance || 0;
  } catch (e: any) {
    console.error('获取钱包信息失败:', e);
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  }
}

function withdrawAll() {
  form.value.amount = availableBalance.value.toString();
}

function formatMoney(value: number | string): string {
  const num = Number(value || 0);
  return num.toFixed(2);
}

async function handleSubmit() {
  if (submitting.value) return;

  // 验证表单
  if (!form.value.amount) {
    uni.showToast({ title: '请输入提现金额', icon: 'none' });
    return;
  }

  if (amountError.value) {
    uni.showToast({ title: amountError.value, icon: 'none' });
    return;
  }

  if (!form.value.accountName) {
    uni.showToast({ title: '请输入账户姓名', icon: 'none' });
    return;
  }

  if (!form.value.accountNumber) {
    uni.showToast({ title: '请输入账户号码', icon: 'none' });
    return;
  }

  if (form.value.accountType === 'bank' && !form.value.bankName) {
    uni.showToast({ title: '请输入开户银行', icon: 'none' });
    return;
  }

  // 确认提现
  uni.showModal({
    title: '确认提现',
    content: `确认提现 ¥${formatMoney(form.value.amount)} 到${getAccountTypeLabel(form.value.accountType)}？`,
    success: async (res) => {
      if (res.confirm) {
        await submitWithdraw();
      }
    },
  });
}

async function submitWithdraw() {
  submitting.value = true;

  try {
    await financeApi.withdraw({
      amount: Number(form.value.amount),
      accountType: form.value.accountType,
      accountName: form.value.accountName,
      accountNumber: form.value.accountNumber,
      bankName: form.value.bankName || undefined,
    });

    uni.showToast({ title: '提现申请已提交', icon: 'success' });

    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (e: any) {
    console.error('提现申请失败:', e);
    uni.showToast({ title: e.message || '提交失败', icon: 'none' });
  } finally {
    submitting.value = false;
  }
}

function getAccountTypeLabel(type: string): string {
  const typeMap: Record<string, string> = {
    alipay: '支付宝',
    wechat: '微信',
    bank: '银行卡',
  };
  return typeMap[type] || type;
}

function goBack() {
  uni.navigateBack();
}
</script>

<style lang="scss" scoped>
.page-withdraw {
  min-height: 100vh;
  background: #F5F7FA;
  display: flex;
  flex-direction: column;
  padding-bottom: 120rpx;
}

/* 导航栏 */
.navbar {
  background: #ffffff;
  padding: 0 24rpx;
  border-bottom: 1rpx solid #F0F0F0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
}

.navbar-left,
.navbar-right {
  width: 80rpx;
  display: flex;
  align-items: center;
}

.navbar-left {
  justify-content: flex-start;
  padding: 12rpx;
  margin-left: -12rpx;
  transition: opacity 0.3s ease;

  &:active {
    opacity: 0.6;
  }
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* 提现内容 */
.withdraw-content {
  flex: 1;
  overflow-y: auto;
}

/* 余额卡片 */
.balance-card {
  margin: 24rpx 24rpx 16rpx;
  padding: 40rpx 32rpx;
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 53, 0.3);
  text-align: center;
}

.balance-label {
  display: block;
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 12rpx;
}

.balance-value {
  display: block;
  font-size: 56rpx;
  font-weight: 700;
  color: #ffffff;
}

/* 表单卡片 */
.form-card {
  margin: 0 24rpx 16rpx;
  padding: 24rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.form-item {
  margin-bottom: 32rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-label {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 16rpx;
}

.amount-input-wrapper {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background: #F5F7FA;
  border-radius: 16rpx;
  gap: 8rpx;
}

.amount-symbol {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.amount-input {
  flex: 1;
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.all-btn {
  padding: 8rpx 20rpx;
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  border-radius: 24rpx;
  transition: opacity 0.3s ease;

  &:active {
    opacity: 0.7;
  }
}

.all-text {
  font-size: 24rpx;
  color: #ffffff;
}

.error-text {
  display: block;
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #FF4D4F;
}

.account-types {
  display: flex;
  gap: 16rpx;
}

.type-item {
  flex: 1;
  padding: 24rpx 16rpx;
  background: #F5F7FA;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;

  &.active {
    background: #FFF5F0;
    border-color: #FF6B35;
  }

  &:active {
    opacity: 0.7;
  }
}

.type-text {
  font-size: 24rpx;
  color: #666;

  .active & {
    color: #FF6B35;
    font-weight: 600;
  }
}

.text-input {
  width: 100%;
  padding: 24rpx;
  background: #F5F7FA;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #1A1A1A;
}

/* 提示卡片 */
.tips-card {
  margin: 0 24rpx 16rpx;
  padding: 24rpx;
  background: #FFF7E6;
  border-radius: 16rpx;
}

.tips-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 16rpx;
}

.tips-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #FF6B35;
}

.tips-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.tips-item {
  font-size: 24rpx;
  color: #999;
  line-height: 1.6;
}

/* 底部占位 */
.bottom-placeholder {
  height: 40rpx;
}

/* 提交按钮 */
.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16rpx 24rpx;
  background: #ffffff;
  border-top: 1rpx solid #F0F0F0;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
}

.submit-btn {
  width: 100%;
  padding: 28rpx;
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  border-radius: 48rpx;
  text-align: center;
  transition: all 0.3s ease;

  &:active:not(.disabled) {
    transform: scale(0.98);
    opacity: 0.9;
  }

  &.disabled {
    opacity: 0.6;
  }
}

.submit-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}
</style>
