<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"
      />
      
      <!-- 门店信息浮层 -->
      <div v-if="selectedShop" class="shop-info-panel" :style="infoPanelStyle">
        <div class="panel-header">
          <h3>{{ selectedShop.name }}</h3>
          <el-button type="info" size="small" circle @click="closeShopInfo">✕</el-button>
        </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);
      }
    } 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, () => {
          console.log('点击门店标记:', shop.name);
          // 设置选中的门店并计算面板位置
          selectedShop.value = shop;
          markerPosition.value = { lng, lat };
        }, '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 closeShopInfo = () => {
  selectedShop.value = null;
  markerPosition.value = null;
};

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

// 计算信息面板样式（显示在标记点右上方）
const infoPanelStyle = computed(() => {
  // 简单方案：始终显示在地图容器的右上角
  // 这样更稳定，不受地图缩放和移动影响
  return {
    position: 'absolute' as const,
    top: '20px',
    right: '20px',
    maxWidth: '320px',
    zIndex: 1000
  };
});

// 初始化加载门店列表
onMounted(() => {
  loadShopList();
  // 等待地图组件初始化完成后再添加标记
  setTimeout(() => {
    addShopMarkers();
  }, 1000); // 延迟 1 秒确保地图已初始化
});
</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;
  top: 20px;
  right: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 300px;
  max-width: 400px;
  border: 1px solid #e4e7ed;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  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>