<template>
  <view class="deposit-container">
    <!-- 押金金额卡片 -->
    <view class="deposit-card">
      <view class="title">押金余额</view>
      <view class="amount">¥{{ depositAmount }}</view>
      <button class="withdraw-btn" @click="handleWithdraw" :disabled="depositAmount <= 0">提现</button>
    </view>

    <!-- 提现说明 -->
    <view class="notice-card">
      <view class="notice-title">
        <view class="dot"></view>
        <text>提现说明</text>
      </view>
      <view class="notice-content">
        <view class="notice-item">1. 提现金额将原路退回支付账户</view>
        <view class="notice-item">2. 提现申请提交后预计0-7个工作日到账</view>
        <view class="notice-item">3. 如超时未收到，请联系客服处理</view>
      </view>
    </view>

    <!-- 押金记录 -->
    <view class="record-card" v-if="records.length > 0">
      <view class="record-title">押金记录</view>
      <view class="record-list">
        <view class="record-item" v-for="(item, index) in records" :key="index">
          <view class="record-info">
            <text class="record-type">{{ item.type }}</text>
            <text class="record-time">{{ item.time }}</text>
          </view>
          <text class="record-amount" :class="item.type === '退还' ? 'refund' : ''">
            {{ item.type === '退还' ? '+' : '-' }}¥{{ item.amount }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserInfo } from '../../util/index.js'
import { withdrawDeposit, queryById, getOrderList } from '../../config/user.js'

export default {
  data() {
    return {
      depositAmount: '0.00',
      orderNo: '',
      records: [],
      orderId: '',
      isLoading: false
    }
  },
  onLoad() {
    // this.loadUserInfo()
  },
  onShow() {
    this.loadUserInfo()
  },
  methods: {
    async loadUserInfo() {
      try {
        this.isLoading = true
        const res = await getUserInfo()
        console.log('loadUserInfo', res);
        if (res.code === 200) {
          this.depositAmount = res.data.balanceAmount || '0.00'
          this.orderNo = res.data.latestOrderNo || ''
          this.orderId = res.data.latestOrderId || ''
          
          // 如果有余额但没有orderId，尝试查询用户订单列表获取
          if (parseFloat(this.depositAmount) > 0 && !this.orderId) {
            console.log('没有latestOrderId但有余额，尝试查询订单列表')
            const orderRes = await getOrderList({ pageNum: 1, pageSize: 10 })
            if (orderRes.code === 200 && orderRes.data && orderRes.data.records && orderRes.data.records.length > 0) {
              // 查找最近的包含押金的订单
              const depositOrder = orderRes.data.records.find(order => 
                order.depositAmount && parseFloat(order.depositAmount) > 0
              )
              
              if (depositOrder) {
                console.log('找到押金订单:', depositOrder)
                this.orderId = depositOrder.orderId
                this.orderNo = depositOrder.orderNo
              }
            }
          }
          
          // 如果存在余额，获取押金记录
          if (parseFloat(this.depositAmount) > 0) {
            this.records = [
              { 
                type: '支付', 
                time: this.formatDate(new Date()), 
                amount: this.depositAmount 
              }
            ]
          } else {
            this.records = []
          }
        }
      } catch (error) {
        console.error('获取用户信息失败：', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    async handleWithdraw() {
      if (parseFloat(this.depositAmount) <= 0) {
        uni.showToast({
          title: '无可提现余额',
          icon: 'none'
        })
        return
      }
      
      if (!this.orderId) {
        uni.showToast({
          title: '无法找到押金订单',
          icon: 'none'
        })
        return
      }
      
      uni.showModal({
        title: '确认提现',
        content: '押金将原路退回，预计0-7个工作日到账',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '提现中...'
            })
            
            try {
              console.log('发起提现请求，订单ID：', this.orderId)
              const result = await withdrawDeposit(this.orderId)
              console.log('提现响应：', result)
              
              if (result.code === 200) {
                uni.hideLoading()
                uni.showToast({
                  title: '提现申请已提交',
                  icon: 'success'
                })
                
                // 更新余额为0
                this.depositAmount = '0.00'
                this.records.push({
                  type: '退还',
                  time: this.formatDate(new Date()),
                  amount: this.depositAmount
                })
                
                // 重新加载用户信息
                setTimeout(() => {
                  this.loadUserInfo()
                }, 1500)
              } else {
                throw new Error(result.msg || '提现失败')
              }
            } catch (error) {
              console.error('提现失败：', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '提现失败，请稍后再试',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style lang="scss" scoped>
.deposit-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 30rpx;

  .deposit-card {
    background: linear-gradient(135deg, #1976D2, #64B5F6);
    border-radius: 20rpx;
    padding: 40rpx;
    color: #fff;
    text-align: center;
    box-shadow: 0 4rpx 20rpx rgba(25,118,210,0.2);

    .title {
      font-size: 28rpx;
      opacity: 0.9;
      margin-bottom: 20rpx;
    }

    .amount {
      font-size: 72rpx;
      font-weight: bold;
      margin-bottom: 40rpx;
    }

    .withdraw-btn {
      background: #fff;
      color: #1976D2;
      width: 80%;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 40rpx;
      font-size: 32rpx;
      font-weight: 500;
      margin: 0 auto;

      &:active {
        transform: scale(0.98);
      }
      
      &[disabled] {
        background: rgba(255,255,255,0.6);
        color: rgba(25,118,210,0.5);
      }
    }
  }

  .notice-card {
    margin-top: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);

    .notice-title {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .dot {
        width: 12rpx;
        height: 12rpx;
        background: #1976D2;
        border-radius: 50%;
        margin-right: 10rpx;
      }

      text {
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
      }
    }

    .notice-content {
      .notice-item {
        font-size: 26rpx;
        color: #666;
        line-height: 1.8;
        padding-left: 22rpx;
      }
    }
  }

  .record-card {
    margin-top: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);

    .record-title {
      font-size: 30rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 20rpx;
      border-left: 8rpx solid #1976D2;
      padding-left: 20rpx;
    }

    .record-list {
      .record-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .record-info {
          .record-type {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 6rpx;
            display: block;
          }

          .record-time {
            font-size: 24rpx;
            color: #999;
          }
        }

        .record-amount {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;

          &.refund {
            color: #4CAF50;
          }
        }
      }
    }
  }
}
</style> 