<template>
  <div class="zoom-control" ref="zoomControlRef">
    <div class="settings-control" :class="{ active: showSettingsPanel }" @click.stop="toggleSettingsPanel">
      <svg class="settings-icon" width="18" height="18" viewBox="0 0 24 24" fill="none">
        <path
          d="M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Z"
          stroke="currentColor"
          stroke-width="2"
        />
        <path
          d="M19.4 15a8.2 8.2 0 0 0 .1-1 8.2 8.2 0 0 0-.1-1l2-1.6-1.9-3.3-2.4 1a7.9 7.9 0 0 0-1.7-1l-.4-2.6H9l-.4 2.6a7.9 7.9 0 0 0-1.7 1l-2.4-1-1.9 3.3 2 1.6a8.2 8.2 0 0 0-.1 1 8.2 8.2 0 0 0 .1 1l-2 1.6 1.9 3.3 2.4-1c.5.4 1.1.7 1.7 1l.4 2.6h6.2l.4-2.6c.6-.3 1.2-.6 1.7-1l2.4 1 1.9-3.3-2-1.6Z"
          stroke="currentColor"
          stroke-width="2"
          stroke-linejoin="round"
        />
      </svg>
    </div>

    <div class="settings-panel" v-if="showSettingsPanel" @click.stop>
      <div class="settings-item" @click="openVehicleEdit">编辑</div>
      <div class="settings-item" @click="openWarningDistance">修改预警距离</div>
      <div class="settings-item" @click="openRouteModify">查询路由</div>
      <div class="settings-item" @click="drawTestRoute">绘制测试路由</div>
      <div class="settings-item settings-switch-item" @click.stop>
        <span>路径冲突显示</span>
        <el-switch v-model="pathConflictDisplayEnabled" size="small" />
      </div>
    </div>

    <VehicleRunningEditDialog :visible="showVehicleEditDialog" @close="showVehicleEditDialog = false" />
    <WarningDistanceDialog
      :visible="showWarningDistanceDialog"
      @close="showWarningDistanceDialog = false"
      @confirm="handleWarningDistanceConfirm"
    />
    <RouteModifyDialog 
      :visible="showRouteModifyDialog" 
      @close="showRouteModifyDialog = false" 
      @confirm="handleRouteModifyConfirm"
    />

    <LayerSwitcher
      class="layer-switcher"
      :map="map"
      :categories="vehicleCategories"
      @layerChange="onLayerChange"
      @setCategoryVisibility="handleSetCategoryVisibility"
      ref="layerSwitcherRef"
    />

    <div
      class="compass-container"
      :style="{ transform: `rotate(${-rotation}deg)` }"
    >
      <div class="rotate-left" @click="rotateLeft" title="向右旋转90°"></div>
  
      <div class="rotate-right" @click="rotateRight" title="向左旋转90°"></div>
    </div>
    <div class="zoom-in" @click="onZoomIn"></div>
    <div class="zoom-out" @click="onZoomOut"></div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, watch } from "vue";
import { ElMessage } from "element-plus";
import useSettingsStore from '@/store/modules/settings';
import LayerSwitcher from "./LayerSwitcher.vue";
import VehicleRunningEditDialog from "./VehicleRunningEditDialog.vue";
import WarningDistanceDialog from "./WarningDistanceDialog.vue";
import RouteModifyDialog from "./RouteModifyDialog.vue";
import { updateDivergingReleaseDistance, updateRunwayAlertRadius } from "@/api/platform/runtimeConfig";
import { queryAircraftRoute } from "@/api/platform/aircraftRoute";

// 导入图片资源
import leftArrowActiveImg from "../../../assets/images/left_arrow_active.png";
import rightArrowActiveImg from "../../../assets/images/right_arrow_active.png";
import zoomInActiveImg from "../../../assets/images/zoomInActive.png";
import zoomOutActiveImg from "../../../assets/images/zoomOutActive.png";
import layerActiveImg from "../../../assets/images/layerActive.png";

[leftArrowActiveImg, rightArrowActiveImg, zoomInActiveImg, zoomOutActiveImg, layerActiveImg].forEach(src => {
  const img = new window.Image();
  img.src = src;
});
// 定义props接受地图实例
const props = defineProps({
  map: Object, // 地图实例
  resetView: {
    type: Function,
    default: null,
  },
  vehicleCategories: {
    type: Object,
    default: () => ({})
  },
  vehicleMovementControl: {
    type: Object,
    default: null
  }
});

// 组件引用
const layerSwitcherRef = ref(null);
const zoomControlRef = ref(null);
const showSettingsPanel = ref(false);
const showVehicleEditDialog = ref(false);
const showWarningDistanceDialog = ref(false);
const showRouteModifyDialog = ref(false);
const settingsStore = useSettingsStore();

const pathConflictDisplayEnabled = computed({
  get: () => settingsStore.pathConflictDisplayEnabled !== false,
  set: (val) => {
    settingsStore.changeSetting({ key: 'pathConflictDisplayEnabled', value: val });
    const layoutSetting = JSON.parse(localStorage.getItem('layout-setting')) || {};
    localStorage.setItem('layout-setting', JSON.stringify({
      ...layoutSetting,
      pathConflictDisplayEnabled: val
    }));
  }
});

// 地图旋转角度 (弧度转换为度)
const rotation = ref(0);

// 向父组件发出事件
const emit = defineEmits([
  "compass",
  "zoomIn",
  "zoomOut",
  "layerChange",
  "rotate",
  "setCategoryVisibility",
  "drawTestRoute",
  "routeQueried"
]);

// 监听地图视图变化，更新旋转角度
function updateRotation() {
  if (props.map && props.map.getView()) {
    // OpenLayers中旋转角度是弧度，转换为度
    rotation.value = (props.map.getView().getRotation() * 180) / Math.PI;
  }
}

// 重置地图旋转
function resetRotation() {
  if (props.map) {
    // 重置旋转为0
    props.map.getView().animate({
      rotation: 0,
      duration: 300,
    });
    emit("rotate", 0);
  }
}

// 向左旋转地图（逆时针）
function rotateLeft() {
  if (props.map) {
    const currentRotation = props.map.getView().getRotation();
    const newRotation = currentRotation - Math.PI / 2; // 旋转90度（逆时针）
    props.map.getView().animate({
      rotation: newRotation,
      duration: 300,
    });
    emit("rotate", (newRotation * 180) / Math.PI);
  }
}

// 向右旋转地图（顺时针）
function rotateRight() {
  if (props.map) {
    const currentRotation = props.map.getView().getRotation();
    const newRotation = currentRotation + Math.PI / 2; // 旋转90度（顺时针）
    props.map.getView().animate({
      rotation: newRotation,
      duration: 300,
    });
    emit("rotate", (newRotation * 180) / Math.PI);
  }
}


// 放大地图
function onZoomIn() {
  emit("zoomIn");
  if (props.map) {
    const view = props.map.getView();
    const targetZoom = view.getConstrainedZoom(view.getZoom() + 1);
    view.animate({
      zoom: targetZoom,
      duration: 250,
    });
  }
}

// 缩小地图
function onZoomOut() {
  emit("zoomOut");
  if (props.map) {
    const view = props.map.getView();
    const targetZoom = view.getConstrainedZoom(view.getZoom() - 1);
    view.animate({
      zoom: targetZoom,
      duration: 250,
    });
  }
}

// 图层变化处理
function onLayerChange(layerInfo) {
  console.log("ZoomControl收到图层变化:", layerInfo);
  // 将图层信息传递给父组件
  emit("layerChange", layerInfo);
}

// 处理分类可见性设置
function handleSetCategoryVisibility(type, settings) {
  // 发送到父组件
  emit('setCategoryVisibility', type, settings);
  
  // 如果props中有vehicleMovementControl，直接调用其方法
  if (props.vehicleMovementControl && props.vehicleMovementControl.setCategoryVisibility) {
    props.vehicleMovementControl.setCategoryVisibility(type, settings);
  }
}

function toggleSettingsPanel() {
  showSettingsPanel.value = !showSettingsPanel.value;
}

function openVehicleEdit() {
  showSettingsPanel.value = false;
  showVehicleEditDialog.value = true;
}

function openWarningDistance() {
  showSettingsPanel.value = false;
  showWarningDistanceDialog.value = true;
}

function openRouteModify() {
  showSettingsPanel.value = false;
  showRouteModifyDialog.value = true;
}

function drawTestRoute() {
  showSettingsPanel.value = false;
  emit('drawTestRoute');
}

async function handleRouteModifyConfirm(payload) {
  try {
    const res = await queryAircraftRoute(payload);
    if (res.code === 200 && res.data) {
      ElMessage.success('路由查询成功，已在地图上绘制');
      // 直接触发全局路由更新事件或调用传入的 vehicleMovementControl 方法
      const bindId =
        payload?.objectId ||
        payload?.vehicleID ||
        payload?.flightNo ||
        payload?.objectName ||
        res?.data?.flightNo ||
        res?.data?.objectId ||
        res?.data?.vehicleID ||
        res?.data?.objectName ||
        res?.data?.routeCodes ||
        'QUERY-ROUTE'
      const routePayload = {
        flightNo: bindId,
        routeType: payload.routeType,
        routeStatus: res.data.routeStatus || 'ACTIVE',
        routeGeometry:
          res.data.geoPath ||
          res.data.featureCollection ||
          res.data.geojson ||
          res.data.routeGeometry ||
          res.data.featureLayer,
        routeCodes: res.data.routeCodes || res.data.codes
      };
      
      if (props.vehicleMovementControl && typeof props.vehicleMovementControl.handleAircraftRouteUpdate === 'function') {
        props.vehicleMovementControl.handleAircraftRouteUpdate(routePayload);
      } else if (window.__injectAircraftRouteUpdate) {
        window.__injectAircraftRouteUpdate(routePayload);
      } else {
        // 如果没有直接方法，通过 emit 抛给父组件
        emit('routeQueried', routePayload);
      }
    } else {
      ElMessage.warning(res.msg || '查询路由失败');
    }
  } catch (error) {
    console.error('查询路由出错:', error);
    ElMessage.error(error.message || '查询路由出错');
  }
}

async function handleWarningDistanceConfirm(payload) {
  const vehicleDistance = Number(payload?.vehicleDistance)
  const aircraftDistance = Number(payload?.aircraftDistance)
  const separationDistance = Number(payload?.separationDistance)

  const hasVehicleDistance = Number.isFinite(vehicleDistance) && vehicleDistance > 0
  const hasAircraftDistance = Number.isFinite(aircraftDistance) && aircraftDistance > 0
  const hasSeparationDistance = Number.isFinite(separationDistance) && separationDistance > 0

  if (!hasVehicleDistance && !hasAircraftDistance && !hasSeparationDistance) {
    ElMessage.error('请至少填写一项有效配置（大于 0 的数字）')
    return
  }

  try {
    const tasks = []
    if (hasVehicleDistance || hasAircraftDistance) {
      const next = {}
      if (hasVehicleDistance) next.vehicleDistance = vehicleDistance
      if (hasAircraftDistance) next.aircraftDistance = aircraftDistance
      tasks.push(updateDivergingReleaseDistance(next))
    }
    if (hasSeparationDistance) {
      tasks.push(updateRunwayAlertRadius(separationDistance))
    }
    await Promise.all(tasks)
    ElMessage.success('配置已更新')
    showWarningDistanceDialog.value = false
  } catch (e) {
    ElMessage.error(e?.message || '配置更新失败')
  }
}

function handleDocumentClick(event) {
  const el = zoomControlRef.value;
  if (!el) return;
  if (el.contains(event.target)) return;
  showSettingsPanel.value = false;
}

// 监听地图旋转事件
let rotationListener = null;

onMounted(() => {
  document.addEventListener('click', handleDocumentClick);
  if (props.map) {
    // 初始化旋转角度
    updateRotation();

    // 添加视图变化监听器 - 使用on方法返回的事件键
    rotationListener = props.map
      .getView()
      .on("change:rotation", updateRotation);
  }
});

onUnmounted(() => {
  document.removeEventListener('click', handleDocumentClick);
  // 移除监听器 - 使用OpenLayers的事件解绑方式
  if (rotationListener && props.map) {
    try {
      // 正确方式是使用unByKey方法解绑事件
      import('ol/Observable').then(({ unByKey }) => {
        unByKey(rotationListener);
      }).catch(e => {
        console.error('清理事件监听器失败:', e);
      });
    } catch (e) {
      console.error('清理事件监听器失败:', e);
    }
  }
});

// 监听地图实例变化
watch(
  () => props.map,
  (newMap) => {
    if (newMap) {
      // 初始化旋转角度
      updateRotation();

      // 移除旧的监听器
      if (rotationListener) {
        try {
          import('ol/Observable').then(({ unByKey }) => {
            unByKey(rotationListener);
          }).catch(e => {
            console.error('清理事件监听器失败:', e);
          });
        } catch (e) {
          console.error('清理事件监听器失败:', e);
        }
      }

      // 添加新的视图变化监听器
      rotationListener = newMap.getView().on("change:rotation", updateRotation);
    }
  }
);

// 导出方法供外部调用
defineExpose({
  // 设置图层可见性的方法
  setLayerVisibility(layerName, visible) {
    if (layerSwitcherRef.value) {
      return layerSwitcherRef.value.setLayerVisibility(layerName, visible);
    }
    return false;
  },
  // 重置旋转
  resetRotation,
  // 获取当前旋转角度
  getRotation() {
    return rotation.value;
  },
});
</script>

<style scoped>
.zoom-control {
  position: absolute;
  bottom: 220px;
  left: 20px;
  z-index: 3000;
  width: 40px;
  height: auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 25px;
}

.settings-control {
  z-index: 3000;
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.95);
  background: rgba(66, 72, 81, 0.9);
  border: 1px solid rgba(48, 56, 80, 0.9);
}

.settings-control:hover,
.settings-control.active {
  background: rgba(66, 72, 81, 1);
  border-color: rgba(0, 150, 255, 0.85);
}

.settings-icon {
  display: block;
}

.settings-panel {
  position: absolute;
  left: 50px;
  top: 0;
  width: 220px;
  background-color: #424851;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
  z-index: 3100;
  overflow: hidden;
  color: #ffffff;
  border: 1px solid #303850;
}

.settings-item {
  height: 40px;
  line-height: 40px;
  padding: 0 14px;
  cursor: pointer;
  font-size: 14px;
  border-bottom: 1px solid rgba(48, 56, 80, 0.9);
}

.settings-item:last-child {
  border-bottom: none;
}

.settings-item:hover {
  background: rgba(0, 150, 255, 0.12);
}

.settings-switch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.settings-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.compass-container {
  position: relative;
  width: 40px;
  height: 40px;
  cursor: pointer;
  background: url("../../../assets/images/znzBg.png") no-repeat;
  background-size: 100% 100%;
}

.rotation-controls {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 3002;
}

.rotate-left,
.rotate-right {
  width: 24px;
  height: 24px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

.rotate-left {
  left: -3px;
  background: url("../../../assets/images/left_arrow.png") no-repeat;
  background-size: 100% 100%;
  z-index: 5000;
}

.rotate-right {
  right: -3px;
  background: url("../../../assets/images/right_arrow.png") no-repeat;
  background-size: 100% 100%;
}

.rotate-left:hover,
.rotate-left:active {
  left: -3px;
  background: url("../../../assets/images/left_arrow_active.png") no-repeat;
  background-size: 100% 100%;
}
.rotate-right:hover,
.rotate-right:active {
  right: -3px;
  background: url("../../../assets/images/right_arrow_active.png") no-repeat;
  background-size: 100% 100%;
}

.layer-switcher {
  z-index: 3000;
  width: 40px;
  height: 40px;
  background: url("../../../assets/images/layer.png") no-repeat;
  background-size: 100% 100%;
  cursor: pointer;
}
.layer-switcher:hover,
.layer-switcher.active {
  background: url("../../../assets/images/layerActive.png") no-repeat;
  background-size: 100% 100%;
  opacity: 1; /* 确保不透明度为1 */
}

.zoom-in {
  background: url("../../../assets/images/zoomOut.png") no-repeat;
  background-size: 100% 100%;
  z-index: 3000;
  width: 40px;
  height: 40px;
  cursor: pointer;
}
.zoom-in:hover,
.zoom-in.active {
  background: url("../../../assets/images/zoomOutActive.png") no-repeat;
  background-size: 100% 100%;
}

.zoom-out {
  background: url("../../../assets/images/zoomIn.png") no-repeat;
  background-size: 100% 100%;
  z-index: 3000;
  width: 40px;
  height: 40px;
  cursor: pointer;
}
.zoom-out:hover,
.zoom-out.active {
  background: url("../../../assets/images/zoomInActive.png") no-repeat;
  background-size: 100% 100%;
}


/* 响应式调整 */
@media (max-width: 768px) {
  .zoom-in,
  .zoom-out,
  .compass-container,
  .compass-bg,
  .compass-needle {
    width: 28px;
    height: 28px;
  }

  .zoom-in,
  .zoom-out {
    background-size: 80%;
    background-position: center center;
    background-repeat: no-repeat;
  }

  .rotate-left,
  .rotate-right {
    width: 18px;
    height: 18px;
  }

  .rotate-left {
    left: -18px;
  }

  .rotate-right {
    right: -18px;
  }
}
</style>
