<template>
  <div class="shop-distribution-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">🗺️ 门店分布地图</h2>
        <el-tag type="success" effect="dark" size="large">
          已显示 {{ shopList.length }} 个门店
        </el-tag>
      </div>
      <div class="header-right">
        <el-input
          v-model="searchAddress"
          placeholder="请输入地址搜索"
          clearable
          style="width: 300px"
          @keyup.enter="handleAddressSearch"
        >
          <template #append>
            <el-button @click="handleAddressSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 地图容器 - 占满剩余空间 -->
    <div class="map-container">
      <AmapWithSearch
        ref="mapComponentRef"
        :longitude="centerLongitude"
        :latitude="centerLatitude"
        height="calc(100vh - 200px)"
        :zoom="12"
        :enable-click-mark="false"
        :show-search="false"
        :initial-marker="false"
      />
      
      <!-- 门店信息浮层 -->
      <div v-if="selectedShop" class="shop-info-panel" :style="infoPanelStyle">
        <div class="panel-header">
          <h3>{{ selectedShop.name }}</h3>
        </div>
        <div class="panel-content">
          <p><strong>📍 地址：</strong>{{ selectedShop.province }}{{ selectedShop.city }}{{ selectedShop.district }}{{ selectedShop.address }}</p>
          <p><strong>🔢 坐标：</strong>经度 {{ selectedShop.longitude }}, 纬度 {{ selectedShop.latitude }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { AmapWithSearch } from '@/components/AmapWithSearch';
import { getShopList } from '@/api/shop';
import { Search } from '@element-plus/icons-vue';

// 高德地图全局对象
let AMap: any = null;

// 地图组件引用
const mapComponentRef = ref<any>(null);

// 门店数据
const shopList = ref<any[]>([]);
const loading = ref(false);
const searchAddress = ref('');

// 地图中心点（默认深圳）
const centerLongitude = ref(114.057868);
const centerLatitude = ref(22.677079);

// 当前选中的门店
const selectedShop = ref<any>(null);
// 标记点位置（用于计算信息面板位置）
const markerPosition = ref<{ lng: number; lat: number } | null>(null);

// 加载门店列表并在地图上标记
const loadShopList = async () => {
  loading.value = true;
  try {
    const res = await getShopList({ page: 1, pageSize: 100 });
    console.log('门店列表 API 响应:', JSON.stringify(res));
    
    if (res.code === 200 || res.code === 0) {
      shopList.value = res.data?.list || [];
      console.log('加载门店列表成功，数量:', shopList.value.length);
      
      // 设置地图中心点
      if (shopList.value.length > 0 && shopList.value[0].longitude && shopList.value[0].latitude) {
        centerLongitude.value = Number(shopList.value[0].longitude);
        centerLatitude.value = Number(shopList.value[0].latitude);
      }
      
      // 门店列表加载成功后，延迟添加标记点（等待地图初始化）
      setTimeout(() => {
        addShopMarkers();
      }, 1500);
    } else {
      console.warn('门店列表 API 返回异常 code:', res.code, 'message:', res.message);
    }
  } catch (error) {
    console.error('加载门店列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取 AMap 实例（从全局 window 对象）
const getAMapInstance = () => {
  if (!AMap && (window as any).AMap) {
    AMap = (window as any).AMap;
  }
  return AMap;
};

// 在地图上添加所有门店的标记
const addShopMarkers = async () => {
  if (!mapComponentRef.value) {
    console.error('地图组件未初始化');
    return;
  }

  // 等待地图实例初始化
  await nextTick();

  console.log('[addShopMarkers] 开始添加门店标记...');
  
  const mapInstance = mapComponentRef.value;
  
  shopList.value.forEach((shop, index) => {
    if (shop.longitude && shop.latitude) {
      const lng = Number(shop.longitude);
      const lat = Number(shop.latitude);
      
      console.log(`添加门店标记 ${index + 1}:`, shop.name, lng, lat);
      
      // 使用组件暴露的 addCustomMarker 方法添加带悬停事件的红色标记
      if (typeof mapInstance.addCustomMarker === 'function') {
        const result = mapInstance.addCustomMarker(lng, lat, shop.name, {
          // 鼠标移入显示信息面板
          onMouseEnter: () => {
            console.log('鼠标移入门店标记:', shop.name);
            selectedShop.value = shop;
            markerPosition.value = { lng, lat };
            
            // 获取像素坐标并更新面板位置
            if (typeof mapInstance.lngLatToPixel === 'function') {
              const pixel = mapInstance.lngLatToPixel(lng, lat);
              if (pixel) {
                panelPixelPosition.value = pixel;
              }
            }
          },
          // 鼠标移出隐藏信息面板
          onMouseLeave: () => {
            console.log('鼠标移出门店标记:', shop.name);
            selectedShop.value = null;
            markerPosition.value = null;
            panelPixelPosition.value = null;
          }
        }, 'red'); // 使用红色标记
        
        if (result) {
          console.log(`[addShopMarkers] 标记点 ${shop.name} 添加成功`);
        } else {
          console.error(`[addShopMarkers] 标记点 ${shop.name} 添加失败`);
        }
      } else {
        console.error('[addShopMarkers] addCustomMarker 方法不存在');
      }
    } else {
      console.warn(`门店 ${shop.name} 没有有效的经纬度`);
    }
  });
  
  console.log('[addShopMarkers] 门店标记添加完成');
};

// 处理地址搜索
const handleAddressSearch = async () => {
  if (!searchAddress.value.trim()) {
    return;
  }
  
  if (mapComponentRef.value && typeof mapComponentRef.value.searchAddress === 'function') {
    await mapComponentRef.value.searchAddress(searchAddress.value);
  }
};

// 面板像素位置
const panelPixelPosition = ref<{ x: number; y: number } | null>(null);

// 计算信息面板样式（显示在标记点旁边）
const infoPanelStyle = computed(() => {
  if (!panelPixelPosition.value) {
    return {
      display: 'none'
    };
  }
  
  const { x, y } = panelPixelPosition.value;
  
  return {
    position: 'absolute' as const,
    left: `${x + 30}px`, // 标记点右侧 30px
    top: `${y - 60}px`, // 标记点上方 60px
    maxWidth: '320px',
    zIndex: 1000
  };
});

// 初始化加载门店列表
onMounted(() => {
  loadShopList();
});
</script>

<style scoped>
.shop-distribution-page {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 占满整个视口高度 */
  overflow: hidden;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0; /* 不压缩头部 */
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.map-container {
  flex: 1; /* 占满剩余空间 */
  position: relative;
  background: white;
  overflow: hidden;
  min-height: 500px; /* 确保最小高度 */
}

.shop-info-panel {
  position: absolute;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 280px;
  max-width: 350px;
  border: 1px solid #e4e7ed;
}

/* 左侧小箭头 */
.shop-info-panel::before {
  content: '';
  position: absolute;
  left: -10px;
  top: 50px;
  border-width: 10px;
  border-style: solid;
  border-color: transparent white transparent transparent;
}

.shop-info-panel::after {
  content: '';
  position: absolute;
  left: -11px;
  top: 49px;
  border-width: 11px;
  border-style: solid;
  border-color: transparent #e4e7ed transparent transparent;
  z-index: -1;
}

.panel-header {
  padding: 10px 14px;
  border-bottom: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px 8px 0 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 15px;
  color: white;
  font-weight: 600;
}

.panel-content {
  padding: 16px;
}

.panel-content p {
  margin: 8px 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
}

.panel-content strong {
  color: #303133;
  font-weight: 600;
}
</style>