<template>
  <div class="map-container">
    <div id="container"></div>
    <div class="map-player">
      <slot />
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import CarOnline from '@/assets/icons/car-online.svg'
import CarOffline from '@/assets/icons/car-offline.svg'
import CarGwcOffline from '@/assets/icons/car-gwc_offline.png'
import CarGwc from '@/assets/icons/car-gwc.png'
import { getCarList } from '@/api/manage/index.js'
import { getCarInfo, getCarLocation } from '@/api/iot.js'
// import geojson from './lj.json'

window._AMapSecurityConfig = {
  securityJsCode: 'a658c2ad641e48ad5abb56d2ad113e5b',
}
export default {
  data() {
    return {
      map: null,
      AMap: null,
      depId: null,
      markeList: null,
      timer: null,
      ids: '',
      ruler1: null,
      mouseTool: null,
      carMarker: null,
      pos: [],
      posIndex: 0,
    }
  },
  provide() {
    return {
      carMap: this,
    }
  },
  props: {
    idInfo: Object,
    showRang: String,
  },
  watch: {
    idInfo: {
      handler(val) {
        this.markeList.forEach((element) => {
          this.map.remove(element)
        })
        if (this.timer) {
          clearTimeout(this.timer)
        }
        if (val.key.indexOf('car') >= 0) {
          this.ids = val.meta.id
          this.addCarMaker(this.AMap)
        } else {
          this.depId = val.meta.deptId
          this.loadFireCarInfo(this.AMap)
        }
      },
      deep: true,
    },
  },

  methods: {
    callback(fn) {
      if (fn) {
        fn(this)
      }
    },
    // 添加遮罩
    addMask () {
      const outer = [
        new this.AMap.LngLat(-360, 90, true),
        new this.AMap.LngLat(-360, -90, true),
        new this.AMap.LngLat(360, -90, true),
        new this.AMap.LngLat(360, 90, true),
      ]
      new this.AMap.GeoJSON({
        geoJSON: geojson,
        getPolygon: (geojson, lnglats) => {
          console.log('面',lnglats)
          const pathArray = [
            // outer, //外边界
            lnglats[0][0] //内边界需要遮罩区域
          ]
          var polygon = new AMap.Polygon({
            pathL: pathArray,
            // strokeColor: 'rgba(190, 161, 58, 1)',
            // strokeWeight: 2,
            fillColor: 'rgba(0,0,0,.0)',
          })
          polygon.setPath(pathArray)
          this.map.add(polygon)
        }
      })

    },
    async initMap() {
      return AMapLoader.load({
        key: 'a09220a9ab56352435dd123abf0c37f6', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.MoveAnimation','AMap.RangingTool', 'AMap.MouseTool', 'AMap.DistrictSearch', 'AMap.GeoJSON'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等      AMap.RangingTool（测距）
      })
        .then((AMap) => {
          this.AMap = AMap
          this.map = new AMap.Map('container', {
            // 设置地图容器id
            viewMode: '3D', // 是否为3D地图模式
            zoom: 12, // 初始化地图级别
            mapStyle: 'amap://styles/whitesmoke',
            // 初始化地图中心点位置
            center: ['106.4754116', '29.6307097'],
          })
          // this.addMask()
          // 测距
          this.ruler1 = new AMap.RangingTool(this.map)
          // 面积
          this.mouseTool = new AMap.MouseTool(this.map)
          this.mouseTool.measureArea({
            strokeColor: '#80d8ff',
            fillColor: '#80d8ff',
            fillOpacity: 0.3,
            //同 Polygon 的 Option 设置
          })
          this.mouseTool.close(true)
          // 加载消防车辆信息
          // this.loadFireCarInfo(AMap)
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 加载消防车辆
    loadFireCarInfo(AMap) {
      const cache = {}
      const that = this
      // 刷新消防车辆
      function refreshFireCar() {
        const params = {
          deptId: that.depId,
        }
        getCarList(params).then((res) => {
          for (const car of res.data) {
            const carImage = {
              image: car.onlineStatus === 1 ? (car.sourceType === 2 ? CarGwc : CarOnline)  : CarOffline ,
              size: [40, 40],
              imageSize: [40, 40],
            }
            const icon = new AMap.Icon(carImage)
            icon.size = new AMap.Size(40, 40)
            icon.imageSize = new AMap.Size(40, 40)
            const position = [car.lng, car.lat]
            const marker = new AMap.Marker({
              icon,
              position,
            })
            // 基础信息模块
            const content = [
              `<div class='info_box_contant' style="background: rgba(255, 255, 255);">
                  <div style='width:100%;height:40px;border-bottom: 1px solid #EFEFEF;position:relative;padding:0 12px;display:flex;align-items: center;justify-content:space-between;'>
                    <span style='font-size: 18px;font-weight: bold;margin-right:4px;'>${car.plateNumber}</span>
                    <span style='display:inline-block;font-size:12px;border: 1px solid #547CD5;border-radius: 2px;color:#547CD5;padding:1px 5px;'>${
                      car.onlineStatus === 1 ? '在线' : '离线'
                    }</span>
                  </div>
                  <div style="width:100%;padding:4px 12px;">${car.depName}</div>
                  <div style="width:100%;padding:4px 12px;">实时车速：0.0km/h</div>
                </div>`,
            ]
            const basicInfo = new AMap.InfoWindow({
              isCustom: true, // 使用自定义窗体
              content: content,
              offset: new AMap.Pixel(5, 5),
            })
            marker.on('mouseover', (e) => {
              // 后面的参数指的是经纬度，在此显示窗口
              basicInfo.open(that.map, position)
            })

            marker.on('mouseout', (e) => {
              basicInfo.close()
            })
            // 点击消防车车
            marker.on('click', (e) => {
              // basicInfo.close()
              that.$emit('clickCarItem', car)
            })

            if (cache[car.id] && that.map) {
              that.map.remove(cache[car.id])
            }
            cache[car.id] = marker
            that.markeList = Object.values(cache)
            that.map.add(marker)
          }
          that.timer = setTimeout(() => {
            refreshFireCar()
          }, 10 * 1000)
        })
      }
      refreshFireCar()
    },
    addCarMaker(AMap) {
      const cache = {}
      const that = this
      // 刷新消防车辆
      function refreshFireCar() {
        getCarInfo(that.ids).then((res) => {
          const car = res.data
          const carImage = {
            image: car.onlineStatus === 1 ? CarOnline : CarOffline,
            size: [40, 40],
            imageSize: [40, 40],
          }
          const icon = new AMap.Icon(carImage)
          icon.size = new AMap.Size(40, 40)
          icon.imageSize = new AMap.Size(40, 40)
          const position = [car.ssjgwd, car.ssjgjd]
          const marker = new AMap.Marker({
            icon,
            position,
          })
          // 基础信息模块
          const content = [
            `<div class='info_box_contant' style="background: rgba(255, 255, 255);">
                  <div style='width:100%;height:40px;border-bottom: 1px solid #EFEFEF;position:relative;padding:0 12px;display:flex;align-items: center;justify-content:space-between;'>
                    <span style='font-size: 18px;font-weight: bold;margin-right:4px;'>${car.plateNumber}</span>
                    <span style='display:inline-block;font-size:12px;border: 1px solid #547CD5;border-radius: 2px;color:#547CD5;padding:1px 5px;'>${
                      car.onlineStatus === 1 ? '在线' : '离线'
                    }</span>
                  </div>
                  <div style="width:100%;padding:4px 12px;">${car.plateNumber}</div>
                  <div style="width:100%;padding:4px 12px;">经度：${car.ssjgjd}</div>
                  <div style="width:100%;padding:4px 12px;">纬度：${car.ssjgwd}</div>
                  <div style="width:100%;padding:4px 12px;">${car.depName}</div>
                  <div style="width:100%;padding:4px 12px;">实时车速：0.0km/h</div>
                </div>`,
          ]
          const basicInfo = new AMap.InfoWindow({
            isCustom: true, // 使用自定义窗体
            content: content,
            offset: new AMap.Pixel(5, 5),
          })
          marker.on('mouseover', (e) => {
            // 后面的参数指的是经纬度，在此显示窗口
            basicInfo.open(that.map, position)
          })

          marker.on('mouseout', (e) => {
            basicInfo.close()
          })
          // 点击消防车车
          marker.on('click', (e) => {
            // basicInfo.close()
            that.$emit('clickCarItem', car)
          })

          if (cache[car.id] && that.map) {
            that.map.remove(cache[car.id])
          }
          cache[car.id] = marker
          that.markeList = Object.values(cache)
          that.map.add(marker)
          // that.timer = setTimeout(() => {
          //   refreshFireCar()
          // }, 10 * 1000)
        })
      }
      refreshFireCar()
    },
  },
  mounted() {
    // 初始化完成进行地图初始化
    this.initMap()
  },
}
</script>

<style lang="less" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
}
.map-container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
  position: relative;
}
.map-player {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  pointer-events: none;
}
</style>
