<!-- 车辆监控内容组件 -->
<template>
  <div class="monitor_container">
    <!-- 使用过渡效果实现平滑切换 -->
    <transition name="fade" mode="out-in">
      <!-- 根据showDetail状态显示不同的内容 -->
      <div v-if="!showDetail" key="list-view">
        <!-- 顶部统计信息 -->
        <VehicleStats
          v-model="activeStatIndex"
          :stats="vehicleStats"
          class="stats-section"
        />
        
        <!-- 内容容器 - 包含搜索区域和内容区域 -->
        <div class="app-container">
          <!-- 搜索和过滤区域 -->
          <div class="search-area">
            <el-input
              v-model="searchText"
              placeholder="请输入车牌号查询"
              clearable
              prefix-icon="Search"
              class="search-input"
              @keyup.enter="handleSearch"
            />
            
            <el-select v-model="vehicleType" placeholder="车辆类型" clearable class="search-select" @change="handleSearch">
              <el-option label="全部" value="" />
              <el-option label="驱动车" value="驱动车" />
              <el-option label="巡检车" value="巡检车" />
            </el-select>
            
            <el-select v-model="vehicleStatus" placeholder="车辆状态" clearable class="search-select" @change="handleSearch">
              <el-option label="全部" value="" />
              <el-option label="在线" value="在线" />
              <el-option label="离线" value="离线" />
              <el-option label="故障" value="故障" />
            </el-select>
    
            
            <div class="search-buttons">
              <el-button type="primary" class="search-btn" @click="handleSearch">搜索</el-button>
              <el-button class="reset-btn" @click="resetFilter">重置</el-button>
              <el-button class="export-btn" @click="exportVehicleData">导出</el-button>
            </div>
            
            <div class="action-buttons">
              <!-- 视图切换按钮 -->
              <div class="view-switcher">
                <div 
                  class="view-btn list-view" 
                  :class="{'active': viewMode === 'list'}" 
                  @click="handleViewSwitch('list')"
                  title="列表视图"
                >
                  <img src="../../../assets/images/monitor_tab1.png" alt="列表视图" />
                </div>
                <div 
                  class="view-btn card-view" 
                  :class="{'active': viewMode === 'card'}" 
                  @click="handleViewSwitch('card')"
                  title="卡片视图"
                >
                  <img src="../../../assets/images/monitor_tab2.png" alt="卡片视图" />
                </div>
              </div>
            </div>
          </div>
          
          <!-- 内容区域 -->
          <div class="content-area">
            <!-- 列表视图 -->
            <VehicleTable
              v-if="viewMode === 'list'"
              :vehicleData="filteredVehicleData"
              :filters="filters"
              @view="viewVehicleDetail"
              @control="controlVehicle"
              @selection-change="handleSelectionChange"
              :hide-search="true"
            />
            
            <!-- 卡片视图 -->
            <VehicleCards
              v-else
              :vehicleData="filteredVehicleData"
              :filters="filters"
              @view="viewVehicleDetail"
              @control="controlVehicle"
            />
          </div>
        </div>
      </div>
      
      <!-- 详情视图 - 完全替换上面的内容 -->
      <div v-else key="detail-view" class="detail-view">
        <VehicleDetail 
          :vehicle="currentVehicle" 
          @close="closeDetail" 
        />
        <!-- 车辆移动控制组件 -->
        <VehicleMovementControl
          v-if="currentVehicle"
          :vehicleData="currentVehicle"
          ref="vehicleMovementControlRef"
        />
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, defineEmits, computed, onMounted, onUnmounted, watch, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close, Search } from '@element-plus/icons-vue';
import VehicleStats from '../../../components/car/VehicleStats.vue';
import VehicleTable from '../../../components/car/VehicleTable.vue';
import VehicleCards from '../../../components/car/VehicleCards.vue';
import VehicleDetail from './detail.vue';
import VehicleMovementControl from '../../../components/map/controls/VehicleMovementControlRefactored.vue';
import { useVehicle } from '../../../composables/useVehicle';

const { proxy } = getCurrentInstance();

// 创建一个响应式的车辆详情映射
const vehicleDetails = ref(new Map());

const emit = defineEmits(['edit-vehicle', 'view-vehicle']);

// 使用车辆组合式函数
const {
  vehicleData,
  vehicleStats,
  filters,
  filteredVehicleData,
  updateFilters,
  resetFilters,
  exportData
} = useVehicle();

// 监听车辆详情更新
watch(vehicleDetails, (newDetails) => {
  // 当车辆详情更新时，同步更新当前显示的车辆详情（如果正在显示）
  if (showDetail.value && currentVehicle.value) {
    const updatedDetails = newDetails.get(currentVehicle.value.carId || currentVehicle.value.id);
    if (updatedDetails) {
      currentVehicle.value = { ...currentVehicle.value, ...updatedDetails };
    }
  }
}, { deep: true });

// 获取VehicleMovementControl组件的引用
const vehicleMovementControlRef = ref(null);

// 组件挂载时订阅车辆详情更新事件
onMounted(() => {
  // 通过ref访问VehicleMovementControl组件并监听其vehicle-details-updated事件
  if (vehicleMovementControlRef.value) {
    vehicleMovementControlRef.value.$on('vehicle-details-updated', handleVehicleDetailsUpdate);
  }
});

onUnmounted(() => {
  // 取消订阅
  if (vehicleMovementControlRef.value) {
    vehicleMovementControlRef.value.$off('vehicle-details-updated', handleVehicleDetailsUpdate);
  }
});

// 处理车辆详情更新
function handleVehicleDetailsUpdate(vehicleDetailsData) {
  // 更新车辆详情映射
  vehicleDetails.value.set(vehicleDetailsData.carId || vehicleDetailsData.id, vehicleDetailsData);
  
  // 触发更新事件，通知其他组件
  emit('vehicle-details-updated', vehicleDetailsData);
}

// 搜索相关
const searchText = ref('');
const vehicleType = ref('');
const vehicleStatus = ref('');

// 统计数据选中索引
const activeStatIndex = ref(0);

// 视图模式 - 列表或卡片
const viewMode = ref('card');

// 状态过滤器
const statusFilter = ref('default');

// 表格选中行
const selectedRows = ref([]);

// 详情显示控制
const showDetail = ref(false);
const currentVehicle = ref(null);

// 查看车辆详情 - 点击查看按钮时触发
function viewVehicleDetail(vehicle) {
  // 合并最新的车辆详情数据（如果存在）
  const latestDetails = vehicleDetails.value.get(vehicle.carId || vehicle.id);
  currentVehicle.value = latestDetails ? { ...vehicle, ...latestDetails } : vehicle;
  showDetail.value = true;
}

// 关闭详情 - 返回列表视图
function closeDetail() {
  showDetail.value = false;
}

// 处理视图切换
function handleViewSwitch(type) {
  viewMode.value = type;
}

// 远程控制车辆
function controlVehicle(vehicle) {
  ElMessageBox.confirm(
    `确定要对 ${vehicle.id} 进行远程控制吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        type: 'success',
        message: `已发送控制指令到车辆 ${vehicle.id}`,
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
      });
    });
}

// 编辑车辆信息
function editVehicle(vehicle) {
  emit('edit-vehicle', vehicle);
}

// 处理表格选择变化
function handleSelectionChange(rows) {
  selectedRows.value = rows;
}

// 处理搜索
function handleSearch() {
  // 更新过滤条件
  updateFilters({
    searchText: searchText.value,
    vehicleType: vehicleType.value,
    vehicleStatus: vehicleStatus.value
  });
}

// 重置过滤器
function resetFilter() {
  searchText.value = '';
  vehicleType.value = '';
  vehicleStatus.value = '';
  resetFilters();
}

// 导出数据
function exportVehicleData() {
  try {
    proxy.download('system/vehicle_type/export', {}, `vehicle_type_${new Date().getTime()}.xlsx`);
  } catch (e) {
    console.error('导出失败:', e);
  }
}

// 设置状态过滤器
function setStatusFilter(status) {
  statusFilter.value = status;
  // 根据状态过滤数据
  updateFilters({
    ...filters.value,
    status: status === 'default' ? '' : status
  });
}
</script>

<style lang="scss" scoped>
.monitor_container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 100%;
}

.stats-section {
  margin-bottom: 20px;
}

.app-container {
  padding: 20px;
  background-color: #292C38;
  color: #ffffff;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: calc(100vh - 250px);
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: calc(100% - 70px); /* 减去搜索区域的高度 */
  min-height: 500px;
}

.detail-view {
  height: calc(100vh - 100px);
  overflow: hidden;
  animation: fadeIn 0.3s ease;

}

/* 搜索区域样式 */
.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding-bottom: 15px;
  margin-bottom: 15px;
  border-bottom: 1px solid #343744;
  
  .search-input {
    width: 250px;
  }
  
  .search-select {
    width: 150px;
  }
  
  /* 状态选择器样式 */
  .status-selector {
    background-color: #343744;
    border-radius: 8px;
    padding: 10px;
    margin-right: 20px;
    
    .status-label {
      color: #96A0B5;
      font-size: 14px;
      margin-bottom: 8px;
    }
    
    .status-options {
      display: flex;
      flex-direction: column;
      gap: 10px;
      
      .status-option {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 6px 10px;
        border-radius: 4px;
        cursor: pointer;
        
        &:hover {
          background-color: #2B3B5A;
        }
        
        &.active {
          background-color: #2B3B5A;
          
          .status-icon {
            background-color: #409eff;
          }
          
          .status-text {
            color: #fff;
          }
        }
        
        .status-icon {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 4px;
          background-color: #292C38;
          
          img {
            width: 20px;
            height: 20px;
            object-fit: contain;
          }
          
          &.selected {
            background-color: #409eff;
          }
        }
        
        .status-text {
          color: #96A0B5;
          font-size: 14px;
        }
      }
    }
  }
  
  .search-buttons {
    display: flex;
    gap: 10px;
  }
  
  .action-buttons {
    margin-left: auto;
    display: flex;
    gap: 10px;
    
    .view-switcher {
      display: flex;
      background-color: #343744;
      border-radius: 8px;
      overflow: hidden;
      
      .view-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 36px;
        height: 36px;
        cursor: pointer;
        transition: all 0.3s;
        
        img {
          width: 20px;
          height: 20px;
          object-fit: contain;
        }
        
        &:hover {
          background-color: #2B3B5A;
        }
        
        &.active {
          background-color: #409eff;
        }
      }
    }
  }
}

/* 自定义输入框样式 */
:deep(.el-input__wrapper) {
  background: #343744 !important;
  color: #96A0B5 !important;
  border-radius: 8px !important;
  height: 36px !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-select__wrapper) {
  background: #343744 !important;
  color: #96A0B5 !important;
  border-radius: 8px !important;
  height: 36px !important;
  font-size: 15px;
  border: none !important;
}

:deep(.el-button) {
  background: #343744;
  border-color: transparent;
  border-radius: 8px;
  height: 36px;
  
  &.el-button--primary {
    background-color: #409eff;
  }
  
  &:hover, &:focus {
    background: #2B3B5A;
    border-color: transparent;
  }
  
  &.el-button--primary:hover, &.el-button--primary:focus {
    background-color: #337ecc;
  }
}

/* 淡入淡出过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-view {
    min-height: calc(100vh - 80px);
  }
  
  .search-area {
    flex-direction: column;
    align-items: flex-start;
    
    .search-input,
    .search-select {
      width: 100%;
    }
    
    .action-buttons {
      margin-left: 0;
      margin-top: 10px;
      width: 100%;
      justify-content: flex-end;
    }
  }
}
</style>
const { proxy } = getCurrentInstance();
const { proxy } = getCurrentInstance();
