<!-- 车辆详情内容组件 -->
<template>
  <div class="vehicle-detail-content">
    <!-- 上部分 -->
    <div class="detail-header">
      <!-- 返回按钮 - 添加在右上角 -->
      <div class="back-button">
        <el-button
          type="primary"
          plain
          class="btn custom-back-btn"
          size="small"
          @click="$emit('close')"
        >
          <el-icon class="back-icon"><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>

      <!-- 左侧车辆图片 -->
      <div class="vehicle-image">
        <img :src="carPic" alt="车辆图片" />
      </div>
      <!-- 右侧车辆信息 -->
      <div class="vehicle-info-panel">
        <div class="info-top-row">
          <img :src="carIcon" class="car-icon" />
        </div>
        <div class="info-bottom-row">
          <div class="info-title">{{ vehicle?.carId || "--" }}</div>
          <div class="info-status-row">
            <span class="status-item">
              <span class="status-label">作业状态：</span>
              <span class="dot status-signal"></span>
              <span class="status-value status-task">{{ routeStatus }}</span>
            </span>
            <span class="status-sep">|</span>
            <span class="status-item">
              <span class="dot status-signal"></span>
              <span class="status-label">车辆状态：</span>
              <span class="status-value status-online">{{ status }}</span>
            </span>
            <span class="status-sep">|</span>
            <span class="status-item">
              <span class="dot status-signal"></span>
              <span class="status-value">信号良好</span>
            </span>
            <span class="status-sep">|</span>
            <span class="status-item">
              <span class="dot status-battery"></span>
              <span class="status-value">电量充足</span>
            </span>
          </div>
          <div class="info-cards-row">
            <div class="info-card" v-for="item in cardList" :key="item.name">
              <div class="card-icon">
                <img :src="item.icon" />
              </div>
              <div class="card-content">
                <div class="card-title">{{ item.name }}</div>
                <div class="card-value">{{ item.value }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 下部分：标签页 -->
    <div class="detail-tabs">
      <!-- 分屏按钮只在视频监控tab下显示，保持绝对定位 -->
      <div v-if="activeTab === 'video'" class="split-btns">
        <el-tooltip content="单画面" placement="top">
          <img
            src="../../../assets/images/1btn.png"
            alt="单画面"
            @click.stop="layoutType = '1'"
          />
        </el-tooltip>
        <el-tooltip content="双画面" placement="top">
          <img
            src="../../../assets/images/2btn.png"
            alt="双画面"
            @click.stop="layoutType = '2'"
          />
        </el-tooltip>
        <el-tooltip content="六画面" placement="top">
          <img
            src="../../../assets/images/6btn.png"
            alt="六画面"
            @click.stop="layoutType = '6'"
          />
        </el-tooltip>
      </div>
      <el-tabs v-model="activeTab" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="电池概况" name="battery">
          <template #label>
            <span class="custom-tabs-label">
              <img src="../../../assets/images/tab1.png" alt="电池概况" />
              <span>电池概况</span>
            </span>
          </template>
          <BatteryOverview :vehicle="vehicle" />
        </el-tab-pane>
        <el-tab-pane label="故障报警" name="fault">
          <template #label>
            <span class="custom-tabs-label">
              <img src="../../../assets/images/tab2.png" alt="故障报警" />
              <span>故障报警</span>
            </span>
          </template>
          <FaultAlarm :vehicle="vehicle" :detail="detailData" />
        </el-tab-pane>
        <el-tab-pane label="轨迹回放" name="track">
          <template #label>
            <span class="custom-tabs-label">
              <img src="../../../assets/images/tab3.png" alt="轨迹回放" />
              <span>轨迹回放</span>
            </span>
          </template>
          <TrackPlayback :vehicle="vehicle" :detail="detailData" :tasks="tasksData" />
        </el-tab-pane>
        <el-tab-pane label="充放电统计" name="charging">
          <template #label>
            <span class="custom-tabs-label">
              <img src="../../../assets/images/tab4.png" alt="充放电统计" />
              <span>充放电统计</span>
            </span>
          </template>
          <ChargingStats :vehicle="vehicle" />
        </el-tab-pane>
        <el-tab-pane label="视频监控" name="video">
          <template #label>
            <span class="custom-tabs-label">
              <img src="../../../assets/images/tab5.png" alt="视频监控" />
              <span>视频监控</span>
            </span>
          </template>
          <VideoMonitoring :vehicle="vehicle" :layout-type="layoutType" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, onMounted, watch } from "vue";
import { ArrowLeft, Monitor, Grid } from "@element-plus/icons-vue";
import BatteryOverview from "../../../components/car/detail/BatteryOverview.vue";
import FaultAlarm from "../../../components/car/detail/FaultAlarm.vue";
import TrackPlayback from "../../../components/car/detail/TrackPlayback.vue";
import ChargingStats from "../../../components/car/detail/ChargingStats.vue";
import VideoMonitoring from "../../../components/car/detail/VideoMonitoring.vue";
import request from "@/utils/request";
import { getVehicleTasks } from "@/api/vehicle/manager";
import carPic from "../../../assets/images/car.png";
import carIcon from "../../../assets/images/carIcon.png";
import carIcon1 from "../../../assets/images/carIcon1.png";
import carIcon2 from "../../../assets/images/carIcon2.png";
import carIcon3 from "../../../assets/images/carIcon3.png";
import carIcon4 from "../../../assets/images/carIcon4.png";
import carIcon5 from "../../../assets/images/carIcon5.png";
// import phoneIcon from '../../../assets/images/phone.png';
const props = defineProps({
  vehicle: {
    type: Object,
    required: true,
  },
});
const activeTab = ref("battery");
const layoutType = ref("6");
const detailData = ref({});
const tasksData = ref([]);
const routeStatus = ref(props.vehicle?.routeStatus || "待命中");
const status = ref(props.vehicle?.status || "在线");
const detailFetching = ref(false);
const lastDetailId = ref(null);
async function fetchVehicleDetail(id) {
  if (!id) return;
  if (detailFetching.value) return;
  if (lastDetailId.value === id) return;
  detailFetching.value = true;
  try {
    const res = await request({
      url: `/api/vehicle-manager/vehicles/${encodeURIComponent(id)}`,
      method: "get",
    });
    const data = res && res.data !== undefined ? res.data : res || {};
    detailData.value = data;
    routeStatus.value = data?.order?.jobStageTag || props.vehicle?.routeStatus || routeStatus.value;
    status.value = data?.loginStatus?.login === "login" ? "在线" : (props.vehicle?.status || status.value);
    lastDetailId.value = id;
  } catch (e) {
    detailData.value = detailData.value || {};
    routeStatus.value = props.vehicle?.routeStatus || routeStatus.value;
    status.value = props.vehicle?.status || status.value;
  }
  detailFetching.value = false;
}
async function fetchVehicleTasks(id) {
  if (!id) {
    tasksData.value = [];
    return;
  }
  try {
    const res = await getVehicleTasks(id);
    const env = res && res.data !== undefined ? res.data : res || {};
    let list = [];
    const candidates = [env?.data, env?.rows, env?.list, env?.tasks, env];
    for (const c of candidates) {
      if (Array.isArray(c)) {
        list = c;
        break;
      }
    }
    if ((!list || list.length === 0) && Array.isArray(env?.waypoints)) {
      list = [{
        id,
        vehicleId: id,
        waypoints: env.waypoints,
        timestamp: env.timestamp
      }];
    }
    const mapped = (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) => {
        const ts = wp?.timestamp ?? wp?.time ?? wp?.ts ?? (t?.timestamp ?? 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 ?? id,
          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?.vehicleId ?? id)?.toString(),
        no: (t?.missionId ?? t?.id ?? id)?.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
      };
    });
    tasksData.value = mapped;
  } catch (e) {
    tasksData.value = [];
  }
}

onMounted(() => {
  routeStatus.value = props.vehicle?.routeStatus || routeStatus.value;
  status.value = props.vehicle?.status || status.value;
  fetchVehicleDetail(props.vehicle?.carId);
  fetchVehicleTasks(props.vehicle?.carId);
});
watch(
  () => props.vehicle?.carId,
  (id) => {
    fetchVehicleDetail(id);
    fetchVehicleTasks(id);
  }
);
const cardList = [
  { name: "驱动车", value: props.vehicle?.type || "--", icon: carIcon1 },
  { name: "比亚迪", value: props.vehicle?.brand || "--", icon: carIcon2 },
  {
    name: "物流建筑公司",
    value: props.vehicle?.organization || "--",
    icon: carIcon5,
  },
  {
    name: "张三",
    value: props.vehicle?.batteryLevel || "--",
    icon: carIcon4,
  },
  {
    name: props.vehicle?.contactPhone || "--",
    value: "负责人电话",
    icon: carIcon3,
  },
];
</script>

<style scoped lang="scss">
.vehicle-detail-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
}
.detail-header {
  display: flex;
  margin-bottom: 20px;
  border-radius: 8px;
  background-color: #292c38;
  padding: 24px;
  justify-content: flex-start;
  gap: 20px;
  align-items: center;
  position: relative;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 10;
}

/* 自定义返回按钮样式 */
.custom-back-btn {
  background-color: rgba(52, 122, 226, 0.2) !important;
  border-color: #347ae2 !important;
  color: #ffffff !important;
}

.custom-back-btn:hover {
  background-color: rgba(52, 122, 226, 0.3) !important;
}

.back-icon {
  margin-right: 4px;
}

.vehicle-image {
  width: 255px;
  height: 154px;
  border-radius: 8px;
  /* overflow: hidden; */
  background-color: #1e2233;
  display: flex;
  justify-content: center;
  align-items: center;
}
.vehicle-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.vehicle-info-panel {
  /* width: 60%; */
  flex: 1;
  display: flex;
  /* flex-direction: column; */
  justify-content: center;
}
.info-bottom-row {
  width: 100%;
}
.info-top-row {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* margin-bottom: 8px; */
  margin-top: 10px;
}
.car-icon {
  width: 48px;
  height: 48px;
  margin-right: 10px;
}
.info-title {
  font-size: 28px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 8px;
}
.info-status-row {
  display: flex;
  align-items: center;
  gap: 0;
  margin-bottom: 16px;
  font-size: 15px;
}
.status-item {
  display: flex;
  align-items: center;
}
.status-label {
  color: #b0b8c9;
  margin-right: 2px;
}
.status-value {
  /* font-weight: bold; */
  margin-right: 2px;
  color: #fff;
}
.status-task {
  color: #409eff;
}
.status-online {
  color: #00c48f;
}
.status-signal {
  background: #4ea1ff;
}
.status-battery {
  background: #00c48f;
}
.status-sep {
  color: #b0b8c9;
  margin: 0 12px;
  font-weight: normal;
  font-size: 15px;
}
.dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 4px;
  vertical-align: middle;
}
.info-cards-row {
  display: flex;
  gap: 10px;
}
.info-card {
  /* width: 100%; */
  display: flex;
  align-items: center;
  justify-content: center;
  background: #343744;
  border-radius: 8px;
  padding: 5px 10px;
}
.card-icon {
  width: 20px;
  height: 20px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.card-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.card-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.card-title {
  font-size: 14px;
  color: #b0b8c9;
  margin-bottom: 2px;
}
.card-value {
  font-size: 12px;
  color: #fff;
}
.detail-tabs {
  position: relative;
  flex: 1;
  padding: 12px 24px;
  background-color: #292c38;
  border-radius: 8px;
  min-height: 0;
  overflow: auto;
}
.split-btns {
  position: absolute;
  top: 0px;
  right: 32px;
  transform: translateY(80%);
  z-index: 10;
  display: flex;
  gap: 8px;
}
.custom-tabs-label {
  display: flex;
  align-items: center;
  gap: 4px;
  
}
.custom-tabs-label img {
    width: 16px;
    height: 16px;
    filter: brightness(0) invert(1); /* 默认将图标变为白色 */
  }
:deep(.el-tabs) {
  --el-tabs-header-background-color: #1e2233;
  --el-tabs-border-color: #303850;
}
:deep(.el-tabs__header) {
  margin-bottom: 20px;
  border-bottom: none;
}
:deep(.el-tabs__item) {
  color: #f0f0f0;
}
:deep(.el-tabs__item.is-active) {
  color: #409eff;
  
  .custom-tabs-label img {
    filter: brightness(0) saturate(100%) invert(46%) sepia(85%) saturate(1731%) hue-rotate(199deg) brightness(100%) contrast(101%); /* 选中时图标变为蓝色 #409eff */
  }
}
:deep .el-tabs__nav-wrap::after {
  height: 1px;
  background-color: #4c4f5f;
}
@media (max-width: 992px) {
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .vehicle-image {
    margin-right: 0;
    margin-bottom: 16px;
  }
  .info-cards-row {
    flex-wrap: wrap;
  }
}
</style>
