<template>
  <view class="page">
    <!-- 导航栏 -->
    <NavBar title="设备详情" :showBack="true" />
    
    <view class="detail-card" v-if="device">
      <!-- 设备状态 -->
      <view class="status-section">
        <view class="status-header">
          <text class="device-name">{{ device.name }}</text>
          <view class="device-status" :class="getStatusClass(device.status)">
            <view class="status-dot"></view>
            <text>{{ getStatusText(device.status) }}</text>
          </view>
        </view>
        <text class="device-no">{{ device.deviceId }}</text>
      </view>
      
      <!-- 基本信息 -->
      <view class="info-section">
        <text class="section-title">基本信息</text>
        <view class="info-item">
          <text class="label">所属门店</text>
          <text class="value">{{ device.shopName }}</text>
        </view>
        <view class="info-item">
          <text class="label">门店地址</text>
          <text class="value">{{ device.shopAddress }}</text>
        </view>
      </view>
      
      <!-- 运行状态 -->
      <view class="info-section" v-if="device.status === 1">
        <text class="section-title">运行状态</text>
        <view class="status-grid">
          <view class="status-item">
            <view class="status-icon temp">
              <view class="icon-inner"></view>
            </view>
            <text class="status-value">{{ device.temperature }}°C</text>
            <text class="status-label">柜内温度</text>
          </view>
          <view class="status-item">
            <view class="status-icon volume">
              <view class="icon-inner"></view>
            </view>
            <text class="status-value">{{ device.volume }}%</text>
            <text class="status-label">音量</text>
          </view>
        </view>
      </view>
      
      <!-- 销售数据 -->
      <view class="info-section">
        <text class="section-title">销售数据</text>
        <view class="sales-grid">
          <view class="sales-item">
            <text class="sales-value accent">¥{{ formatMoney(device.todaySales) }}</text>
            <text class="sales-label">今日销售额</text>
          </view>
          <view class="sales-item">
            <text class="sales-value">{{ device.todayOrders }}</text>
            <text class="sales-label">今日订单</text>
          </view>
          <view class="sales-item">
            <text class="sales-value primary">¥{{ formatMoney(device.totalSales) }}</text>
            <text class="sales-label">累计销售</text>
          </view>
        </view>
      </view>
      
      <!-- 库存状态 -->
      <view class="info-section">
        <text class="section-title">库存状态</text>
        <view class="inventory-info">
          <view class="inventory-bar">
            <view 
              class="inventory-progress" 
              :style="{ width: (device.capacity > 0 ? device.inventory / device.capacity * 100 : 0) + '%' }"
            ></view>
          </view>
          <text class="inventory-text">{{ device.inventory }}/{{ device.capacity }}</text>
        </view>
        
        <!-- 库存预警 -->
        <view class="low-stock-list" v-if="device.lowStockItems && device.lowStockItems.length > 0">
          <view class="low-stock-title">
            <view class="warning-icon"></view>
            <text>库存预警</text>
          </view>
          <view class="low-stock-item" v-for="item in device.lowStockItems" :key="item.productName">
            <text class="product-name">{{ item.productName }}</text>
            <text class="stock-warning">
              库存不足: {{ item.currentStock }}/{{ item.minStock }}
            </text>
          </view>
        </view>
      </view>
      
      <!-- 开门记录 -->
      <view class="info-section" v-if="doorRecords.length > 0">
        <text class="section-title">最近开门记录</text>
        <view class="record-list">
          <view class="record-item" v-for="record in doorRecords" :key="record.id">
            <view class="record-left">
              <text class="record-action">{{ record.action || '开门' }}</text>
              <text class="record-user">{{ record.userName || '未知用户' }}</text>
            </view>
            <text class="record-time">{{ record.createTime || record.time }}</text>
          </view>
        </view>
      </view>

      <!-- 远程操作 -->
      <view class="info-section" v-if="device.status === 1">
        <text class="section-title">远程操作</text>
        <view class="operation-grid">
          <view class="operation-btn" @click="handleOpenDoor">
            <view class="op-icon green">
              <view class="icon-door"></view>
            </view>
            <text class="op-name">远程开门</text>
          </view>
          <view class="operation-btn" @click="showTempModal = true">
            <view class="op-icon amber">
              <view class="icon-temp"></view>
            </view>
            <text class="op-name">设置温度</text>
          </view>
          <view class="operation-btn" @click="showVolumeModal = true">
            <view class="op-icon blue">
              <view class="icon-vol"></view>
            </view>
            <text class="op-name">设置音量</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 温度设置弹窗 -->
    <view class="modal-overlay" v-if="showTempModal" @click="showTempModal = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">设置柜内温度</text>
        </view>
        <view class="modal-body">
          <text class="modal-label">当前温度: {{ device?.temperature }}°C</text>
          <input
            class="modal-input"
            v-model="newTemperature"
            type="number"
            placeholder="请输入温度 (0-30°C)"
            placeholder-class="input-placeholder"
          />
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="showTempModal = false">取消</button>
          <button class="btn-confirm" @click="handleSetTemperature">确认</button>
        </view>
      </view>
    </view>

    <!-- 音量设置弹窗 -->
    <view class="modal-overlay" v-if="showVolumeModal" @click="showVolumeModal = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">设置设备音量</text>
        </view>
        <view class="modal-body">
          <text class="modal-label">当前音量: {{ device?.volume }}%</text>
          <input
            class="modal-input"
            v-model="newVolume"
            type="number"
            placeholder="请输入音量 (0-100)"
            placeholder-class="input-placeholder"
          />
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="showVolumeModal = false">取消</button>
          <button class="btn-confirm" @click="handleSetVolume">确认</button>
        </view>
      </view>
    </view>

    <view class="bottom-spacer"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { logger } from '@/utils/logger';
import NavBar from '@/components/NavBar.vue';
import { getDeviceDetail, openDeviceDoor, setDeviceTemperature, setDeviceVolume, getDeviceDoorRecords } from '@/api/device';
import { DeviceStatusText, DeviceStatusColor } from '@/utils/constants';
import { formatMoney as formatMoneyUtil, showToast, showConfirm, navigateBack } from '@/utils/common';

const device = ref<any>(null);
const doorRecords = ref<any[]>([]);
const showTempModal = ref(false);
const showVolumeModal = ref(false);
const newTemperature = ref('');
const newVolume = ref('');
const formatMoney = formatMoneyUtil;

const getStatusText = (status: number) => DeviceStatusText[status] || '未知';
const getStatusColor = (status: number) => DeviceStatusColor[status] || '$text-color-muted';

const getStatusClass = (status: number) => {
  if (status === 1) return 'online';
  if (status === 0) return 'offline';
  return 'maintenance';
};

const loadDetail = async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const id = (currentPage as any).options?.id;

  if (!id) {
    showToast('设备ID不存在');
    navigateBack();
    return;
  }

  try {
    device.value = await getDeviceDetail(id);
    loadDoorRecords(id);
  } catch (error) {
    showToast('加载设备详情失败');
    navigateBack();
  }
};

const loadDoorRecords = async (deviceId: string) => {
  try {
    const res = await getDeviceDoorRecords(deviceId, { page: 1, pageSize: 5 });
    doorRecords.value = res.list || [];
  } catch (error) {
    logger.warn('加载开门记录失败', error);
  }
};

const handleOpenDoor = async () => {
  const confirmed = await showConfirm('确认远程开门？请确保设备前无人遮挡。');
  if (!confirmed) return;

  try {
    await openDeviceDoor(device.value.id, 'A');
    showToast('远程开门指令已发送', 'success');
  } catch (error) {
    showToast('远程开门失败', 'error');
  }
};

const handleSetTemperature = async () => {
  const temp = parseInt(newTemperature.value);
  if (isNaN(temp) || temp < 0 || temp > 30) {
    showToast('请输入0-30之间的温度值', 'error');
    return;
  }

  try {
    await setDeviceTemperature(device.value.id, temp);
    device.value.temperature = temp;
    showTempModal.value = false;
    newTemperature.value = '';
    showToast('温度设置成功', 'success');
  } catch (error) {
    showToast('温度设置失败', 'error');
  }
};

const handleSetVolume = async () => {
  const vol = parseInt(newVolume.value);
  if (isNaN(vol) || vol < 0 || vol > 100) {
    showToast('请输入0-100之间的音量值', 'error');
    return;
  }

  try {
    await setDeviceVolume(device.value.id, vol);
    device.value.volume = vol;
    showVolumeModal.value = false;
    newVolume.value = '';
    showToast('音量设置成功', 'success');
  } catch (error) {
    showToast('音量设置失败', 'error');
  }
};

onMounted(() => {
  loadDetail();
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  padding-bottom: 120rpx;
}

.status-section {
  background: $bg-color-card;
  padding: 30rpx 32rpx;
  margin-bottom: 16rpx;
  
  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
    
    .device-name {
      font-size: 36rpx;
      font-weight: 700;
      color: $text-color-primary;
    }
    
    .device-status {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
      padding: 10rpx 20rpx;
      font-size: 24rpx;
      font-weight: 500;
      border-radius: 20rpx;
      
      .status-dot {
        width: 8rpx;
        height: 8rpx;
        border-radius: 50%;
      }
      
      &.online {
        background: $success-color-bg;
        color: $success-color;
        .status-dot { background: $success-color; }
      }

      &.offline {
        background: $bg-color-secondary;
        color: $text-color-muted;
        .status-dot { background: $text-color-placeholder; }
      }

      &.maintenance {
        background: $warning-color-bg;
        color: $warning-color;
        .status-dot { background: $warning-color; }
      }
    }
  }
  
  .device-no {
    font-size: 26rpx;
    color: $text-color-muted;
    font-family: monospace;
  }
}

.info-section {
  background: $bg-color-card;
  margin-bottom: 16rpx;
  padding: 24rpx 32rpx;
  
  .section-title {
    display: block;
    font-size: 28rpx;
    font-weight: 600;
    color: $text-color-primary;
    margin-bottom: 20rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid $bg-color-secondary;
  }
  
  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 14rpx 0;
    
    .label {
      font-size: 28rpx;
      color: $text-color-tertiary;
    }
    
    .value {
      font-size: 28rpx;
      color: $text-color-primary;
    }
  }
  
  .status-grid {
    display: flex;
    
    .status-item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      background: $bg-color-page;
      border-radius: 12rpx;
      margin-right: 16rpx;
      
      &:last-child {
        margin-right: 0;
      }
      
      .status-icon {
        width: 56rpx;
        height: 56rpx;
        border-radius: 16rpx;
        margin: 0 auto 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &.temp {
          background: $success-color-bg;
          
          .icon-inner {
            width: 20rpx;
            height: 20rpx;
            border: 4rpx solid $primary-color;
            border-radius: 50%;
          }
        }
        
        &.volume {
          background: $info-color-bg;
          
          .icon-inner {
            width: 0;
            height: 0;
            border-left: 10rpx solid $info-color;
            border-top: 8rpx solid transparent;
            border-bottom: 8rpx solid transparent;
          }
        }
      }
      
      .status-value {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 700;
        color: $text-color-primary;
        margin-bottom: 8rpx;
      }
      
      .status-label {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: $text-color-tertiary;
      }
    }
  }
  
  .sales-grid {
    display: flex;
    background: $bg-color-page;
    border-radius: 12rpx;
    padding: 20rpx 0;
    
    .sales-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .sales-value {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        font-weight: 700;
        color: $text-color-primary;
        margin-bottom: 8rpx;
        
        &.accent {
          color: $accent-color;
        }
        
        &.primary {
          color: $primary-color;
        }
      }
      
      .sales-label {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22rpx;
        color: $text-color-tertiary;
      }
    }
  }
  
  .inventory-info {
    display: flex;
    align-items: center;
    
    .inventory-bar {
      flex: 1;
      height: 20rpx;
      background: $border-color;
      border-radius: 10rpx;
      overflow: hidden;
      
      .inventory-progress {
        height: 100%;
        background: $primary-color;
        border-radius: 10rpx;
      }
    }
    
    .inventory-text {
      width: 120rpx;
      text-align: right;
      font-size: 26rpx;
      color: $text-color-secondary;
      font-weight: 500;
    }
  }
  
  .low-stock-list {
    margin-top: 20rpx;
    padding: 20rpx;
    background: $error-color-bg;
    border-radius: 12rpx;
    
    .low-stock-title {
      display: flex;
      align-items: center;
      gap: 8rpx;
      font-size: 26rpx;
      font-weight: 600;
      color: $error-color;
      margin-bottom: 16rpx;
      
      .warning-icon {
        width: 20rpx;
        height: 20rpx;
        border: 3rpx solid $error-color;
        border-radius: 50%;
        position: relative;
        
        &::before {
          content: '';
          position: absolute;
          top: 4rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 3rpx;
          height: 3rpx;
          background: $error-color;
          border-radius: 50%;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: 3rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 3rpx;
          height: 6rpx;
          background: $error-color;
          border-radius: 2rpx;
        }
      }
    }
    
    .low-stock-item {
      display: flex;
      justify-content: space-between;
      padding: 12rpx 0;
      
      .product-name {
        font-size: 26rpx;
        color: $text-color-primary;
      }
      
      .stock-warning {
        font-size: 24rpx;
        color: $error-color;
      }
    }
  }
  
  .order-list {
    .order-item {
      display: flex;
      align-items: center;
      padding: 16rpx 0;
      border-bottom: 1rpx solid $bg-color-secondary;
      
      &:last-child {
        border-bottom: none;
      }
      
      .order-no {
        flex: 1;
        font-size: 26rpx;
        color: $text-color-primary;
        font-family: monospace;
      }
      
      .order-amount {
        width: 120rpx;
        text-align: right;
        font-size: 26rpx;
        color: $text-color-primary;
        font-weight: 600;
      }
      
      .order-time {
        width: 160rpx;
        text-align: right;
        font-size: 24rpx;
        color: $text-color-muted;
      }
    }
  }
}

.record-list {
  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid $bg-color-secondary;

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

    .record-left {
      .record-action {
        display: block;
        font-size: 28rpx;
        color: $text-color-primary;
        margin-bottom: 4rpx;
      }

      .record-user {
        font-size: 22rpx;
        color: $text-color-muted;
      }
    }

    .record-time {
      font-size: 24rpx;
      color: $text-color-muted;
    }
  }
}

.operation-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;

  .operation-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24rpx 0;
    background: $bg-color-page;
    border-radius: 16rpx;
    transition: background 0.15s;

    &:active {
      background: $bg-color-secondary;
    }

    .op-icon {
      width: 72rpx;
      height: 72rpx;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12rpx;

      &.green { background: $success-color-bg; }
      &.amber { background: $accent-color-bg; }
      &.blue { background: $info-color-bg; }

      .icon-door {
        width: 28rpx;
        height: 32rpx;
        border: 3rpx solid $primary-color;
        border-radius: 4rpx;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          top: 50%;
          right: -6rpx;
          transform: translateY(-50%);
          width: 4rpx;
          height: 8rpx;
          background: $primary-color;
          border-radius: 2rpx;
        }
      }

      .icon-temp {
        width: 20rpx;
        height: 20rpx;
        border: 3rpx solid $accent-color;
        border-radius: 50%;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 3rpx;
          height: 10rpx;
          background: $accent-color;
        }
      }

      .icon-vol {
        width: 0;
        height: 0;
        border-left: 12rpx solid $info-color;
        border-top: 8rpx solid transparent;
        border-bottom: 8rpx solid transparent;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: -10rpx;
          left: -4rpx;
          width: 6rpx;
          height: 20rpx;
          background: $info-color;
          border-radius: 3rpx;
        }
      }
    }

    .op-name {
      font-size: 24rpx;
      color: $text-color-secondary;
    }
  }
}

.bottom-spacer {
  height: 40rpx;
}

/* 弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(30, 30, 30, 0.5);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 48rpx;
}

.modal-content {
  width: 100%;
  background: $bg-color-card;
  border-radius: 20rpx;
  overflow: hidden;

  .modal-header {
    padding: 24rpx;
    border-bottom: 1rpx solid $bg-color-secondary;

    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: $text-color-primary;
    }
  }

  .modal-body {
    padding: 24rpx;

    .modal-label {
      display: block;
      font-size: 26rpx;
      color: $text-color-tertiary;
      margin-bottom: 16rpx;
    }

    .modal-input {
      width: 100%;
      height: 88rpx;
      background: $bg-color-page;
      border: 2rpx solid $border-color;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: $text-color-primary;
      box-sizing: border-box;
    }
  }

  .modal-footer {
    display: flex;
    padding: 16rpx 24rpx 24rpx;
    gap: 12rpx;

    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
      border: none;
      padding: 0;

      &::after {
        border: none;
      }
    }

    .btn-cancel {
      background: $bg-color-page;
      color: $text-color-tertiary;
    }

    .btn-confirm {
      background: $primary-color;
      color: #fff;
    }
  }
}

.input-placeholder {
  color: $text-color-placeholder;
}
</style>
