<template>
  <view class="deposit-container">
    <!-- 押金金额卡片 -->
    <view class="deposit-card">
      <view class="title">{{ $t('deposit.depositBalance') }}</view>
      <view class="amount">¥{{ depositAmount }}</view>
      <button class="withdraw-btn" @click="handleWithdraw" :disabled="depositAmount <= 0">{{ $t('deposit.withdraw') }}</button>
    </view>

    <!-- 提现说明 -->
    <view class="notice-card">
      <view class="notice-title">
        <view class="dot"></view>
        <text>{{ $t('deposit.withdrawNotice') }}</text>
      </view>
      <view class="notice-content">
        <view class="notice-item">1. {{ $t('deposit.withdrawNotice1') }}</view>
        <view class="notice-item">2. {{ $t('deposit.withdrawNotice2') }}</view>
        <view class="notice-item">3. {{ $t('deposit.withdrawNotice3') }}</view>
      </view>
    </view>

    <!-- 押金记录 -->
    <view class="record-card" v-if="records.length > 0">
      <view class="record-title">{{ $t('deposit.depositRecord') }}</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.typeText }}</text>
            <text class="record-time">{{ item.time }}</text>
          </view>
          <text class="record-amount" :class="item.type === 'refund' ? 'refund' : ''">
            {{ item.type === 'refund' ? '+' : '-' }}¥{{ item.amount }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getUserInfo } from '../../util/index.js'
import { withdrawDeposit } from '../../config/api/user.js'
import { queryById } from '../../config/api/order.js'
import { useI18n } from '@/utils/i18n.js'

const { t } = useI18n()

const depositAmount = ref('0.00')
const orderNo = ref('')
const orderId = ref('')
const records = ref([])

onMounted(() => {
  uni.setNavigationBarTitle({
    title: t('deposit.title')
  })
})

onShow(() => {
  loadUserInfo()
})

const loadUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200) {
      depositAmount.value = res.data.balanceAmount || '0.00'
      orderNo.value = res.data.latestOrderNo || ''
      orderId.value = res.data.latestOrderId || ''
      
      // 如果存在余额，获取押金记录
      if (parseFloat(depositAmount.value) > 0 && orderNo.value) {
        records.value = [
          { 
            type: 'pay',
            typeText: t('deposit.payRecord'),
            time: formatDate(new Date()), 
            amount: depositAmount.value 
          }
        ]
      } else {
        records.value = []
      }
    }
  } catch (error) {
    uni.showToast({
      title: t('user.getUserInfoFailed'),
      icon: 'none'
    })
  }
}

const handleWithdraw = async () => {
  if (parseFloat(depositAmount.value) <= 0) {
    uni.showToast({
      title: t('deposit.noBalance'),
      icon: 'none'
    })
    return
  }
  
  uni.showModal({
    title: t('deposit.confirmWithdraw'),
    content: t('deposit.withdrawDesc'),
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: t('deposit.withdrawing')
        })
        
        try {
          const result = await withdrawDeposit(orderNo.value)
          
          if (result.code === 200) {
            uni.hideLoading()
            uni.showToast({
              title: t('deposit.withdrawSubmitted'),
              icon: 'success'
            })
            
            // 更新记录
            records.value.push({
              type: 'refund',
              typeText: t('deposit.refundRecord'),
              time: formatDate(new Date()),
              amount: depositAmount.value
            })
            // 更新余额为0
            depositAmount.value = '0.00'
            
            // 重新加载用户信息
            setTimeout(() => {
              loadUserInfo()
            }, 1500)
          } else {
            throw new Error(result.msg || t('deposit.withdrawFailed'))
          }
        } catch (error) {
          uni.hideLoading()
          
          // 更详细的错误处理
          let errorMessage = t('deposit.withdrawFailed');
          
          if (error.message) {
            if (error.message.includes('尚未归还')) {
              errorMessage = t('deposit.orderNotReturned');
            } else if (error.message.includes('已退还')) {
              errorMessage = t('deposit.alreadyRefunded');
            } else if (error.message.includes('处理中')) {
              errorMessage = t('deposit.refundProcessing');
            } else if (error.message.includes('余额为0')) {
              errorMessage = t('deposit.noBalance');
            } else {
              errorMessage = error.message;
            }
          }
          
          uni.showModal({
            title: t('deposit.withdrawFailed'),
            content: errorMessage,
            showCancel: false
          })
        }
      }
    }
  })
}

const 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>