<template>
  <div class="demo-page" :style="{ height: '87vh' }">
    <AfMap
      v-if="gisConfig && webConfig"
      ref="mapTool"
      class="map-area"
      map-options-name="GisHomeConfig"
      serviceName="af-linepatrol"
      :show-group-id-arr="showGroupIdArr"
      :get-dynamic-icon="getDynamicIcon"
      :handle-svg-error="handleSvgError"
      @closeAllActiveBusiness="closeAllActiveBusiness"
      @inited="handleInited"
      @loading-change="loading = $event"
      @dock-click="handleDockClick"
      @panel-select="panelSelect"
      @wms-click="handleWmsClick"
      @map-click="handleMapClick"
    />

    <div v-if="tipMessage" class="map-tip">
      {{ tipMessage }}
    </div>
  </div>
</template>

<script>
import AfMap from '@vue2-client/base-client/components/common/AfMap/map/index.vue'
import {getConfigByNameAsync, runLogic} from '@vue2-client/services/api/common'
import { mapState } from 'vuex'
import InfoWindowComponent from '@vue2-client/base-client/components/common/AfMap/InfoWindowComponent.vue'
export default {
  name: 'MapDemo',
  components: {
    AfMap,
    InfoWindowComponent
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
  },
  data () {
    return {
      inited: false,
      loading: false,
      groups: [],
      currentEngine: 'OPENLAYERS',
      mapViewMode: '3D',
      mapConfig: {},
      tipMessage: '',
      gisConfig: null,
      webConfig: null,
      // WMS点击查询事件是否开启
      wmsClickEnabled: false,
      showGroupIdArr: ['line-patrol-plan-point']
    }
  },
  async created () {
    this.mapConfig = await getConfigByNameAsync('GisHomeConfig', 'af-linepatrol')
    this.pageSize = this.mapConfig.queryResultPageSize || 20
    this.businessLayers = this.mapConfig?.businessLayers || []
    this.gisConfig = await getConfigByNameAsync('gisConfig', 'af-linepatrol')
    this.webConfig = await getConfigByNameAsync('webConfig', 'af-linepatrol')
  },
  async mounted () {
  },
  methods: {
    getDynamicIcon(iconName) {
      // console.log(iconName)
      if (!iconName) {
        console.warn('svgName 未定义，使用默认SVG')
        return require('@vue2-client/assets/svg/unknown-icon.svg')
      }
      try {
        return require(`@vue2-client/assets/svg/${iconName}.svg`)
      } catch (error) {
        console.warn(`SVG ${iconName} 未找到，使用默认SVG`, error)
        return require('@vue2-client/assets/svg/unknown-icon.svg')
      }
    },
    handleSvgError(event) {
      console.warn('图片加载失败，使用默认图片')
      // 设置默认图片
      event.target.src = require('@vue2-client/assets/svg/unknown-icon.svg')
    },
    // ===== 生命周期 & 初始化 =====
    async handleInited() {
      this.inited = true
      this.currentEngine = this.$refs.mapTool.getCurrentEngine()
      if (this.$refs.mapTool.getMapViewMode) {
        this.mapViewMode = this.$refs.mapTool.getMapViewMode() || '3D'
      }
      // 添加一个demo图层
      const defaultParams = {}
      if (this.webConfig?.setting?.isGroup) {
        defaultParams.f_orgid = this.currUser?.orgid || this.currUser?.operaInfo?.f_orgid || this.currUser?.operInfo?.f_orgid
      }
      const getMarkerData = async (params) => {
        const param = {
          endDate: params?.endDate || this.getNowDay()
        }
        if (params?.f_orgid) {
          param.f_orgid = params?.f_orgid || params?.orgid
        }
        try {
          const locationList = await runLogic('getPatrolTaskPoints', param, 'af-linepatrol')
          return locationList.map(item => {
            // eslint-disable-next-line camelcase
            const {f_longitude, f_latitude, f_state, f_check_state, ...rest} = item
            return {
              lng: Number(f_longitude),
              lat: Number(f_latitude),
              icon: (() => {
                let iconUrl = ''
                // eslint-disable-next-line camelcase
                if (f_state === '正常') {
                  iconUrl = this.getDynamicIcon('inspected')
                }
                // eslint-disable-next-line camelcase
                if (f_state === '有隐患') {
                  iconUrl = this.getDynamicIcon('pointhidden')
                }
                // eslint-disable-next-line camelcase
                if (f_check_state === '已检') {
                  iconUrl = this.getDynamicIcon('checked')
                }
                return iconUrl
              })(),
              // eslint-disable-next-line camelcase
              f_state,
              // eslint-disable-next-line camelcase
              f_check_state,
              name: item.f_name,
              ...rest
            }
          })
          // 处理最新的数据
        } catch (e) {
          console.log('>>>>获取固定点位失败', e)
          return []
        }
      }
      // 点击巡检计划
      const onClickLinePatrolPlanPoint = async (mapService, marker, markerOptions) => {
        console.warn('>> 点击巡检计划', marker, markerOptions)

        try {
          const data = await runLogic('getPointAndPlanByPlanPointIdLogic', { id: marker.id }, 'af-linepatrol')
          console.warn('>> 获取到的数据', data)


          // 调用openInfoWindow
          this.$refs.mapTool.openInfoWindow(
            [marker.lng, marker.lat],
            InfoWindowComponent,
            {
              props: { data },
              on: {
                close: () => console.log('信息窗口关闭')
              }
            }
          )

        } catch (error) {
          console.error('获取数据失败:', error)
        }
      }
      await this.$refs.mapTool.addMarker(getMarkerData,
        {
          groupId: 'line-patrol-plan-point',
          groupName: '巡检计划',
          desc: '巡线任务安排',
          func: 'getLinePatrolPlanPoint',
          visible: true,
          groupType: '业务图层',
          icon: 'patrol-plan',
          color: '#1890ff',
          onClick: 'onClickLinePatrolPlanPoint'
        },
        onClickLinePatrolPlanPoint)
      // 添加 WMS
      await this.handleAddWms()
      await this.handleRefreshGroups()
      this.$refs.mapTool.updateGroupsByGroupType()
    },
    getNowDay () {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要加1，并补零
      const day = String(today.getDate()).padStart(2, '0') // 补零
      return `${year}-${month}-${day}`
    },
    async handleRefreshGroups () {
      if (!this.inited) return
      this.groups = await this.$refs.mapTool.getGroups()
      // console.warn('>>>> groups', this.groups)
    },
    async handleAddWms() {
      try {
        const layers = this.gisConfig?.layers ?? []
        const wmsCfg = this.gisConfig?.wms ?? {}
        const geoserverUrl = wmsCfg.target || '/gis/geoserver/aofeng/wms'
        const version = wmsCfg.version || '1.3.0'
        const format = wmsCfg.format || 'image/png'
        const srs = wmsCfg.srs || 'EPSG:3857'
        // 版本号获取回调
        const getLayerVersion = async (tableName) => {
          const layersVersion = await runLogic('getLayersVersion', {f_table_name: tableName}, 'af-linepatrol')
          return layersVersion[0]?.f_version || Date.now()
        }
        for (const layer of layers) {
          const wms = {
            id: layer.key,
            name: layer.value || layer.layerName || `layer-${layer.id}`,
            url: geoserverUrl,
            // 注入版本号回调：由地图适配器缓存，refresh 时直接调用，无需再传 不传递或调用失败时使用时间戳
            getLayerVersion,
            params: {
              SERVICE: 'WMS',
              REQUEST: 'GetMap',
              VERSION: version,
              FORMAT: layer.format || format,
              TRANSPARENT: true,
              LAYERS: layer.layerName,
              STYLES: '',
              SRS: srs,
              CRS: srs,
            },
            visible: layer.show !== false
          }
          // 现在可以安全地使用 await 了
          await this.$refs.mapTool.addWmsLayer(
            wms,
            layer.key,
            layer.value || layer.layerName || `layer-${layer.id}`,
            'vtb' in layer ? '输配管线' : '站场与设备'
          )
        }
      } catch (e) {
        console.error('WMS图层加载失败', e)
      }
      await this.handleRefreshGroups()
    },
    // ===== custom dock 事件（父组件处理） =====
    async handleDockClick (btn) {
      // this.$message.info(`>>>> 点击了 ${btn.click} - ${btn.text}`)
      // 查询过程中不允许触发业务按钮
      if (this.queryLoading) {
        this.$message.warning(this.loadingMessage)
        return
      }

      // 【重要】每次接收到新的 dock 点击事件时，先关闭所有之前激活的业务功能
      // 这样可以确保状态清理干净，避免残留
      await this.closeAllActiveBusiness()

      // 只处理 custom=true 的 dock 事件，其余由地图内部处理
      if (!btn?.custom) return

      // 如果点击的是当前已激活的 dock（visible=false），则只关闭，不打开新功能
      if (!btn.visible) {
        this.$refs.mapTool.togglePanelIsCollapsed(false)
        return
      }
      this.$refs.mapTool.togglePanelIsCollapsed()
      switch (btn.click) {
        // 数据筛选
        case 'toggle-filter': {
          const layers = Array.isArray(this.gisConfig?.layers) ? [...this.gisConfig.layers] : []
          this.toggleFilterLayers = layers
          this.showToggleFilter = true
          break
        }
        // 数据编辑
        case 'panel-edit': {
          this.showDataEditPanel = true
          // 重置编辑模式状态
          this.dataEditMode = {
            enabled: false
          }
          break
        }
        // 报警监控
        case 'panel-layers': {
          this.showPanelLayers = true
          break
        }
        // 告警列表
        case 'panel-alarms': {
          this.showpanelAlarms = true
          break
        }
        // 巡线业务
        case 'linepatrol': {
          this.showLinePatrol = true
          break
        }
        // 巡线人员定位
        case 'panel-inspectors': {
          this.$refs.mapTool.setGroupVisible('line-patrol-person-real-time-info', true)
          this.showPersonInspectors = true
          break
        }
        default: {
          const panelButton = this.mapConfig?.toolButton?.find(item => item.click === btn.click)
          if (!panelButton?.button) return
          const position = panelButton?.buttonPosition || 'right'
          this.businessCard = {
            visible: true,
            title: btn.text,
            buttons: panelButton.button,
            position,
            activeButton: null
          }
          break
        }
      }
    },
    async panelSelect (data) {
      console.log('panelSelect', data)
    },
    // 处理WMS点击事件：统一交给 ModeManager（包括编辑点选模式）
    handleWmsClick (data) {
      try {
        console.log('WMS点击查询结果:', JSON.stringify(data))
      } catch (e) {
        console.error('>>> handleWmsClick', e)
      }
    },
    // 处理通用地图点击事件
    handleMapClick (coordinate) {
      try {
        console.log('onMapClick', coordinate)
      } catch (e) {
        console.error('>>>  handleMapClick', e)
      }
    },
    closeAllActiveBusiness() {
    },
  }
}
</script>

<style scoped>
.demo-page {
  position: relative;
  width: 100%;
}

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

.map-tip {
  position: absolute;
  top: 12px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 998;
  background: rgba(255, 255, 255, 0.75);
  border: 1px solid rgba(24, 144, 255, 0.35);
  font-size: 16px;
  color: #000;
  border-radius: 30px;
  padding: 10px 18px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  font-weight: 600;
}

.panel-toggle-mini {
  position: absolute;
  bottom: 12px;
  right: 12px;
  z-index: 10000;
  padding: 4px 8px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.panel-overlay {
  position: absolute;
  bottom: 12px;
  left: 12px;
  right: 12px;
  z-index: 10000;
  pointer-events: none;
}

.panel-overlay > * {
  pointer-events: auto;
}

.query-result {
  position: absolute;
  bottom: 10%;
  display: flex;
  flex-direction: column;
  z-index: 998;
  right: 12px;
}

.query-result button {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  border: none;
  background: #1890ff;
  color: #fff;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
  transition: all 0.2s ease;
  padding: 0;
}

.query-result button:hover {
  background: #40a9ff;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #e0e0e0;
  border-radius: 0 0 8px 8px;
  padding: 8px 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.panel-title {
  font-size: 14px;
  font-weight: 600;
}

.panel-actions button {
  margin-left: 8px;
  padding: 4px 8px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
}

.op-section h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.op-section button {
  margin-right: 8px;
  margin-bottom: 8px;
  padding: 6px 12px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s;
}

.op-section button:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.engine-switch button {
  width: 100%;
}

.engine-switch button.active {
  background: #1890ff;
  color: #fff;
  border-color: #1890ff;
}

.engine-switch button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

