<template>
  <div>
    <div class="event-list-container">
      <CarDetail v-if="selectedCar" :car="selectedCar" @back="selectedCar = null" />
      <div  v-else class="event-list-header">
        <div class="header-title">
         <img src="../../../assets/images/sub_icon.png" alt="list_bg" class="header-title-icon">
          <div class="header-title-text">车辆列表 ({{ totalCount }})</div>
        </div>
        <div class="header-actions">
          <FilterDropdown 
            v-model="statusFilter" 
            :options="statusOptions" 
            @change="handleFilterChange"
          />
          <FilterDropdown 
            v-model="typeFilter" 
            :options="typeOptions" 
            @change="handleFilterChange"
          />
          <div class="search-box">
            <input 
              type="text" 
              placeholder="请输入关键字搜索" 
              v-model="searchKeyword"
              @input="handleSearch"
              @keyup.enter="handleSearch"
            />
            <div class="search-icon" @click="clearSearch" v-if="!searchKeyword"></div>
            <div class="clear-icon" @click="clearSearch" v-if="searchKeyword">×</div>
          </div>
        </div>
      </div>
      <div class="event-list-content">
        <div 
          v-for="(car, index) in displayedCarList" 
          :key="car.id" 
          class="car-item"
          :class="{ 'fault': car.status === 'fault', 'online': car.status === 'online', 'offline': car.status === 'offline' }"
          @click="showDetail(car)"
        >
          <div class="car-main-info">
            <div class="car-id">{{ car.id }} ({{ getCarType(car) }})</div>
            <div class="car-actions">
              <div class="status-btn" :class="car.taskStatus">{{ getTaskStatusText(car.taskStatus) }}</div>
              <div class="online-status" :class="car.status">{{ getStatusText(car.status) }}</div>
            </div>
          </div>
          <div class="car-details">
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">行驶速度:</span>
                <span class="detail-value">{{ car.speed }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">行驶距离:</span>
                <span class="detail-value">{{ car.distance }}</span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="detail-label">任务进度:</span>
                <span class="detail-value">{{ car.progress }}%</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">负责人:</span>
                <span class="detail-value">{{ car.manager }}</span>
              </div>
            </div>
            <div class="car-owner">
              <span class="owner-icon"></span>
              <span class="owner-name">{{ car.owner }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="event-list-pagination">
        <div 
          v-for="p in totalPages" 
          :key="p" 
          class="page-btn" 
          :class="{ active: p === currentPage }"
          @click="setPage(p)"
        >{{ p }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import CarDetail from './CarDetail.vue';
import FilterDropdown from './FilterDropdown.vue';
import { listVehicle_type } from '@/api/system/vehicle_type.js';
import request from '@/utils/request';
import { getVehicleTasks, getVehicleBattery } from '@/api/vehicle/manager';
import useVehicleDisplayStore from '@/store/modules/vehicleDisplay';

// 状态筛选选项
const statusOptions = [
  { label: '全部', value: 'all' },
  { label: '在线', value: 'online' },
  { label: '离线', value: 'offline' },
  { label: '故障', value: 'fault' }
];

// 车辆类型筛选选项
const typeOptions = ref([
  { label: '全部', value: 'all' }
]);

// 当前选中的筛选值
const statusFilter = ref('all');
const typeFilter = ref('all');
// 搜索关键字
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(8);

const carList = ref([]);
const vehicleDisplayStore = useVehicleDisplayStore();

function mapStatus(s, isFault) {
  if (s === 'fault' || isFault) return 'fault';
  if (s === 'offline') return 'offline';
  if (s === 'online') return 'online';
  return 'online';
}

function mapTaskStatus(row) {
  if (row?.isFault) return 'repair';
  if (row?.currentTask) return 'task';
  return 'idle';
}

function mapRow(row) {
  return {
    id: row?.vehicleId,
    type: row?.vehicleType || '',
    status: mapStatus(row?.status, row?.isFault),
    taskStatus: mapTaskStatus(row),
    speed: row?.speed ?? '',
    distance: row?.distance ?? '',
    progress: row?.progress ?? 0,
    manager: row?.manager ?? '',
    owner: row?.organization ?? ''
  };
}

function getCarType(car) {
  const overrideType = vehicleDisplayStore.getVehicleTypeOverride(car?.id);
  const t = String(overrideType || '').toUpperCase()
  if (t === 'UNMANNED_VEHICLE') return '无人车'
  if (t === 'SPECIAL_VEHICLE') return '特勤车'
  if (t === 'AIRCRAFT') return '航空器'
  return overrideType || car?.type || '';
}

function createVirtualCarItem(vehicleId, overrideType) {
  return {
    id: vehicleId,
    type: overrideType || '',
    status: 'online',
    taskStatus: 'idle',
    speed: '',
    distance: '',
    progress: 0,
    manager: '',
    owner: ''
  }
}

const mergedCarList = computed(() => {
  const base = Array.isArray(carList.value) ? carList.value : []
  const seen = new Set(base.map((c) => c?.id).filter(Boolean))
  const overrides = vehicleDisplayStore.vehicleTypeOverrides || {}
  const enabled = vehicleDisplayStore.enabledVehicleIds || {}
  const extra = []

  Object.keys(overrides).forEach((id) => {
    if (!id || seen.has(id)) return
    const t = String(overrides[id] || '').toUpperCase()
    if (t !== 'UNMANNED_VEHICLE' && t !== 'SPECIAL_VEHICLE') return
    if (enabled[id] !== true) return
    extra.push(createVirtualCarItem(id, overrides[id]))
  })

  return [...base, ...extra]
})

async function fetchVehicles(params = { pageNum: 1, pageSize: 100 }) {
  try {
    const res = await request({
      url: '/api/vehicle-manager/vehicles',
      method: 'get',
      params
    });
    const data = res && res.data !== undefined ? res.data : res || {};
    const rows = data?.rows || data?.data?.rows || [];
    carList.value = rows.map(mapRow);
  } catch (e) {
    carList.value = [];
  }
}

// 计算总数（显示筛选后的数量）
const totalCount = computed(() => filteredCarList.value.length);

// 筛选后的车辆列表
const filteredCarList = computed(() => {
  return mergedCarList.value.filter(car => {
    if (!vehicleDisplayStore.isVehicleEnabled(car?.id)) return false;
    // 状态筛选
    if (statusFilter.value !== 'all' && car.status !== statusFilter.value) {
      return false;
    }
    
    // 类型筛选
    if (typeFilter.value !== 'all' && getCarType(car) !== typeFilter.value) {
      return false;
    }
    
    // 搜索关键字筛选
    if (searchKeyword.value.trim()) {
      const keyword = searchKeyword.value.toLowerCase().trim();
      const searchableText = [
        car.id,
        getCarType(car),
        car.manager,
        car.owner,
        getStatusText(car.status),
        getTaskStatusText(car.taskStatus)
      ].join(' ').toLowerCase();
      
      if (!searchableText.includes(keyword)) {
        return false;
      }
    }
    
    return true;
  });
});

const totalPages = computed(() => {
  const total = filteredCarList.value.length;
  const size = pageSize.value || 1;
  return Math.max(1, Math.ceil(total / size));
});

const displayedCarList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredCarList.value.slice(start, end);
});

function setPage(p) {
  if (typeof p !== 'number') return;
  const tp = totalPages.value;
  if (p < 1) currentPage.value = 1;
  else if (p > tp) currentPage.value = tp;
  else currentPage.value = p;
}

// 处理筛选变化
function handleFilterChange() {
  currentPage.value = 1;
  console.log('筛选条件变更:', { 
    status: statusFilter.value, 
    type: typeFilter.value,
    search: searchKeyword.value 
  });
}

// 处理搜索
function handleSearch() {
  currentPage.value = 1;
  console.log('搜索关键字:', searchKeyword.value);
}

// 清空搜索
function clearSearch() {
  searchKeyword.value = '';
  currentPage.value = 1;
  console.log('清空搜索关键字');
}

// 获取车辆类型列表
function getVehicleTypeList() {
  listVehicle_type({ level: 2 }).then((res) => {
    if (res.rows && Array.isArray(res.rows)) {
      // 过滤出二级类型数据
      const secondTypes = res.rows.filter((item) => item.level === 2);
      
      // 构建类型选项，保持"全部"选项在第一位
      const dynamicTypeOptions = secondTypes.map((item) => ({
        label: item.displayNameCn,
        value: item.displayNameCn
      }));
      
      // 更新车辆类型选项
      typeOptions.value = [
        { label: '全部', value: 'all' },
        ...dynamicTypeOptions
      ];
      
      console.log('车辆类型列表已更新:', typeOptions.value);
    }
  }).catch((error) => {
    console.error('获取车辆类型列表失败:', error);
  });
}

// 获取状态文本
function getStatusText(status) {
  switch(status) {
    case 'online': return '在线';
    case 'offline': return '离线';
    case 'fault': return '故障';
    default: return '未知';
  }
}

// 获取任务状态文本
function getTaskStatusText(taskStatus) {
  switch(taskStatus) {
    case 'task': return '任务中';
    case 'idle': return '闲置中';
    case 'repair': return '维修中';
    default: return '未知';
  }
}

// 暴露方法，允许父组件更新数据
defineExpose({
  updateCarList,
});

// 更新车辆列表的方法
function updateCarList(newList) {
  if (newList && Array.isArray(newList)) {
    carList.value = newList;
  }
}

const selectedCar = ref(null);
async function showDetail(car) {
  if (showDetail.inFlight) return;
  showDetail.inFlight = true;
  try {
    const res = await request({
      url: `/api/vehicle-manager/vehicles/${encodeURIComponent(car.id)}`,
      method: 'get'
    });
    const data = res && res.data !== undefined ? res.data : res || {};
    const merged = {
      ...car,
      id: data?.vehicleId ?? car.id,
      type: data?.vehicleType ?? car.type,
      brand: data?.brand ?? car.brand,
      manager: data?.manager ?? car.manager,
      company: data?.organization ?? car.company,
      phone: data?.contactPhone ?? car.phone,
      speed: data?.speed ?? car.speed,
      distance: data?.distance ?? car.distance,
      batteryTemp: data?.batteryTemp ?? car.batteryTemp
    };
    selectedCar.value = merged;
    try {
      const tres = await getVehicleTasks(merged.id);
      const env = tres && tres.data !== undefined ? tres.data : tres || {};
      let list = [];
      const cands = [env?.data, env?.rows, env?.list, env?.tasks, env];
      for (const c of cands) {
        if (Array.isArray(c)) {
          list = c;
          break;
        }
      }
      if ((!list || list.length === 0) && Array.isArray(env?.waypoints)) {
        list = [{
          id: merged.id,
          vehicleId: merged.id,
          waypoints: env.waypoints,
          timestamp: env.timestamp
        }];
      }
      const pad = (n) => String(n).padStart(2, '0');
      const fmt = (ts) => {
        const d = new Date(ts);
        return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      };
      const trackList = (list || []).map((t, idx) => {
        const pts = Array.isArray(t?.points)
          ? t.points
          : (Array.isArray(t?.waypoints) ? t.waypoints : (Array.isArray(t?.path?.points) ? t.path.points : []));
        const points = pts.map((wp, i) => {
          const ts = wp?.timestamp ?? wp?.time ?? wp?.ts ?? Date.now() + i * 1000;
          const lon = wp?.longitude ?? wp?.lng ?? wp?.lon ?? wp?.y ?? 0;
          const lat = wp?.latitude ?? wp?.lat ?? wp?.x ?? 0;
          return {
            timestamp: typeof ts === 'string' ? ts : new Date(ts).toISOString(),
            longitude: Number(lon) || 0,
            latitude: Number(lat) || 0
          };
        });
        if (points.length === 0) {
          return {
            time: '',
            desc: '',
            distance: '',
            taskId: String(t?.missionId ?? t?.id ?? idx + 1)
          };
        }
        const first = points[0];
        const last = points[points.length - 1] || first;
        let total = 0;
        for (let i = 1; i < points.length; i++) {
          const a = points[i - 1];
          const b = points[i];
          const dist = Math.sqrt(Math.pow(b.longitude - a.longitude, 2) + Math.pow(b.latitude - a.latitude, 2)) * 111;
          total += dist;
        }
        const startStr = fmt(first.timestamp);
        const endStr = fmt(last.timestamp);
        return {
          time: `${startStr}—${endStr}`,
          desc: `起点：经度${first.longitude},纬度${first.latitude} 终点：经度${last.longitude},纬度${last.latitude}`,
          distance: `${total.toFixed(2)}km`,
          taskId: String(t?.missionId ?? t?.id ?? idx + 1)
        };
      });
      selectedCar.value = { ...selectedCar.value, trackList };
    } catch (err) {
      selectedCar.value = { ...selectedCar.value, trackList: [] };
    }
    try {
      const bres = await getVehicleBattery(merged.id);
      const env = bres && bres.data !== undefined ? bres.data : bres || {};
      const inner = env && env.data !== undefined ? env.data : env || {};
      const temp = inner?.batteryStatus?.mainBattery?.temperature;
      const batteryTemp = typeof temp === 'number' ? `${temp}℃` : '--';
      selectedCar.value = { ...selectedCar.value, batteryTemp };
    } catch (err) {
      selectedCar.value = { ...selectedCar.value, batteryTemp: '--' };
    }
  } catch (e) {
    selectedCar.value = car;
  }
  showDetail.inFlight = false;
}

onMounted(() => {
  console.log('车辆列表组件已加载');
  getVehicleTypeList(); // 获取车辆类型列表
  fetchVehicles();
});
</script>

<style scoped lang="scss">
.event-list-container {
  background: #4F565F;
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  width: 391px;
  height: 80vh;
  display: flex;
  flex-direction: column;
  /* background-color: rgba(24, 33, 45, 0.85); */
  border-radius: 6px;
  overflow: hidden;
  z-index: 1;
  color: #fff;
  /* box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); */
}


.header-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  line-height: 1.8;
  font-weight: bold;
  background:url("../../../assets/images/subheading.png") no-repeat;
  background-size:100% 100%;
  padding:5px 10px;
  color: #fff;
 
}
.header-title img{
 width: 31px;
 height: 15px;
 margin-right: 5px;
}
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding:0 16px;
  margin: 10px 0;
  gap: 10px;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
  flex: 1;
}

.search-box input {
  background: rgba(19, 26, 36, 0.5);
  border: none;
  border-radius: 4px;
  padding: 6px 30px 6px 10px;
  color: #fff;
  width: 100%;
  font-size: 13px;
  outline: none;
}

.search-box input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.search-icon {
  position: absolute;
  right: 10px;
  width: 16px;
  height: 16px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ffffff'%3E%3Cpath d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  cursor: pointer;
}

.clear-icon {
  position: absolute;
  right: 10px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: color 0.2s;
}

.clear-icon:hover {
  color: #ffffff;
}

.event-list-content {
  flex: 1;
  overflow-y: auto;
  padding:0px 16px 16px 16px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 15px;
}


.car-item {
  padding: 10px;
  background-color: #424851;
  border-radius: 6px;
}
.car-item:hover {
  background-color: #373C43;
}
.car-main-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.car-id {
  font-size: 15px;
  font-weight: bold;
  color: #fff;
}

.car-actions {
  display: flex;
  gap: 8px;
}

.status-btn {
  padding: 3px 6px;
  border-radius: 2px;
  font-size: 11px;
  color: white;
}

.status-btn.task {
  background-color: #5690E7;
}

.status-btn.idle {
  background-color: #BDBDBD;
}

.status-btn.repair {
  background-color: #E8D254;
  color: #333;
}

.car-details {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.detail-item {
  display: flex;
}

.detail-label {
  color: rgba(255, 255, 255, 0.6);
  margin-right: 5px;
}

.car-owner {
  display: flex;
  align-items: center;
  margin-top: 10px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

.owner-icon {
  width: 14px;
  height: 14px;
  margin-right: 5px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ffffff'%3E%3Cpath d='M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  opacity: 0.6;
}

.online-status {
  padding: 3px 6px;
  border-radius: 2px;
  font-size: 11px;
  color: white;
}

.online-status.online {
  background-color: #5690E7;
}

.online-status.offline {
  background-color: #BDBDBD;
}

.online-status.fault {
  background-color: #B51318;
}

.event-list-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 10px 16px;
  gap: 5px;
  /* background-color: rgba(19, 26, 36, 0.5); */
}

.page-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  background-color: rgba(36, 76, 120, 0.25);
}

.page-btn.active {
  background-color: rgba(36, 76, 120, 0.5);
  color: #fff;
}

.page-btn:hover:not(.active) {
  background-color: rgba(36, 76, 120, 0.5);
}

/* 滚动条样式 */
.event-list-content::-webkit-scrollbar {
  width: 5px;
}

.event-list-content::-webkit-scrollbar-track {
  background: rgba(19, 26, 36, 0.5);
}

.event-list-content::-webkit-scrollbar-thumb {
  background: rgba(78, 113, 143, 0.5);
  border-radius: 3px;
}

.event-list-content::-webkit-scrollbar-thumb:hover {
  background: rgba(78, 113, 143, 0.8);
}

/* 响应式适配 */
@media (max-width: 768px) {
  .event-list-container {
    width: 280px;
    right: 10px;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .search-box input {
    width: 100%;
  }
}
</style>
