<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 } from '../../config/user.js'

export default {
  data() {
    return {
      depositAmount: '0.00',
      orderNo: '',
      records: [],
	  orderId:''
    }
  },
  onLoad() {
    // this.loadUserInfo()
  },
  onShow() {
    this.loadUserInfo()
  },
  methods: {
    async loadUserInfo() {
      try {
        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||''
          
          // 如果存在余额，获取押金记录
          if (parseFloat(this.depositAmount) > 0 && this.orderNo) {
            this.records = [
              { 
                type: '支付', 
                time: this.formatDate(new Date()), 
                amount: this.depositAmount 
              }
            ]
          } else {
            this.records = []
          }
        }
      } catch (error) {
        console.error('获取用户信息失败：', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },
    async handleWithdraw() {
      if (parseFloat(this.depositAmount) <= 0) {
        uni.showToast({
          title: '无可提现余额',
          icon: 'none'
        })
        return
      }
	  if(this.orderId.length!=0||this.orderNo.length!=0){
		  const res  = await queryById(Number(this.orderId))
		  console.log(res);
	  }
	 
	  // if(this.orderNo.length!=0){
		 //  uni.showToast({
		 //  	title:'当前存在进行中的订单',
			// icon:'none'
		 //  })
		 //  return
	  // }
      
      uni.showModal({
        title: '确认提现',
        content: '押金将原路退回，预计0-7个工作日到账',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '提现中...'
            })
            
            try {
              console.log('发起提现请求，订单号：', this.orderNo)
              const result = await withdrawDeposit(this.orderNo)
              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()
              
              // 更详细的错误处理
              let errorMessage = '提现失败，请稍后再试';
              
              // 如果有具体错误信息，使用它
              if (error.message) {
                // 常见错误消息处理
                if (error.message.includes('尚未归还')) {
                  errorMessage = '当前订单尚未归还，请归还后再提现';
                } else if (error.message.includes('已退还')) {
                  errorMessage = '押金已退还，无需重复提现';
                } else if (error.message.includes('处理中')) {
                  errorMessage = '押金退还处理中，请耐心等待';
                } else if (error.message.includes('余额为0')) {
                  errorMessage = '账户余额为0，无法提现';
                } else {
                  // 使用后端返回的具体错误消息
                  errorMessage = error.message;
                }
              }
              
              // 显示错误提示
              uni.showModal({
                title: '提现失败',
                content: errorMessage,
                showCancel: false
              })
            }
          }
        }
      })
    },
    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> 