<template>
  <view class="withdraw-page">
    <!-- 可提现余额 -->
    <view class="balance-card">
      <view class="card-content">
        <view class="label">可提现余额（元）</view>
        <view class="amount">{{ balance }}</view>
      </view>
    </view>
    
    <!-- 提现表单 -->
    <view class="form-container">
      <!-- 提现金额 -->
      <view class="form-item">
        <view class="form-label">提现金额</view>
        <view class="input-wrapper">
          <text class="currency">¥</text>
          <input 
            v-model="amount"
            type="digit"
            placeholder="请输入提现金额"
            class="form-input"
            @input="onAmountInput"
          />
          <text class="all-btn" @click="withdrawAll">全部</text>
        </view>
        <view class="tips">最低提现金额100元</view>
      </view>
      
      <!-- 收款方式 -->
      <view class="form-item" @click="selectPayMethod">
        <view class="form-label">收款方式</view>
        <view class="picker-value">
          <text v-if="payMethod" class="text">{{ payMethodText }}</text>
          <text v-else class="placeholder">请选择收款方式</text>
          <text class="arrow">›</text>
        </view>
      </view>
      
      <!-- 收款账号 -->
      <view class="form-item" v-if="payMethod">
        <view class="form-label">收款账号</view>
        <view class="account-info">{{ accountInfo }}</view>
      </view>
      
      <!-- 手续费说明 -->
      <view class="fee-info">
        <text>到账金额：¥{{ arrivalAmount }}</text>
        <text class="fee">（手续费：¥{{ feeAmount }}）</text>
      </view>
    </view>
    
    <!-- 提现记录入口 -->
    <view class="record-link" @click="goToRecordList">
      <text>查看提现记录</text>
      <text class="arrow">›</text>
    </view>
    
    <!-- 提交按钮 -->
    <view class="btn-container">
      <button 
        class="submit-btn"
        :disabled="!canSubmit"
        :loading="submitting"
        @click="handleSubmit"
      >
        立即提现
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      balance: '0.00',
      amount: '',
      payMethod: '', // alipay: 支付宝 bank: 银行卡
      accountInfo: '',
      feeRate: 0.01, // 手续费率
      submitting: false
    }
  },
  
  computed: {
    payMethodText() {
      return this.payMethod === 'alipay' ? '支付宝' : this.payMethod === 'bank' ? '银行卡' : '';
    },
    
    feeAmount() {
      const fee = (parseFloat(this.amount) || 0) * this.feeRate;
      return fee.toFixed(2);
    },
    
    arrivalAmount() {
      const amount = parseFloat(this.amount) || 0;
      const fee = parseFloat(this.feeAmount);
      return (amount - fee).toFixed(2);
    },
    
    canSubmit() {
      return this.amount && 
             parseFloat(this.amount) >= 100 && 
             parseFloat(this.amount) <= parseFloat(this.balance) &&
             this.payMethod;
    }
  },
  
  onLoad() {
    this.loadBalance();
  },
  
  methods: {
    // 加载余额
    async loadBalance() {
      try {
        const res = await this.$http.post('/api/user/info');
        if (res.code === 0) {
          this.balance = res.data.balance || '0.00';
        }
      } catch (error) {
        console.error('加载余额失败:', error);
      }
    },
    
    // 金额输入
    onAmountInput(e) {
      let value = e.detail.value;
      // 只允许输入数字和小数点
      value = value.replace(/[^\d.]/g, '');
      // 只保留两位小数
      if (value.includes('.')) {
        const parts = value.split('.');
        value = parts[0] + '.' + parts[1].slice(0, 2);
      }
      this.amount = value;
    },
    
    // 全部提现
    withdrawAll() {
      this.amount = this.balance;
    },
    
    // 选择收款方式
    selectPayMethod() {
      uni.showActionSheet({
        itemList: ['支付宝', '银行卡'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.selectAlipay();
          } else {
            this.selectBank();
          }
        }
      });
    },
    
    // 选择支付宝
    async selectAlipay() {
      try {
        const res = await this.$http.get('/api/alipay/index');
        if (res.code === 0 && res.data.account) {
          this.payMethod = 'alipay';
          this.accountInfo = res.data.account;
        } else {
          uni.showModal({
            title: '提示',
            content: '您还未绑定支付宝账号，是否前往绑定？',
            success: (modalRes) => {
              if (modalRes.confirm) {
                uni.navigateTo({
                  url: '/pages/sub-pages/my-payee/zfb-detail'
                });
              }
            }
          });
        }
      } catch (error) {
        uni.showToast({
          title: error.msg || '获取失败',
          icon: 'none'
        });
      }
    },
    
    // 选择银行卡
    async selectBank() {
      try {
        const res = await this.$http.get('/api/bank/index');
        if (res.code === 0 && res.data.card_no) {
          this.payMethod = 'bank';
          this.accountInfo = `${res.data.bank_name} (${res.data.card_no.slice(-4)})`;
        } else {
          uni.showModal({
            title: '提示',
            content: '您还未绑定银行卡，是否前往绑定？',
            success: (modalRes) => {
              if (modalRes.confirm) {
                uni.navigateTo({
                  url: '/pages/sub-pages/my-payee/yl-detail'
                });
              }
            }
          });
        }
      } catch (error) {
        uni.showToast({
          title: error.msg || '获取失败',
          icon: 'none'
        });
      }
    },
    
    // 去提现记录
    goToRecordList() {
      uni.navigateTo({
        url: '/pages/sub-pages/withdraw/list'
      });
    },
    
    // 提交提现
    async handleSubmit() {
      const amount = parseFloat(this.amount);
      
      if (amount < 100) {
        uni.showToast({
          title: '最低提现金额100元',
          icon: 'none'
        });
        return;
      }
      
      if (amount > parseFloat(this.balance)) {
        uni.showToast({
          title: '余额不足',
          icon: 'none'
        });
        return;
      }
      
      this.submitting = true;
      
      try {
        const res = await this.$http.post('/api/money/withdraw', {
          amount: this.amount,
          type: this.payMethod === 'alipay' ? 1 : 2
        });
        
        if (res.code === 0) {
          uni.showToast({
            title: '提现申请已提交',
            icon: 'success'
          });
          
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        uni.showToast({
          title: error.msg || '提现失败',
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.withdraw-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.balance-card {
  background: linear-gradient(135deg, #667eea, #764ba2);
  margin: 30rpx;
  border-radius: 20rpx;
  padding: 50rpx 40rpx;
  color: #fff;
  
  .label {
    font-size: 26rpx;
    opacity: 0.9;
    margin-bottom: 20rpx;
  }
  
  .amount {
    font-size: 72rpx;
    font-weight: bold;
  }
}

.form-container {
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
}

.form-item {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: 500;
  }
  
  .input-wrapper {
    display: flex;
    align-items: center;
    height: 90rpx;
    padding: 0 20rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    
    .currency {
      font-size: 32rpx;
      color: #333;
      margin-right: 10rpx;
    }
    
    .form-input {
      flex: 1;
      height: 100%;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .all-btn {
      padding: 10rpx 20rpx;
      background-color: #FF4757;
      color: #fff;
      font-size: 24rpx;
      border-radius: 20rpx;
    }
  }
  
  .tips {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }
  
  .picker-value {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 90rpx;
    padding: 0 20rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    
    .text {
      font-size: 28rpx;
      color: #333;
    }
    
    .placeholder {
      font-size: 28rpx;
      color: #999;
    }
    
    .arrow {
      font-size: 40rpx;
      color: #ccc;
    }
  }
  
  .account-info {
    padding: 20rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    font-size: 26rpx;
    color: #666;
  }
}

.fee-info {
  padding: 20rpx;
  background-color: #fff3cd;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #856404;
  
  .fee {
    color: #999;
    margin-left: 10rpx;
  }
}

.record-link {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  font-size: 28rpx;
  color: #333;
  
  .arrow {
    font-size: 40rpx;
    color: #ccc;
  }
}

.btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(90deg, #FF6B6B, #FF4757);
  color: #fff;
  border-radius: 45rpx;
  font-size: 32rpx;
  border: none;
  
  &[disabled] {
    opacity: 0.6;
  }
}
</style>

