<template>
  <view class="success-container">
    <!-- 支付成功状态 -->
    <view class="status-card">
      <view class="status-icon success"></view>
      <view class="status-text">归还成功</view>
      <view class="status-desc">您的风扇已归还，费用已从押金中扣除</view>
    </view>
    
    <!-- 订单信息 -->
    <view class="order-card">
      <view class="card-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单号</text>
        <text class="value">{{ orderInfo.orderNo || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">设备号</text>
        <text class="value">{{ orderInfo.deviceNo || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">使用时长</text>
        <text class="value">{{ orderInfo.usedTime || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">套餐时长</text>
        <text class="value">{{ orderInfo.packageTime || '1小时' }}</text>
      </view>
      <view class="info-item">
        <text class="label">超出时长</text>
        <text class="value">{{ orderInfo.extraTime || '0分钟' }}</text>
      </view>
      <view class="info-item">
        <text class="label">归还时间</text>
        <text class="value">{{ orderInfo.endTime || '-' }}</text>
      </view>
    </view>

    <!-- 费用信息 -->
    <view class="refund-card">
      <view class="card-title">费用信息</view>
      <view class="info-item">
        <text class="label">套餐费用</text>
        <text class="value">￥{{ orderInfo.packagePrice || '0.00' }}</text>
      </view>
      <view class="info-item">
        <text class="label">超时费用</text>
        <text class="value">￥{{ orderInfo.extraFee || '0.00' }}</text>
      </view>
      <view class="info-item">
        <text class="label">总费用</text>
        <text class="value">￥{{ orderInfo.currentFee || '0.00' }}</text>
      </view>
      <view class="info-item">
        <text class="label">押金</text>
        <text class="value">￥{{ orderInfo.deposit || '99.00' }}</text>
      </view>
      <view class="info-item">
        <text class="label">退还金额</text>
        <text class="value highlight">￥{{ orderInfo.refundAmount || '99.00' }}</text>
      </view>
      <view class="info-item">
        <text class="label">退还状态</text>
        <text class="value" :class="orderInfo.withdrawStatus || 'waiting'">{{ getWithdrawStatusText() }}</text>
      </view>
    </view>

    <!-- 退款说明卡片 -->
    <view class="notice-card">
      <view class="card-title">退款说明</view>
      <view class="notice-content">
        <text>1. 押金剩余金额需要您手动申请提现</text>
        <text>2. 提现申请提交后将在1-3个工作日内退还到原支付账户</text>
        <text>3. 如有疑问，请联系客服</text>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="button-group">
      <button class="primary-btn" @click="handleWithdraw" v-if="!orderInfo.isWithdrawn && orderInfo.refundAmount > 0">申请退款</button>
      <button class="primary-btn" @click="goToHome">返回首页</button>
    </view>
  </view>
</template>

<script>
import { queryById } from '@/config/user.js'
import {
		URL
	}from"@/config/url.js"

export default {
  data() {
    return {
      orderId: '',
      orderInfo: {
        orderNo: '',
        deviceNo: '',
        usedTime: '',
        currentFee: '0.00',
        deposit: '99.00',
        refundAmount: '99.00',
        endTime: '',
        withdrawStatus: 'waiting',
        isWithdrawn: false
      }
    }
  },
  onLoad(options) {
    if (options && options.orderId) {
      this.orderId = options.orderId;
      this.loadOrderInfo();
    } else {
      uni.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      });
      setTimeout(() => {
        this.goToHome();
      }, 1500);
    }
  },
  methods: {
    // 获取退款状态文本
    getWithdrawStatusText() {
      const statusMap = {
        'waiting': '待申请',
        'processing': '处理中',
        'success': '已退款',
        'failed': '退款失败'
      };
      return statusMap[this.orderInfo.withdrawStatus] || '待申请';
    },
    
    // 加载订单信息
    async loadOrderInfo() {
      try {
        uni.showLoading({ title: '加载中' });
        
        const result = await queryById(this.orderId);
        if (result.code === 200 && result.data) {
          const orderData = result.data;
          
          // 从remark字段中解析使用信息
          let packageMinutes = 60;
          let extraMinutes = 0;
          let usedMinutes = 0;
          let packagePrice = '0.00';
          let extraFee = '0.00';
          
          if (orderData.remark) {
            try {
              // 解析remark字段
              const remarkInfo = orderData.remark;
              
              // 尝试提取使用时长
              const usedTimeMatch = remarkInfo.match(/使用时长:(\d+)分钟/);
              if (usedTimeMatch && usedTimeMatch[1]) {
                usedMinutes = parseInt(usedTimeMatch[1]);
              }
              
              // 尝试提取套餐时长
              const packageTimeMatch = remarkInfo.match(/套餐时长:(\d+)分钟/);
              if (packageTimeMatch && packageTimeMatch[1]) {
                packageMinutes = parseInt(packageTimeMatch[1]);
              }
              
              // 尝试提取超出时长
              const extraTimeMatch = remarkInfo.match(/超出时长:(\d+)分钟/);
              if (extraTimeMatch && extraTimeMatch[1]) {
                extraMinutes = parseInt(extraTimeMatch[1]);
              }
              
              // 尝试提取套餐费用
              const packagePriceMatch = remarkInfo.match(/套餐费用:([\d.]+)元/);
              if (packagePriceMatch && packagePriceMatch[1]) {
                packagePrice = packagePriceMatch[1];
              }
              
              // 尝试提取超时费用
              const extraFeeMatch = remarkInfo.match(/超时费用:([\d.]+)元/);
              if (extraFeeMatch && extraFeeMatch[1]) {
                extraFee = extraFeeMatch[1];
              }
              
              console.log('从remark解析到的信息:', {
                usedMinutes,
                packageMinutes,
                extraMinutes,
                packagePrice,
                extraFee
              });
            } catch (e) {
              console.error('解析remark字段失败:', e);
            }
          }
          
          this.orderInfo = {
            orderNo: orderData.orderNo || '',
            deviceNo: orderData.deviceNo || '',
            usedTime: usedMinutes + '分钟',
            packageTime: packageMinutes + '分钟',
            extraTime: extraMinutes + '分钟',
            packagePrice: packagePrice,
            extraFee: extraFee,
            currentFee: orderData.actualDeviceAmount || '0.00',
            deposit: orderData.depositAmount || '99.00',
            refundAmount: orderData.residueAmount || '99.00',
            endTime: orderData.endTime || '',
            withdrawStatus: orderData.withdrawStatus || 'waiting',
            isWithdrawn: orderData.withdrawStatus === 'success'
          };
        } else {
          throw new Error(result.msg || '获取订单信息失败');
        }
      } catch (error) {
        console.error('加载订单信息错误:', error);
        uni.showToast({
          title: error.message || '获取订单信息失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 申请退款
    async handleWithdraw() {
      try {
        uni.showLoading({ title: '处理中' });
        
        const res = await uni.request({
          url: `${URL || 'http://127.0.0.1:8080'}/app/withdraw/add/${this.orderInfo.orderNo}`,
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + uni.getStorageSync('token'),
            'Clientid': uni.getStorageSync('client_id')
          }
        })
        
        if (res.statusCode === 200 && res.data.code === 200) {
          uni.showToast({
            title: '退款申请成功',
            icon: 'success'
          });
          
          // 更新状态
          this.orderInfo.withdrawStatus = 'processing';
          this.orderInfo.isWithdrawn = true;
          
          // 刷新订单信息
          setTimeout(() => {
            this.loadOrderInfo();
          }, 1500);
        } else {
          throw new Error(res.data.msg || '退款申请失败');
        }
      } catch (error) {
        console.error('退款申请错误:', error);
        uni.showToast({
          title: error.message || '退款申请失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 返回首页
    goToHome() {
      uni.reLaunch({
        url: '/pages/index/index'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.success-container {
  padding: 20px;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.status-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  
  .status-icon {
    width: 60px;
    height: 60px;
    margin: 0 auto 16px;
    
    &.success {
      background-color: #07c160;
      border-radius: 50%;
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        top: 50%;
        width: 30px;
        height: 20px;
        border: 3px solid #fff;
        border-top: none;
        border-right: none;
        transform-origin: center;
        transform: translate(-50%, -70%) rotate(-45deg);
      }
    }
  }
  
  .status-text {
    font-size: 24px;
    font-weight: bold;
    color: #07c160;
    margin-bottom: 8px;
  }
  
  .status-desc {
    font-size: 14px;
    color: #666;
  }
}

.order-card, .refund-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  
  .card-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 10px;
  }
  
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      color: #666;
      font-size: 14px;
    }
    
    .value {
      color: #333;
      font-size: 14px;
      
      &.highlight {
        color: #ff6b00;
        font-weight: bold;
        font-size: 16px;
      }
      
      &.success {
        color: #07c160;
      }
    }
  }
}

.button-group {
  margin-top: 40rpx;
  display: flex;
  justify-content: center;
  gap: 20rpx;
  
  .primary-btn, .secondary-btn {
    width: 50%;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    text-align: center;
    font-size: 32rpx;
  }
  
  .primary-btn {
    background: #07c160;
    color: #fff;
    
    &:active {
      opacity: 0.8;
    }
  }
  
  .secondary-btn {
    background: #f0f0f0;
    color: #333;
    
    &:active {
      opacity: 0.8;
    }
  }
}

.notice-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  
  .card-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 10px;
  }
  
  .notice-content {
    text-align: left;
    color: #666;
    font-size: 14px;
  }
}

.waiting {
  color: #ffaa00;
  font-weight: bold;
}
</style> 