<template>
  <view class="map-container">
    <!-- 地图组件 -->
    <map
      :id="mapId"
      class="map-view"
      :style="{ width: width + 'rpx', height: height + 'rpx' }"
      :longitude="center.longitude"
      :latitude="center.latitude"
      :scale="scale"
      :markers="mapMarkers"
      :polyline="polylines"
      :polygons="polygons"
      :circles="circles"
      :controls="controls"
      :include-points="includePoints"
      :show-location="showLocation"
      :enable-3D="enable3D"
      :show-compass="showCompass"
      :enable-overlooking="enableOverlooking"
      :enable-zoom="enableZoom"
      :enable-scroll="enableScroll"
      :enable-rotate="enableRotate"
      :enable-satellite="enableSatellite"
      :enable-traffic="enableTraffic"
      @markertap="handleMarkerTap"
      @labeltap="handleLabelTap"
      @callouttap="handleCalloutTap"
      @controltap="handleControlTap"
      @regionchange="handleRegionChange"
      @tap="handleMapTap"
      @updated="handleMapUpdated"
      @poitap="handlePoiTap"
    />
    
    <!-- 地图工具栏 -->
    <view class="map-toolbar" v-if="showToolbar">
      <!-- 定位按钮 -->
      <button
        class="toolbar-btn location-btn"
        @click="handleLocationClick"
        v-if="showLocationButton"
      >
        <text class="btn-icon">📍</text>
      </button>
      
      <!-- 缩放控制 -->
      <view class="zoom-controls" v-if="showZoomControls">
        <button class="toolbar-btn zoom-btn" @click="handleZoomIn">
          <text class="btn-icon">+</text>
        </button>
        <button class="toolbar-btn zoom-btn" @click="handleZoomOut">
          <text class="btn-icon">-</text>
        </button>
      </view>
      
      <!-- 图层切换 -->
      <button
        class="toolbar-btn layer-btn"
        @click="handleLayerToggle"
        v-if="showLayerButton"
      >
        <text class="btn-icon">🗺️</text>
      </button>
      
      <!-- 路线规划 -->
      <button
        class="toolbar-btn route-btn"
        @click="handleRouteClick"
        v-if="showRouteButton"
      >
        <text class="btn-icon">🚗</text>
      </button>
    </view>
    
    <!-- 搜索框 -->
    <view class="map-search" v-if="showSearch">
      <Search
        v-model="searchKeyword"
        placeholder="搜索地点"
        @search="handleSearch"
        @clear="handleSearchClear"
      />
      
      <!-- 搜索结果 -->
      <view class="search-results" v-if="searchResults.length">
        <view
          class="search-item"
          v-for="(item, index) in searchResults"
          :key="index"
          @click="handleSearchItemClick(item)"
        >
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-address">{{ item.address }}</text>
          </view>
          <text class="item-distance" v-if="item.distance">
            {{ item.distance }}km
          </text>
        </view>
      </view>
    </view>
    
    <!-- 信息窗口 -->
    <view class="info-window" v-if="showInfoWindow" :style="infoWindowStyle">
      <view class="info-content">
        <view class="info-header">
          <text class="info-title">{{ infoData.title }}</text>
          <button class="info-close" @click="handleInfoClose">✕</button>
        </view>
        
        <view class="info-body">
          <text class="info-address" v-if="infoData.address">
            📍 {{ infoData.address }}
          </text>
          <text class="info-phone" v-if="infoData.phone">
            📞 {{ infoData.phone }}
          </text>
          <text class="info-description" v-if="infoData.description">
            {{ infoData.description }}
          </text>
        </view>
        
        <view class="info-actions" v-if="infoData.actions">
          <button
            class="info-btn"
            v-for="action in infoData.actions"
            :key="action.type"
            @click="handleInfoAction(action)"
          >
            {{ action.text }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 路线面板 -->
    <view class="route-panel" v-if="showRoutePanel">
      <view class="panel-header">
        <text class="panel-title">路线规划</text>
        <button class="panel-close" @click="handleRoutePanelClose">✕</button>
      </view>
      
      <view class="route-form">
        <view class="route-item">
          <text class="route-label">起点</text>
          <input
            class="route-input"
            v-model="routeForm.start"
            placeholder="请输入起点"
          />
        </view>
        
        <view class="route-item">
          <text class="route-label">终点</text>
          <input
            class="route-input"
            v-model="routeForm.end"
            placeholder="请输入终点"
          />
        </view>
        
        <view class="route-options">
          <button
            class="route-option"
            :class="{ active: routeForm.mode === 'driving' }"
            @click="handleRouteModeChange('driving')"
          >
            🚗 驾车
          </button>
          <button
            class="route-option"
            :class="{ active: routeForm.mode === 'walking' }"
            @click="handleRouteModeChange('walking')"
          >
            🚶 步行
          </button>
          <button
            class="route-option"
            :class="{ active: routeForm.mode === 'transit' }"
            @click="handleRouteModeChange('transit')"
          >
            🚌 公交
          </button>
        </view>
        
        <button class="route-search-btn" @click="handleRouteSearch">
          搜索路线
        </button>
      </view>
      
      <!-- 路线结果 -->
      <view class="route-results" v-if="routeResults.length">
        <view
          class="route-result-item"
          v-for="(route, index) in routeResults"
          :key="index"
          @click="handleRouteSelect(route)"
        >
          <view class="route-info">
            <text class="route-distance">{{ route.distance }}</text>
            <text class="route-duration">{{ route.duration }}</text>
          </view>
          <text class="route-description">{{ route.description }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import Search from '@/common/components/search/search.vue'

export default {
  name: 'Map',
  components: {
    Search
  },
  props: {
    // 地图中心点
    center: {
      type: Object,
      default: () => ({
        longitude: 116.397428,
        latitude: 39.90923
      })
    },
    // 缩放级别
    scale: {
      type: Number,
      default: 16
    },
    // 地图尺寸
    width: {
      type: Number,
      default: 750
    },
    height: {
      type: Number,
      default: 600
    },
    // 标记点
    markers: {
      type: Array,
      default: () => []
    },
    // 路线
    polylines: {
      type: Array,
      default: () => []
    },
    // 多边形
    polygons: {
      type: Array,
      default: () => []
    },
    // 圆形
    circles: {
      type: Array,
      default: () => []
    },
    // 是否显示当前位置
    showLocation: {
      type: Boolean,
      default: true
    },
    // 是否启用3D
    enable3D: {
      type: Boolean,
      default: false
    },
    // 是否显示指南针
    showCompass: {
      type: Boolean,
      default: true
    },
    // 是否启用俯视
    enableOverlooking: {
      type: Boolean,
      default: true
    },
    // 是否启用缩放
    enableZoom: {
      type: Boolean,
      default: true
    },
    // 是否启用滚动
    enableScroll: {
      type: Boolean,
      default: true
    },
    // 是否启用旋转
    enableRotate: {
      type: Boolean,
      default: true
    },
    // 是否启用卫星图
    enableSatellite: {
      type: Boolean,
      default: false
    },
    // 是否启用路况
    enableTraffic: {
      type: Boolean,
      default: false
    },
    // 是否显示工具栏
    showToolbar: {
      type: Boolean,
      default: true
    },
    // 是否显示定位按钮
    showLocationButton: {
      type: Boolean,
      default: true
    },
    // 是否显示缩放控制
    showZoomControls: {
      type: Boolean,
      default: true
    },
    // 是否显示图层按钮
    showLayerButton: {
      type: Boolean,
      default: true
    },
    // 是否显示路线按钮
    showRouteButton: {
      type: Boolean,
      default: true
    },
    // 是否显示搜索
    showSearch: {
      type: Boolean,
      default: true
    }
  },
  emits: [
    'markerTap', 'labelTap', 'calloutTap', 'controlTap',
    'regionChange', 'mapTap', 'updated', 'poiTap',
    'locationClick', 'routeSelect'
  ],
  setup(props, { emit }) {
    const mapId = `map-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    const mapContext = ref(null)
    
    // 响应式数据
    const searchKeyword = ref('')
    const searchResults = ref([])
    const showInfoWindow = ref(false)
    const infoData = ref({})
    const infoWindowStyle = ref({})
    const showRoutePanel = ref(false)
    const routeResults = ref([])
    
    // 路线表单
    const routeForm = reactive({
      start: '',
      end: '',
      mode: 'driving'
    })
    
    // 计算属性
    const mapMarkers = computed(() => {
      return props.markers.map((marker, index) => ({
        id: marker.id || index,
        longitude: marker.longitude,
        latitude: marker.latitude,
        title: marker.title || '',
        iconPath: marker.iconPath || '/static/images/marker.png',
        width: marker.width || 30,
        height: marker.height || 30,
        callout: marker.callout || null,
        label: marker.label || null,
        anchor: marker.anchor || { x: 0.5, y: 1 },
        ...marker
      }))
    })
    
    const controls = computed(() => [
      // 可以添加自定义控件
    ])
    
    const includePoints = computed(() => {
      if (props.markers.length === 0) return []
      
      return props.markers.map(marker => ({
        longitude: marker.longitude,
        latitude: marker.latitude
      }))
    })
    
    // 方法
    const initMapContext = () => {
      mapContext.value = uni.createMapContext(mapId)
    }
    
    const handleMarkerTap = (e) => {
      const markerId = e.detail.markerId
      const marker = props.markers.find(m => m.id === markerId)
      
      if (marker && marker.showInfo) {
        showMarkerInfo(marker, e.detail)
      }
      
      emit('markerTap', e)
    }
    
    const handleLabelTap = (e) => {
      emit('labelTap', e)
    }
    
    const handleCalloutTap = (e) => {
      emit('calloutTap', e)
    }
    
    const handleControlTap = (e) => {
      emit('controlTap', e)
    }
    
    const handleRegionChange = (e) => {
      emit('regionChange', e)
    }
    
    const handleMapTap = (e) => {
      hideInfoWindow()
      emit('mapTap', e)
    }
    
    const handleMapUpdated = (e) => {
      emit('updated', e)
    }
    
    const handlePoiTap = (e) => {
      emit('poiTap', e)
    }
    
    const handleLocationClick = () => {
      if (!mapContext.value) return
      
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          mapContext.value.moveToLocation({
            longitude: res.longitude,
            latitude: res.latitude
          })
          
          emit('locationClick', {
            longitude: res.longitude,
            latitude: res.latitude
          })
        },
        fail: (error) => {
          uni.showToast({
            title: '获取位置失败',
            icon: 'error'
          })
        }
      })
    }
    
    const handleZoomIn = () => {
      if (!mapContext.value) return
      
      mapContext.value.getScale({
        success: (res) => {
          const newScale = Math.min(res.scale + 1, 20)
          mapContext.value.moveToLocation({
            scale: newScale
          })
        }
      })
    }
    
    const handleZoomOut = () => {
      if (!mapContext.value) return
      
      mapContext.value.getScale({
        success: (res) => {
          const newScale = Math.max(res.scale - 1, 5)
          mapContext.value.moveToLocation({
            scale: newScale
          })
        }
      })
    }
    
    const handleLayerToggle = () => {
      // 切换地图图层（卫星图/普通地图）
      uni.showActionSheet({
        itemList: ['普通地图', '卫星地图', '路况信息'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              // 切换到普通地图
              break
            case 1:
              // 切换到卫星地图
              break
            case 2:
              // 显示路况信息
              break
          }
        }
      })
    }
    
    const handleRouteClick = () => {
      showRoutePanel.value = true
    }
    
    const handleSearch = async (keyword) => {
      try {
        // 这里应该调用地图搜索API
        // 模拟搜索结果
        const mockResults = [
          {
            name: '北京天安门',
            address: '北京市东城区东长安街',
            longitude: 116.397428,
            latitude: 39.90923,
            distance: 1.2
          },
          {
            name: '故宫博物院',
            address: '北京市东城区景山前街4号',
            longitude: 116.397026,
            latitude: 39.918058,
            distance: 1.5
          }
        ]
        
        searchResults.value = mockResults.filter(item => 
          item.name.includes(keyword) || item.address.includes(keyword)
        )
      } catch (error) {
        console.error('搜索失败:', error)
      }
    }
    
    const handleSearchClear = () => {
      searchKeyword.value = ''
      searchResults.value = []
    }
    
    const handleSearchItemClick = (item) => {
      // 移动到搜索结果位置
      if (mapContext.value) {
        mapContext.value.moveToLocation({
          longitude: item.longitude,
          latitude: item.latitude,
          scale: 16
        })
      }
      
      // 显示信息窗口
      showMarkerInfo({
        title: item.name,
        address: item.address,
        longitude: item.longitude,
        latitude: item.latitude
      })
      
      // 清空搜索结果
      searchResults.value = []
    }
    
    const showMarkerInfo = (marker, position) => {
      infoData.value = {
        title: marker.title || marker.name,
        address: marker.address,
        phone: marker.phone,
        description: marker.description,
        actions: marker.actions || [
          { type: 'navigate', text: '导航' },
          { type: 'call', text: '电话' }
        ]
      }
      
      // 计算信息窗口位置
      if (position) {
        infoWindowStyle.value = {
          left: position.x + 'px',
          top: (position.y - 100) + 'px'
        }
      } else {
        infoWindowStyle.value = {
          left: '50%',
          top: '50%',
          transform: 'translate(-50%, -50%)'
        }
      }
      
      showInfoWindow.value = true
    }
    
    const hideInfoWindow = () => {
      showInfoWindow.value = false
    }
    
    const handleInfoClose = () => {
      hideInfoWindow()
    }
    
    const handleInfoAction = (action) => {
      switch (action.type) {
        case 'navigate':
          // 打开导航
          uni.openLocation({
            longitude: infoData.value.longitude,
            latitude: infoData.value.latitude,
            name: infoData.value.title,
            address: infoData.value.address
          })
          break
        case 'call':
          // 拨打电话
          if (infoData.value.phone) {
            uni.makePhoneCall({
              phoneNumber: infoData.value.phone
            })
          }
          break
      }
      
      hideInfoWindow()
    }
    
    const handleRoutePanelClose = () => {
      showRoutePanel.value = false
      routeResults.value = []
    }
    
    const handleRouteModeChange = (mode) => {
      routeForm.mode = mode
    }
    
    const handleRouteSearch = async () => {
      if (!routeForm.start || !routeForm.end) {
        uni.showToast({
          title: '请输入起点和终点',
          icon: 'none'
        })
        return
      }
      
      try {
        // 这里应该调用路线规划API
        // 模拟路线结果
        const mockRoutes = [
          {
            distance: '12.5公里',
            duration: '25分钟',
            description: '经三环路、长安街',
            polyline: [] // 路线坐标点
          },
          {
            distance: '14.2公里',
            duration: '28分钟',
            description: '经二环路、建国门',
            polyline: []
          }
        ]
        
        routeResults.value = mockRoutes
      } catch (error) {
        console.error('路线规划失败:', error)
        uni.showToast({
          title: '路线规划失败',
          icon: 'error'
        })
      }
    }
    
    const handleRouteSelect = (route) => {
      // 在地图上显示选中的路线
      if (mapContext.value && route.polyline) {
        // 这里应该更新地图上的路线显示
      }
      
      emit('routeSelect', route)
      handleRoutePanelClose()
    }
    
    // 公共方法
    const moveToLocation = (location) => {
      if (mapContext.value) {
        mapContext.value.moveToLocation(location)
      }
    }
    
    const addMarkers = (markers) => {
      // 添加标记点的方法
    }
    
    const removeMarkers = (markerIds) => {
      // 移除标记点的方法
    }
    
    const showRoute = (polyline) => {
      // 显示路线的方法
    }
    
    const clearRoute = () => {
      // 清除路线的方法
    }
    
    // 生命周期
    onMounted(() => {
      nextTick(() => {
        initMapContext()
      })
    })
    
    return {
      mapId,
      searchKeyword,
      searchResults,
      showInfoWindow,
      infoData,
      infoWindowStyle,
      showRoutePanel,
      routeForm,
      routeResults,
      mapMarkers,
      controls,
      includePoints,
      handleMarkerTap,
      handleLabelTap,
      handleCalloutTap,
      handleControlTap,
      handleRegionChange,
      handleMapTap,
      handleMapUpdated,
      handlePoiTap,
      handleLocationClick,
      handleZoomIn,
      handleZoomOut,
      handleLayerToggle,
      handleRouteClick,
      handleSearch,
      handleSearchClear,
      handleSearchItemClick,
      handleInfoClose,
      handleInfoAction,
      handleRoutePanelClose,
      handleRouteModeChange,
      handleRouteSearch,
      handleRouteSelect,
      moveToLocation,
      addMarkers,
      removeMarkers,
      showRoute,
      clearRoute
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map-view {
  width: 100%;
  height: 100%;
}

.map-toolbar {
  position: absolute;
  right: 32rpx;
  top: 32rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  z-index: 10;
}

.toolbar-btn {
  width: 80rpx;
  height: 80rpx;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .btn-icon {
    font-size: 32rpx;
  }
  
  &:active {
    background-color: #f8f9fa;
  }
}

.zoom-controls {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  
  .zoom-btn {
    width: 64rpx;
    height: 64rpx;
    
    .btn-icon {
      font-size: 28rpx;
      font-weight: 600;
    }
  }
}

.map-search {
  position: absolute;
  top: 32rpx;
  left: 32rpx;
  right: 140rpx;
  z-index: 10;
}

.search-results {
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  margin-top: 16rpx;
  max-height: 400rpx;
  overflow-y: auto;
}

.search-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: #f8f9fa;
  }
}

.item-info {
  flex: 1;
  
  .item-name {
    display: block;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 8rpx;
  }
  
  .item-address {
    font-size: 24rpx;
    color: #666;
  }
}

.item-distance {
  font-size: 24rpx;
  color: #2e8b57;
  font-weight: 500;
}

.info-window {
  position: absolute;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  min-width: 400rpx;
  max-width: 600rpx;
  z-index: 20;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -16rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 16rpx solid transparent;
    border-right: 16rpx solid transparent;
    border-top: 16rpx solid #fff;
  }
}

.info-content {
  padding: 32rpx;
}

.info-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.info-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.info-close {
  font-size: 28rpx;
  color: #666;
  padding: 8rpx;
}

.info-body {
  margin-bottom: 24rpx;
  
  .info-address,
  .info-phone,
  .info-description {
    display: block;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 12rpx;
    line-height: 1.4;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.info-actions {
  display: flex;
  gap: 16rpx;
}

.info-btn {
  flex: 1;
  height: 64rpx;
  background-color: #2e8b57;
  color: #fff;
  border-radius: 8rpx;
  font-size: 26rpx;
  
  &:active {
    opacity: 0.8;
  }
}

.route-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.15);
  max-height: 80vh;
  z-index: 30;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.panel-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.panel-close {
  font-size: 32rpx;
  color: #666;
  padding: 8rpx;
}

.route-form {
  padding: 32rpx;
}

.route-item {
  display: flex;
  align-items: center;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.route-label {
  width: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.route-input {
  flex: 1;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  
  &:focus {
    border-color: #2e8b57;
  }
}

.route-options {
  display: flex;
  gap: 16rpx;
  margin-bottom: 32rpx;
}

.route-option {
  flex: 1;
  height: 72rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #fff;
  font-size: 26rpx;
  color: #666;
  
  &.active {
    border-color: #2e8b57;
    background-color: #f0f8f0;
    color: #2e8b57;
  }
  
  &:active {
    opacity: 0.8;
  }
}

.route-search-btn {
  width: 100%;
  height: 88rpx;
  background-color: #2e8b57;
  color: #fff;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: 600;
  
  &:active {
    opacity: 0.8;
  }
}

.route-results {
  max-height: 400rpx;
  overflow-y: auto;
  border-top: 2rpx solid #f0f0f0;
}

.route-result-item {
  padding: 32rpx;
  border-bottom: 2rpx solid #f8f9fa;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: #f8f9fa;
  }
}

.route-info {
  display: flex;
  align-items: center;
  gap: 24rpx;
  margin-bottom: 12rpx;
  
  .route-distance {
    font-size: 32rpx;
    color: #2e8b57;
    font-weight: 600;
  }
  
  .route-duration {
    font-size: 28rpx;
    color: #666;
  }
}

.route-description {
  font-size: 26rpx;
  color: #999;
}
</style>