<!-- TrackPlayback.vue（轨迹回放页面） -->
<template>
  <div class="track-playback-content">
    <!-- 左侧搜索+列表 -->
    <div class="left-list">
     
      <el-input
        v-model="search"
        class="search-input"
        placeholder="请输入任务号/车辆名"
        :suffix-icon="Search"
      />
      <el-scrollbar class="task-list">
        <div
          v-for="item in filteredTasks"
          :key="item.id"
          class="task-item"
          :class="{ active: item.id === activeId }"
          @click="selectTask(item)"
        >
          <!-- 选中三角角标 -->
          <div v-if="item.id === activeId" class="corner-triangle">
            
          </div>
          <!-- 第一行：蓝色圆点+编号+任务名 -->
          <div class="task-row1">
            <span class="dot"></span>
            <span class="task-no">{{ item.no }}</span>
            <span class="task-name">{{ item.name }}</span>
          </div>
          <!-- 第二行：时间段 -->
          <div class="task-row2">{{ item.time }}</div>
          <!-- 第三行：起点——>终点 -->
          <div class="task-row3">
            <span class="point start">起点</span>
            <span class="label">{{ item.start }}</span>
            <!-- <span class="arrow">——&gt;</span> -->
            <img class="arrow" src="@/assets/images/arrow.png" alt="arrow">
            <span class="point end">终点</span>
            <span class="label">{{ item.end }}</span>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <!-- 右侧地图及轨迹详情 -->
    <div class="right-map">
      <div class="map-container">
        <div class="map-img-placeholder"></div>
        <!-- 轨迹详情卡片（左上角） -->
        <div class="track-detail-panel">
          <!-- 第一行：标题和回放按钮两端对齐 -->
          <div class="panel-header">
            <div class="header-left">
              <span class="dot"></span>
              <span class="panel-title">轨迹详情</span>
            </div>
            <el-button size="small" type="primary" class="replay-btn" @click="handleReplay">回放</el-button>
          </div>
          
          <!-- 第二行：车辆信息一行显示 -->
          <div class="vehicle-stats-row">
            <div class="stat-item">
              <span class="stat-value">{{  licensePlate }}</span>
              <span class="stat-label">车牌号</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ trackDetails.maxSpeed }}km/h</span>
              <span class="stat-label">最大时速</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ trackDetails.averageSpeed }}km/h</span>
              <span class="stat-label">平均时速</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ trackDetails.totalDistance }}km</span>
              <span class="stat-label">行驶总里程</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ trackDetails.totalTime }}min</span>
              <span class="stat-label">行驶耗时</span>
            </div>
            <div class="stat-item warn">
              <span class="stat-value">{{ trackDetails.warnings }}</span>
              <span class="stat-label">冲突告警</span>
            </div>
            <div class="stat-item prewarn">
              <span class="stat-value">{{ trackDetails.preWarnings }}</span>
              <span class="stat-label">冲突预警</span>
            </div>
            <!-- <div class="current-time">
              <span class="time-value">13:46:53</span>
            </div> -->
          </div>
          
          <!-- 第三行：进度条和倍速 -->
          <div class="progress-row">
            <div class="progress-bar-wrap"
                 @mousemove="handleProgressHover"
                 @mouseleave="showTooltip = false"
                 @click="handleProgressClick">
              <div class="progress-bar-bg"></div>
              <div class="progress-bar-fg" :style="{width: progress+'%'}"></div>
              <!-- 进度条拖动点 -->
              <div class="progress-thumb" :style="{left: progress+'%'}" @mousedown="startDrag"></div>
              <!-- 预警/告警红旗 -->
              <div
                v-for="flag in flags"
                :key="flag.label"
                class="progress-flag"
                :style="{left: flag.percent+'%'}"
                :title="flag.label"
              >
                <div class="flag-icon"></div>
              </div>
              <!-- 鼠标悬浮提示 -->
              <div v-if="showTooltip" class="progress-tooltip" :style="{left: tooltipLeft+'px'}">
                {{ tooltipTime }}
              </div>
            </div>
            <div class="speed-select">
              <el-dropdown @command="setSpeed">
                <span class="el-dropdown-link">
                  {{ speed }}x <i class="el-icon-arrow-down"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="1">1x</el-dropdown-item>
                    <el-dropdown-item command="2">2x</el-dropdown-item>
                    <el-dropdown-item command="4">4x</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <!-- 第四行：开始和结束时间 -->
          <div class="time-row">
            <span class="start-time">开始时间 {{ trackDetails.startTime || "--" }}</span>
            <span class="end-time">结束时间 {{ trackDetails.endTime || "--" }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineProps, watchEffect } from "vue";
import { Search } from "@element-plus/icons-vue";
import { 
  listCarRunInfo, 
  exportCarRunInfo, 
  listCarRunInfoByVehicleId, 
  listCarRunInfoByLicensePlate, 
  getLatestLocationByVehicleId, 
  getLatestLocationByLicensePlate,
  batchQueryVehicleTrajectory 
} from "@/api/monitor/carRunInfo";
import { ElMessage } from "element-plus";

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  timeRange: [],
  vehicleId: '',
  licensePlate: ''
});

// 数据列表
const runInfoList = ref([]);
const loading = ref(false);
const total = ref(0);

// 车辆信息模拟数据
const carInfo = {
  img: "https://cdn.jsdelivr.net/gh/duogongneng/testcdn/car-demo.jpg",
  no: "QN001",
  status: "在线",
  statusClass: "online",
  type: "货运车",
  driver: "张三",
  phone: "15689742356",
};

// 任务模拟数据（将由接口数据替换）
const tasks = ref([]);

const search = ref("");
const activeId = ref(0);

// 接收vehicle属性
const props = defineProps({
  vehicle: { type: Object, default: () => ({}) },
  detail: { type: Object, default: () => ({}) },
  tasks: { type: Array, default: () => [] }
});

// 轨迹详情数据
const trackDetails = ref({
  licensePlate: "",
  maxSpeed: "0",
  averageSpeed: "0",
  totalDistance: "0",
  totalTime: "0",
  warnings: "0",
  preWarnings: "0",
  startTime: "",
  endTime: ""
});

const activeVehicleId = ref("");

// 监听vehicle属性变化
watchEffect(() => {
  if (props.vehicle?.carId) {
    activeVehicleId.value = props.vehicle.carId;
    // 更新查询参数
    queryParams.value.vehicleId = '';
    queryParams.value.licensePlate = props.vehicle.carId;
  }
});

function normalizeTasks(inputTasks) {
  return (Array.isArray(inputTasks) ? inputTasks : []).map((t) => {
    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) => {
      const ts = wp?.timestamp ?? wp?.time ?? wp?.ts ?? Date.now();
      const lon = wp?.longitude ?? wp?.lng ?? wp?.lon ?? wp?.y ?? 0;
      const lat = wp?.latitude ?? wp?.lat ?? wp?.x ?? 0;
      const spd = Number(wp?.speed ?? wp?.v ?? 0) || 0;
      return {
        timestamp: typeof ts === "string" ? ts : new Date(ts).toISOString(),
        longitude: Number(lon) || 0,
        latitude: Number(lat) || 0,
        speed: spd,
        vehicleId: t?.vehicleId ?? props.vehicle?.carId ?? "",
        licensePlate: t?.licensePlate ?? props.vehicle?.licensePlate ?? ""
      };
    });
    const first = points[0];
    const last = points[points.length - 1] || first;
    const avg = points.length > 0 ? (points.reduce((s, p) => s + (p.speed || 0), 0) / points.length).toFixed(2) : "0";
    return {
      id: (t?.id ?? t?.vehicleId ?? props.vehicle?.carId ?? "0").toString(),
      no: (t?.no ?? t?.missionId ?? t?.id ?? props.vehicle?.carId ?? "").toString(),
      name: t?.name ?? t?.missionType ?? "任务",
      time: first && last ? `${first.timestamp}--${last.timestamp}` : "",
      start: first ? `经度${first.longitude},纬度${first.latitude}` : "",
      end: last ? `经度${last.longitude},纬度${last.latitude}` : "",
      speed: `${avg}km/h`,
      licensePlate: t?.licensePlate ?? props.vehicle?.licensePlate ?? "",
      points
    };
  });
}

watchEffect(() => {
  if (Array.isArray(props.tasks) && props.tasks.length > 0) {
    const normalized = normalizeTasks(props.tasks);
    tasks.value = normalized;
    if (tasks.value.length > 0) {
      activeId.value = tasks.value[0].id;
      selectTask(tasks.value[0]);
    }
  } else {
    const hasWaypoints =
      (Array.isArray(props.detail?.path?.waypoints) && props.detail.path.waypoints.length > 0) ||
      (Array.isArray(props.detail?.waypoints) && props.detail.waypoints.length > 0) ||
      (Array.isArray(props.detail?.path?.path) && props.detail.path.path.length > 0);
    if (hasWaypoints) {
      buildTasksFromDetail();
    }
  }
});

function buildTasksFromDetail() {
  const pathArr = props.detail?.path?.waypoints || props.detail?.waypoints || props.detail?.path?.path;
  if (!Array.isArray(pathArr) || pathArr.length === 0) return;
  const baseTs = props.detail?.timestamp || props.detail?.path?.timestamp || props.detail?.lastSeenAt || Date.now();
  const sp =
    props.detail?.position?.v ??
    props.detail?.chassis?.sys_info?.state_info?.d_speed_kmph ??
    0;
  const vid = props.detail?.vehicleId || props.vehicle?.carId || "";
  const lp = props.vehicle?.licensePlate || "";
  const points = pathArr.map((p, i) => {
    return {
      timestamp: new Date(baseTs + i * 1000).toISOString(),
      longitude: p.y ?? p.longitude ?? p.lng ?? p.lon ?? p.x,
      latitude: p.x ?? p.latitude ?? p.lat ?? p.y,
      speed: Number(sp) || 0,
      vehicleId: vid,
      licensePlate: lp
    };
  });
  const firstPoint = points[0];
  const lastPoint = points[points.length - 1];
  const avgSpeed = (
    points.reduce((sum, pt) => sum + (pt.speed || 0), 0) / points.length
  ).toFixed(2);
  tasks.value = [
    {
      id: vid?.toString() || "0",
      no: vid?.toString() || "",
      name: "任务",
      time: `${firstPoint.timestamp}--${lastPoint.timestamp}`,
      start: `经度${firstPoint.longitude},纬度${firstPoint.latitude}`,
      end: `经度${lastPoint.longitude},纬度${lastPoint.latitude}`,
      speed: `${avgSpeed}km/h`,
      points
    }
  ];
  activeId.value = tasks.value[0].id;
}

watchEffect(() => {
  const hasWaypoints =
    (Array.isArray(props.detail?.path?.waypoints) && props.detail.path.waypoints.length > 0) ||
    (Array.isArray(props.detail?.waypoints) && props.detail.waypoints.length > 0) ||
    (Array.isArray(props.detail?.path?.path) && props.detail.path.path.length > 0);
  if ((!props.tasks || props.tasks.length === 0) && hasWaypoints && (props.detail?.vehicleId || props.vehicle?.carId)) {
    buildTasksFromDetail();
  }
});
// 获取车辆运动信息列表数据
async function getRunInfoList() {
  loading.value = true;
  try {
    let response;
    const qp = queryParams.value;
    const lp = qp.licensePlate;
    const vid = qp.vehicleId;
    const rest = {
      pageNum: qp.pageNum,
      pageSize: qp.pageSize,
      timeRange: qp.timeRange
    };
    if (lp) {
      response = await listCarRunInfoByLicensePlate(encodeURIComponent(lp), rest);
    } else if (vid) {
      response = await listCarRunInfoByVehicleId(vid, rest);
    } else {
      response = await listCarRunInfo(rest);
    }
    // console.log("-----------------------------------,", response);
    
    if (response.code === 200) {
      runInfoList.value = response.rows || [];
      total.value = response.total;
      
      // 转换数据格式为任务列表
      // 根据车辆ID对数据进行分组处理
      const groupByVehicle = {};
      runInfoList.value.forEach(item => {
        if (!groupByVehicle[item.vehicleId]) {
          groupByVehicle[item.vehicleId] = [];
        }
        groupByVehicle[item.vehicleId].push(item);
      });
      
      // 将分组后的数据转换为任务列表格式
      const tasksList = [];
      Object.keys(groupByVehicle).forEach((vehicleId, index) => {
        const vehicleData = groupByVehicle[vehicleId];
        const firstPoint = vehicleData[0];
        const lastPoint = vehicleData[vehicleData.length - 1];
        
        // 计算平均速度
        const avgSpeed = (vehicleData.reduce((sum, point) => sum + point.speed, 0) / vehicleData.length).toFixed(2);
        
        const licensePlate = firstPoint.licensePlate || "--";
        
        tasksList.push({
          id: vehicleId,
          no: vehicleId,
          name: `车辆${licensePlate}轨迹`,
          time: `${firstPoint.timestamp}--${lastPoint.timestamp}`,
          start: `经度${firstPoint.longitude},纬度${firstPoint.latitude}`,
          end: `经度${lastPoint.longitude},纬度${lastPoint.latitude}`,
          status: "已完成",
          speed: `${avgSpeed}km/h`,
          licensePlate: licensePlate,
          points: vehicleData
        });
      });
      
      tasks.value = tasksList;
      
      // 设置默认选中第一项
      if (tasks.value.length > 0) {
        activeId.value = tasks.value[0].id;
        // 显示第一个任务的轨迹详情
        selectTask(tasks.value[0]);
      }
    } else {
      ElMessage.error(response.msg || '获取车辆运动信息列表失败');
    }
  } catch (error) {
    console.error('获取车辆运动信息列表异常', error);
    ElMessage.error('获取车辆运动信息列表异常');
  } finally {
    loading.value = false;
  }
}





// 批量查询车辆轨迹回放数据
async function getBatchTrajectoryPlayback(vehicleIds, timeRange) {
  if (!vehicleIds || vehicleIds.length === 0) return;
  
  loading.value = true;
  try {
    const requestData = {
      vehicleIds: vehicleIds,
      startTime: timeRange?.[0] || '',
      endTime: timeRange?.[1] || '',
      pageNum: 1,
      pageSize: 1000 // 获取更多数据用于回放
    };
    
    const response = await batchQueryVehicleTrajectory(requestData);
    console.log('批量轨迹查询结果:', response);
    
    if (response.code === 200) {
      const trajectoryData = response.data || response.rows || [];
      
      // 按车辆ID分组处理轨迹数据
      const groupedTrajectories = {};
      trajectoryData.forEach(point => {
        if (!groupedTrajectories[point.vehicleId]) {
          groupedTrajectories[point.vehicleId] = [];
        }
        groupedTrajectories[point.vehicleId].push(point);
      });
      
      // 更新任务列表，添加轨迹回放数据
      const updatedTasks = [];
      Object.keys(groupedTrajectories).forEach(vehicleId => {
        const points = groupedTrajectories[vehicleId];
        points.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        
        const firstPoint = points[0];
        const lastPoint = points[points.length - 1];
        const avgSpeed = (points.reduce((sum, p) => sum + (p.speed || 0), 0) / points.length).toFixed(2);
        
        const licensePlate = firstPoint.licensePlate || "--";
        
        updatedTasks.push({
          id: vehicleId,
          no: vehicleId,
          name: `车辆${licensePlate}轨迹回放`,
          time: `${firstPoint.timestamp}--${lastPoint.timestamp}`,
          start: `经度${firstPoint.longitude},纬度${firstPoint.latitude}`,
          end: `经度${lastPoint.longitude},纬度${lastPoint.latitude}`,
          status: "回放就绪",
          speed: `${avgSpeed}km/h`,
          licensePlate: licensePlate,
          points: points,
          isPlayback: true // 标记为回放数据
        });
      });
      
      // 合并或替换任务列表
      if (updatedTasks.length > 0) {
        tasks.value = updatedTasks;
        // 默认选中第一个并显示其轨迹详情
        if (tasks.value.length > 0) {
          activeId.value = tasks.value[0].id;
          selectTask(tasks.value[0]);
        }
        ElMessage.success(`成功加载${updatedTasks.length}个车辆的轨迹回放数据`);
      } else {
        ElMessage.warning('未找到轨迹回放数据');
      }
      
    } else {
      ElMessage.error(response.msg || '批量查询车辆轨迹失败');
    }
  } catch (error) {
    console.error('批量查询车辆轨迹异常', error);
    ElMessage.error('批量查询车辆轨迹异常');
  } finally {
    loading.value = false;
  }
}

const filteredTasks = computed(() => {
  if (!search.value) return tasks.value;
  return tasks.value.filter(
    (t) =>
      t.name.includes(search.value) ||
      t.no.includes(search.value) ||
      t.id.toString().includes(search.value)
  );
});

const activeTask = computed(() => tasks.value.find((t) => t.id === activeId.value));

// 计算车牌号
const licensePlate = computed(() => {
  if (activeTask.value?.licensePlate) {
    return activeTask.value.licensePlate;
  } else if (trackDetails.value.licensePlate) {
    return trackDetails.value.licensePlate;
  } else if (props.vehicle?.licensePlate) {
    return props.vehicle.licensePlate;
  }
  return "--";
});

function selectTask(item) {
  activeId.value = item.id;
  
  // 从任务中提取轨迹数据
  if (item.points && item.points.length > 0) {
    processTrackPoints(item.points);
    
    // 更新轨迹详情中的车牌号
    if (item.licensePlate) {
      trackDetails.value.licensePlate = item.licensePlate;
    }
  }
}

// 处理轨迹点数据
function processTrackPoints(points) {
  // 按时间排序
  points.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
  
  // 获取第一个点的车牌号（如果存在）
  const firstPoint = points[0];
  const currentLicensePlate = trackDetails.value.licensePlate; // 保存当前车牌号
  
  if (firstPoint && firstPoint.licensePlate) {
    trackDetails.value.licensePlate = firstPoint.licensePlate;
  }
  
  // 计算最大速度
  const maxSpeed = Math.max(...points.map(p => p.speed)).toFixed(2);
  
  // 计算平均速度
  const avgSpeed = (points.reduce((sum, p) => sum + p.speed, 0) / points.length).toFixed(2);
  
  // 计算总距离 (简单估算，实际应该使用更复杂的地理距离计算)
  let totalDistance = 0;
  for (let i = 1; i < points.length; i++) {
    const prev = points[i-1];
    const curr = points[i];
    // 使用直线距离简单估算
    const dist = Math.sqrt(
      Math.pow(curr.longitude - prev.longitude, 2) + 
      Math.pow(curr.latitude - prev.latitude, 2)
    ) * 111000; // 粗略转换为米
    totalDistance += dist;
  }
  const distanceKm = (totalDistance / 1000).toFixed(2);
  
  // 计算总时间
  const startTime = new Date(points[0].timestamp);
  const endTime = new Date(points[points.length-1].timestamp);
  const totalMinutes = Math.round((endTime - startTime) / (60 * 1000));
  
  // 更新轨迹详情，保留车牌号
  trackDetails.value = {
    licensePlate: firstPoint?.licensePlate || currentLicensePlate || "--",
    maxSpeed: maxSpeed,
    averageSpeed: avgSpeed,
    totalDistance: distanceKm,
    totalTime: totalMinutes > 0 ? totalMinutes.toString() : "1",
    warnings: "0", // 实际应从数据中获取告警信息
    preWarnings: "0", // 实际应从数据中获取预警信息
    startTime: points[0].timestamp,
    endTime: points[points.length-1].timestamp
  };
  
  // 处理告警标记点 (示例，实际应根据数据判断)
  flags.value = [
    { 
      percent: 20, 
      label: "告警 " + points[Math.floor(points.length * 0.2)].timestamp 
    },
    { 
      percent: 60, 
      label: "预警 " + points[Math.floor(points.length * 0.6)].timestamp 
    }
  ];
}

// 回放按钮点击处理函数
function handleReplay() {
  // 获取当前选中任务
  const currentTask = tasks.value.find(t => t.id === activeId.value);
  
  if (currentTask) {
    if (currentTask.points && currentTask.points.length > 0) {
      // 如果任务已包含轨迹点数据，直接处理
      processTrackPoints(currentTask.points);
      ElMessage.success('开始轨迹回放');
    } else {
      // 使用批量查询获取轨迹回放数据
      const vehicleIds = [currentTask.id.toString()];
      getBatchTrajectoryPlayback(vehicleIds, queryParams.value.timeRange);
    }
  } else if (queryParams.value.vehicleId) {
    // 使用查询参数中的车辆ID进行批量查询
    const vehicleIds = [queryParams.value.vehicleId];
    getBatchTrajectoryPlayback(vehicleIds, queryParams.value.timeRange);
  } else if (props.vehicle?.carId) {
    // 使用传入的车辆ID进行批量查询
    const vehicleIds = [props.vehicle.carId];
    getBatchTrajectoryPlayback(vehicleIds, queryParams.value.timeRange);
  } else {
    // 如果有多个车辆，批量查询所有车辆的轨迹
    if (tasks.value.length > 0) {
      const vehicleIds = tasks.value.map(task => task.id.toString());
      getBatchTrajectoryPlayback(vehicleIds, queryParams.value.timeRange);
    } else {
      // 获取列表数据
      getRunInfoList();
      ElMessage.info('请先选择一个车辆任务');
    }
  }
}

// 批量加载所有车辆轨迹回放数据
function loadAllTrajectoryPlayback() {
  if (tasks.value.length === 0) {
    ElMessage.warning('暂无车辆数据');
    return;
  }
  
  const vehicleIds = tasks.value.map(task => task.id.toString());
  getBatchTrajectoryPlayback(vehicleIds, queryParams.value.timeRange);
}

// 导出车辆运动信息
async function handleExport() {
  try {
    await exportCarRunInfo(queryParams.value);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出车辆运动信息异常', error);
    ElMessage.error('导出车辆运动信息异常');
  }
}

const progress = ref(30); // 进度百分比
const speed = ref(1);
const showTooltip = ref(false);
const tooltipTime = ref("");
const tooltipLeft = ref(0);

// 预警/告警红旗模拟数据（将由接口数据替换）
const flags = ref([]);

// 拖动进度条
let dragging = false;
function startDrag(e) {
  dragging = true;
  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
}
function onDrag(e) {
  if (!dragging) return;
  const bar = document.querySelector(".progress-bar-wrap");
  const rect = bar.getBoundingClientRect();
  let percent = ((e.clientX - rect.left) / rect.width) * 100;
  percent = Math.max(0, Math.min(100, percent));
  progress.value = percent;
}
function stopDrag() {
  dragging = false;
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
}

// 鼠标悬浮显示时分秒
function handleProgressHover(e) {
  const bar = e.currentTarget;
  const rect = bar.getBoundingClientRect();
  let percent = ((e.clientX - rect.left) / rect.width) * 100;
  percent = Math.max(0, Math.min(100, percent));
  tooltipLeft.value = e.clientX - rect.left;
  // 假设总时长20分钟
  const totalSec = 20 * 60;
  const sec = Math.round((percent / 100) * totalSec);
  const mm = String(Math.floor(sec / 60)).padStart(2, "0");
  const ss = String(sec % 60).padStart(2, "0");
  tooltipTime.value = `${mm}:${ss}`;
  showTooltip.value = true;
}
function handleProgressClick(e) {
  const bar = e.currentTarget;
  const rect = bar.getBoundingClientRect();
  let percent = ((e.clientX - rect.left) / rect.width) * 100;
  percent = Math.max(0, Math.min(100, percent));
  progress.value = percent;
}
function setSpeed(val) {
  speed.value = val;
}

// 页面加载时获取数据
onMounted(() => {
  // 如果从父组件传入了车辆信息，初始化车牌号和默认数据
  if (props.vehicle) {
    if (props.vehicle.licensePlate) {
      trackDetails.value.licensePlate = props.vehicle.licensePlate;
    }
    
    // 初始化一个默认的轨迹详情数据
    trackDetails.value = {
      licensePlate: props.vehicle.licensePlate || "--",
      maxSpeed: "0",
      averageSpeed: "0",
      totalDistance: "0",
      totalTime: "0",
      warnings: "0",
      preWarnings: "0",
      startTime: "",
      endTime: ""
    };
  }
  
  if (!props.detail?.path?.path) {
    getRunInfoList();
  }

});
</script>

<style scoped lang="scss">
.track-playback-content {
  display: flex;
  gap: 20px;
  flex: 1;
}
.left-list {
  width: 25%;

  border-radius: 8px;
  padding: 16px 8px;
  display: flex;
  flex-direction: column;
}
.search-input {
  margin-bottom: 10px;
}
.task-list {
  max-height: 400px;
}
.task-item {
  position: relative;
  padding: 16px 16px 14px 16px;
  border-radius: 8px;
  margin-bottom: 14px;
  cursor: pointer;
  background: #343744;
  color: #fff;
  border: 2px solid transparent;
  transition: border 0.2s, box-shadow 0.2s;
  box-sizing: border-box;
}
.task-item.active {
  border: 2px solid #347ae2;
  box-shadow: 0 2px 8px rgba(52,122,226,0.08);
}
.corner-triangle {
  background: url('@/assets/images/choice.png') no-repeat 100% 100%;
  position: absolute;
  right: 0;
  top: 0;
  width: 38px;
  height: 33px;
  z-index: 2;
}
.task-row1 {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 4px;
  .dot {
    width: 8px;
    height: 8px;
    background: #347ae2;
    border-radius: 50%;
    display: inline-block;
    margin-right: 2px;
  }
  .task-no {
    color: #347ae2;
    font-weight: bold;
  }
  .task-name {
    color: #fff;
  }
}
.task-row2 {
  font-size: 13px;
  color: #b0b8c9;
  margin-bottom: 6px;
}
.task-row3 {
  display: flex;
  align-items: center;
  gap: 8px;
  .label{
    font-size: 13px;
    color:#fff;
  }
  .point {
    padding: 0px 5px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    background: transparent;
    border: 1.5px solid;
    &.start {
      border-color: #347ae2;
      background: rgba(52, 122, 226, 0.20);
      color: #347ae2;
    }
    &.end {
      border-color: #27ae60;
      background: rgba(39, 174, 96, 0.20);
      color: #27ae60;
    }
  }
  .arrow {
    color: #b0b8c9;
    font-size: 15px;
    font-weight: bold;
  }
}
.right-map {
  flex: 1;
  border: 1px solid #343744;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-width: 0;
}
.map-container {
  flex: 1;

  border-radius: 8px;
  min-height: 400px;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
.map-img-placeholder {
  width: 100%;
  height: 100%;
 
  border-radius: 12px;
}
.track-detail-panel {
  position: absolute;
  top: 24px;
  left: 24px;
  min-width: 520px;
  background: rgba(41,44,56,0.8);
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.18);
  padding: 18px 28px 18px 20px;
  z-index: 10;
  .panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .dot {
        width: 10px;
        height: 10px;
        background: #347ae2;
        border-radius: 50%;
        display: inline-block;
      }
      
      .panel-title {
        font-size: 16px;
        font-weight: bold;
        color: #4ea1ff;
      }
    }
    
    .replay-btn {
      // 按钮样式保持默认
    }
  }
  // 第二行：车辆信息一行显示
  .vehicle-stats-row {
    display: flex;
    align-items: flex-start;
    gap: 20px;
    margin-bottom: 12px;
    
    .vehicle-info {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      // min-width: 80px;
      padding:3px 10px;
  
      
      .vehicle-number {
        font-size: 18px;
        font-weight: bold;
        color: #fff;
        line-height: 1.2;
        margin-bottom: 2px;
      }
      
      .vehicle-label {
        font-size: 12px;
        color: #8a8e99;
        line-height: 1;
      }
    }
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      // min-width: 60px;
      
      .stat-value {
        font-size: 16px;
        font-weight: bold;
        color: #fff;
        line-height: 1.2;
        margin-bottom: 2px;
      }
      
      .stat-label {
        font-size: 12px;
        color: #8a8e99;
        line-height: 1;
      }
      
      &.warn .stat-value {
        color: #e34d59;
      }
      
      &.prewarn .stat-value {
        color: #f7b500;
      }
    }
    
    .current-time {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: rgba(52, 122, 226, 0.15);
      border-radius: 6px;
      padding: 8px 12px;
      min-width: 80px;
      margin-left: auto;
      
      .time-value {
        font-size: 16px;
        font-weight: bold;
        color: #4ea1ff;
        line-height: 1;
      }
    }
  }
  // 第三行：进度条和倍速
  .progress-row {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 8px;
    
    .progress-bar-wrap {
      position: relative;
      height: 8px;
      background: transparent;
      cursor: pointer;
      user-select: none;
      flex: 1;
    }
    
    .speed-select {
      .el-dropdown-link {
        color: #4ea1ff;
        cursor: pointer;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }
  
  // 第四行：开始和结束时间
  .time-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13px;
    color: #b0b8c9;
    
    .start-time, .end-time {
      font-size: 13px;
      color: #b0b8c9;
    }
  }
  
  // 进度条相关样式
  .progress-bar-bg {
    position: absolute;
    left: 0; top: 0; right: 0; bottom: 0;
    background: #343744;
    border-radius: 4px;
  }
  
  .progress-bar-fg {
    position: absolute;
    left: 0; top: 0; bottom: 0;
    background: linear-gradient(90deg, #347ae2, #4ea1ff);
    border-radius: 4px;
    height: 8px;
    z-index: 1;
  }
  
  .progress-thumb {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 16px;
    height: 16px;
    background: #fff;
    border: 3px solid #347ae2;
    border-radius: 50%;
    z-index: 2;
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(52,122,226,0.12);
  }
  
  .progress-flag {
    position: absolute;
    top: -16px;
    z-index: 3;
    width: 16px;
    height: 20px;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    pointer-events: auto;
    
    .flag-icon {
      position: relative;
      width: 2px;
      height: 18px;
      background: #e34d59;
      
      // 旗杆
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 2px;
        height: 18px;
        background: #e34d59;
      }
      
      // 小红旗
      &::after {
        content: '';
        position: absolute;
        left: 2px;
        top: 2px;
        width: 0;
        height: 0;
        border-left: 10px solid #e34d59;
        border-top: 3px solid transparent;
        border-bottom: 3px solid transparent;
        // 添加小三角形缺口效果
        clip-path: polygon(0 0, 80% 0, 70% 50%, 80% 100%, 0 100%);
      }
    }
  }
  
  .progress-tooltip {
    position: absolute;
    top: -32px;
    background: #23263a;
    color: #fff;
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 4px;
    white-space: nowrap;
    box-shadow: 0 2px 8px rgba(52,122,226,0.10);
    z-index: 10;
    pointer-events: none;
  }
}
</style>
