<template>
  <view class="container">
    <!-- 阶段一：选购中 (门已开) -->
    <view v-if="doorStatus === 'opened'" class="shopping-section">
      <view class="status-icon">🚪</view>
      <view class="status-title">门已开，请选购商品</view>
      <view class="status-tip">请在60秒内完成选购并关门</view>
      <view class="countdown" v-if="countdown > 0">{{ countdown }}秒</view>
      <view class="countdown warning" v-else>请尽快关门</view>
      <view class="problem-link" @click="showProblem">遇到问题？（如门没开）</view>
    </view>
    
    <!-- 阶段二：结算中 (门已关) -->
    <view v-else-if="doorStatus === 'closing'" class="shopping-section">
      <view class="loading-icon">⏳</view>
      <view class="status-title">AI正在识别商品，请稍候...</view>
      <view class="status-tip">预计需要5-15秒</view>
    </view>
    
    <!-- 阶段三：结算完成 -->
    <view v-else-if="doorStatus === 'closed'" class="shopping-section">
      <view class="success-icon">✅</view>
      <view class="status-title">结算完成</view>
      <view class="status-tip">您已成功购买以下商品</view>
      <view class="purchase-info">
        <view class="product-item" v-for="product in purchasedProducts" :key="product.id">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-quantity">×{{ product.quantity }}</view>
          <view class="product-price">¥{{ product.price }}</view>
        </view>
        <view class="total-info">
          <view class="total-label">总计</view>
          <view class="total-price">¥{{ totalPrice }}</view>
        </view>
      </view>
      <button class="view-order-button" @click="goToOrderDetail">查看订单详情</button>
    </view>
    
    <!-- 错误状态 -->
    <view v-else-if="doorStatus === 'error'" class="shopping-section">
      <view class="error-icon">❌</view>
      <view class="status-title">出错了</view>
      <view class="status-tip">{{ errorMessage }}</view>
      <button class="retry-button" @click="goHome">返回首页</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { pollDeviceStatus, pollRecognizeResult, pollOrderInfo } from '../../api/status';
import type { RecognizeResultResponse } from '../../api/status';

const doorStatus = ref<'opened' | 'closing' | 'closed' | 'error'>('opened');
const countdown = ref(60);
const purchasedProducts = ref<any[]>([]);
const totalPrice = ref(0);
const errorMessage = ref('');
const currentDeviceId = ref('');
const currentActivityId = ref('');
const currentOrderNo = ref('');

let countdownTimer: number | null = null;
let statusCheckTimer: number | null = null;

onMounted(() => {
  // 获取存储的设备信息
  currentDeviceId.value = uni.getStorageSync('currentDeviceId') || '';
  currentOrderNo.value = uni.getStorageSync('currentOrderNo') || '';
  
  if (!currentDeviceId.value) {
    doorStatus.value = 'error';
    errorMessage.value = '未找到设备信息';
    return;
  }
  
  // 开始倒计时
  startCountdown();
  
  // 开始轮询设备状态
  startStatusPolling();
});

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  if (statusCheckTimer) {
    clearTimeout(statusCheckTimer);
  }
});

const startCountdown = () => {
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    }
  }, 1000);
};

const startStatusPolling = () => {
  // 轮询设备状态，等待关门
  pollDeviceStatus(currentDeviceId.value, 120000, 2000)
    .then((status) => {
      console.log('设备状态更新:', status);
      
      // 检查门是否关闭
            if (status.doorStatus === 'close') {
                // 门已关，进入识别阶段
                doorStatus.value = 'closing';
                currentActivityId.value = status.activityId;
                
                // 开始轮询识别结果
                return pollRecognizeResult(status.activityId, 60000, 1000);
            } else {
                // 继续等待关门
                return new Promise<RecognizeResultResponse>((_, reject) => {
                    startStatusPolling();
                    setTimeout(() => reject(new Error('继续轮询')), 1000);
                });
            }
    })
    .then((recognizeResult) => {
      if (recognizeResult) {
        console.log('识别结果:', recognizeResult);
        
        // 开始轮询订单信息
        return pollOrderInfo(currentActivityId.value, 30000, 1000);
      }
    })
    .then((orderInfo) => {
      if (orderInfo) {
        console.log('订单信息:', orderInfo);
        
        // 解析商品列表
        if (orderInfo.products) {
          try {
            purchasedProducts.value = JSON.parse(orderInfo.products);
          } catch (e) {
            console.error('解析商品列表失败:', e);
            purchasedProducts.value = [];
          }
        }
        
        // 设置总价
        totalPrice.value = parseFloat(orderInfo.totalAmount) || 0;
        
        // 进入结算完成阶段
        doorStatus.value = 'closed';
        
        // 停止倒计时
        if (countdownTimer) {
          clearInterval(countdownTimer);
        }
      }
    })
    .catch((error) => {
      console.error('状态轮询失败:', error);
      
      // 如果还在开门状态，继续轮询
      if (doorStatus.value === 'opened') {
        statusCheckTimer = setTimeout(() => {
          startStatusPolling();
        }, 3000);
      } else {
        doorStatus.value = 'error';
        errorMessage.value = error.message || '获取状态失败';
      }
    });
};

const showProblem = () => {
  uni.showActionSheet({
    itemList: ['辅助远程开门', '报修'],
    success: function (res) {
      if (res.tapIndex === 0) {
        uni.showToast({
          title: '正在远程开门...',
          icon: 'loading'
        });
      } else if (res.tapIndex === 1) {
        uni.showToast({
          title: '已提交报修申请',
          icon: 'success'
        });
      }
    }
  });
};

const goToOrderDetail = () => {
  // 跳转到订单详情页
  uni.navigateTo({
    url: `/pages/orderDetail/orderDetail?orderNo=${currentOrderNo.value}`
  });
};

const goHome = () => {
  uni.reLaunch({
    url: '/pages/index/index'
  });
};
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50rpx;
}

.shopping-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 100%;
}

.status-icon, .loading-icon, .success-icon, .error-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
}

.status-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.status-tip {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 40rpx;
}

.countdown {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 40rpx;
}

.countdown.warning {
  color: #FF6B6B;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.problem-link {
  font-size: 24rpx;
  color: #FFD700;
  text-decoration: underline;
  margin-top: 20rpx;
}

.purchase-info {
  width: 100%;
  background-color: #f9f9f9;
  border-radius: 15rpx;
  padding: 30rpx;
  margin: 40rpx 0;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;
}

.product-item:last-child {
  border-bottom: none;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.product-quantity {
  font-size: 28rpx;
  color: #666;
  margin: 0 20rpx;
}

.product-price {
  font-size: 28rpx;
  color: #333;
}

.total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  margin-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.total-label {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.total-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #FF6B6B;
}

.view-order-button, .retry-button {
  background-color: #FFD700;
  color: #333;
  border: none;
  padding: 20rpx 60rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  font-weight: bold;
  margin-top: 40rpx;
}
</style>