<template>
  <div class="my-ships-main" id="map">
    <!--气象点击显示内容-->
    <OnClickWeather></OnClickWeather>
    <!--   港口鼠标悬浮显示内容   -->
    <PortHoverView></PortHoverView>
    <!--船舶鼠标悬浮时显示信息-->
    <ShipHoverView></ShipHoverView>
    <!--    地图底部船舶类型备注框-->
    <MapBottomShipType></MapBottomShipType>
    <!--    地图底部鼠标位置经纬度显示-->
    <MapBottomMousePos></MapBottomMousePos>
    <!--    弹窗最小化-->
    <MiniBox></MiniBox>
    <!--    船舶轨迹鼠标悬浮时显示信息-->
    <TrackHoverView></TrackHoverView>
    <!--    消息列表循环滚动展示-->
    <realTimeInfo></realTimeInfo>
    <!--  显示全部港口  -->
    <ViewAllPort></ViewAllPort>
  </div>
</template>

<script lang="ts">
import ShipFun from '@/util/map/map.js'
import {Component, Vue} from 'vue-property-decorator'
import storeUtil from '@/util/store'
import OnClickWeather from "@/components/on-map-view/OnClickWeather.vue";
import PortHoverView from "@/components/on-map-view/PortHoverView.vue";
import ShipHoverView from "@/components/on-map-view/ShipHoverView.vue";
import MapBottomShipType from "@/components/on-map-view/MapBottomShipType.vue";
import MapBottomMousePos from "@/components/on-map-view/MapBottomMousePos.vue";
import MiniBox from "@/components/on-map-view/MiniBox.vue";
import TrackHoverView from "@/components/on-map-view/TrackHoverView.vue";
import realTimeInfo from "@/components/real-time-info/realTimeInfo.vue";
import HttpApi from "@/api";
import DialogUtil from "@/util/new-dialog";
import PortQueryTemp from '../new-dialog/PortQueryTemp.vue';
import {DialogType} from '@/util/temp-interface';
import {SearchLogUtil} from "@/util/tool";
import bus from '@/util/bus';
import ShipInfoTemp from '../new-dialog/ShipInfoTemp.vue';
import CarInfoTemp from '../new-dialog/CarInfoTemp.vue';
import ViewAllPort from "@/components/on-map-view/ViewAllPort.vue";
import {Style} from 'ol/style.js'
import Icon from 'ol/style/Icon'
import styleText from 'ol/style/Text' //添加文字标注
import styleFill from 'ol/style/Fill' //添加填充样式
import styleStroke from 'ol/style/Stroke' //添加填充样式

const warningImg = require('../../util/map/img/shipWarningIcon.png') 
const config = require('../../../public/config/sys-config.json')
const elementResizeDetectorMaker = require("element-resize-detector")

@Component({
  components: {
    OnClickWeather,
    PortHoverView,
    ShipHoverView,
    MapBottomShipType,
    MapBottomMousePos,
    MiniBox,
    TrackHoverView,
    realTimeInfo,
    ViewAllPort
  }
})
export default class Main extends Vue {
  private map: any

  private shipData = []
  private carData = []
  private async getShips() {
    const ships: any = []
    await HttpApi.getShipRanks({}).then((res: any) => {
      res.forEach((item: any) => {
        if (item.idw !== -1 && item.followShipList && item.followShipList.length) {
          item.followShipList.forEach(async (item2: any) => {
            item2.groupName = item.name;
            item2.color = item.color;
            ships.push(item2)
          })
        }
      })
    })

    const shipIds: any[] = []
    for (let i = 0; i < ships.length; i++) {
      shipIds.push(ships[i].shipId)
    }
    if (shipIds.length <= 100) {
      await HttpApi.getShipMessage({shipId: shipIds.toString()}).then((res: any[]) => {
        for (let i = 0; i < ships.length; i++) {
          res.forEach((item: any) => {
            if (ships[i].shipId === item.shipId) {
              Object.keys(item).forEach((key) => {
                ships[i][key] = item[key]
              })
            }
          })
        }
      })
    } else {
      const p: any[] = []
      const idGroup = this.spArray(shipIds, 100);
      for (let i = 0; i < idGroup.length; i++) {
        const ids = idGroup[i];
        p.push(new Promise((resolve) => {
          HttpApi.getShipMessage({shipId: ids.toString()}).then((res) => {
            resolve(res)
          })
        }))
      }

      const newGetShips: any[] = []
      await Promise.all(p).then((res) => {
        for (let i = 0; i < res.length; i++) {
          const shipG: any[] = res[i];
          for (let j = 0; j < shipG.length; j++) {
            newGetShips.push(shipG[j])
          }
        }
      })

      for (let i = 0; i < ships.length; i++) {
        newGetShips.forEach((item: any) => {
          if (ships[i].shipId === item.shipId) {
            Object.keys(item).forEach((key) => {
              ships[i][key] = item[key]
            })
          }
        })
      }
    }
    this.shipData = ships
    this.jiexiRanks(ships);
    storeUtil.setShipFleet(ships);
    // this.setShipWarning(ships);
  }
  private getCars() {
    const carData: any = []
    HttpApi.getCarInfo().then((res) => {
      for (let i = 0; i < Object.keys(res).length; i++) {
        const key = Object.keys(res)[i];
        carData.push({
          carNum: res[key].carNum,
          companyName: res[key].companyName,
          customsCreateDate: res[key].customsCreateDate,
          gpsTime: res[key].data && res[key].data.GpsTime ? res[key].data.GpsTime : '',
          latitude: res[key].data && res[key].data.Latitude ? res[key].data.Latitude : '',
          longitude: res[key].data && res[key].data.Longitude ? res[key].data.Longitude : '',
          entryId: res[key].entryId,
          firstRegistrationDate: res[key].firstRegistrationDate,
          vehicleModel: res[key].vehicleModel
        })
      }
      this.carData = carData
      ShipFun.addCar(carData.filter((item: any) => {
        return item.latitude && item.longitude
      }), this.map)
      this.setCarWarning(carData.filter((item: any) => {
        return item.latitude && item.longitude
      }))
    })
  }
  private spArray(array: any[], len: number) {
    const newArray: any[] = [];
    item(array, len)

    function item(array: any[], len: number) {
      if (array.length && array.length > len) {
        newArray.push(array.splice(0, len))
        item(array, len);
      } else if (array.length && array.length < len) {
        newArray.push(array)
        array = []
      }
    }

    return newArray
  }

  private jiexiRanks(data: any) {
    const newShipList: any = []
    data.forEach((item: any) => {
      newShipList.push({
        y: item.shiptype,
        m: item.mmsi,
        h: item.heading,
        g: item.callsign,
        c: item.cog,
        o: item.imo,
        s: item.sog,
        v: item.aisNavStatus,
        l: item.length,
        p: item.destPort,
        b: item.breadth,
        r: item.eta,
        d: item.draught,
        t: item.posTime,
        i: item.shipId,
        n: item.lon,
        a: item.lat,
        e: item.shipnameEn,
        color: item.color,
        isFleet: true
      })
    })
    ShipFun.addShip(JSON.parse(JSON.stringify(newShipList)), 11, storeUtil.getMapInstance())
  }

  private setShipWarning(ships: any[]) {  //将更新时间超出30天的游艇的图标设置为感叹号
    const nowTime: number = (new Date()).getTime()
    const temp: string[] = []
    ships.forEach((item: any) => {
      let timeDiff: number = item.posTime ? (nowTime - (item.posTime * 1000)) / (24 * 60 * 60 * 1000) : 0 
      if (timeDiff > 30) {
        temp.push(item.shipId)
      }
    })
    const features = ShipFun.getShipFeaturesByIds(temp)
    const iconStyle = new Style({
      image: new Icon({
        color: '#ffffff',
        crossOrigin: 'anonymous',
        src: warningImg,
        scale: 0.18
      })
    })
    features.forEach((f: any) => {
      f.setStyle(iconStyle)
    })
  }

  private setCarWarning(dataList: any[]) {
    const nowTime: number = (new Date()).getTime()
    const temp: string[] = []
    dataList.forEach((item: any) => {
      let timeDiff: number = item.gpsTime ? (nowTime - new Date(item.gpsTime).getTime()) / (24 * 60 * 60 * 1000) : 0 
      if (timeDiff > 3) {
        temp.push(item.carNum)
      }
    })
    const features = ShipFun.getCarFeaturesByIds(temp)
    features.forEach((f: any) => {
      const iconStyle = new Style({
        image: new Icon({
          color: '#ffffff',
          crossOrigin: 'anonymous',
          src: warningImg,
          scale: 0.25
        }),
        text: new styleText({
          font: '16px Microsoft YaHei 100',
          textAlign: 'center',
          overflow: true,
          fill: new styleFill({
            color: '#000'
          }),
          stroke: new styleStroke({
            color: '#fff',
            width: 3
          }),
          textBaseline: 'bottom',
          text: f.get('carNum')
        })
      })
      f.setStyle(iconStyle)
    })
  }
  private showAllData() {
    //展示所有数据
    //this.getShips()
    //this.getCars()
    this.jiexiRanks(this.shipData);
    // this.setShipWarning(this.shipData);
    ShipFun.addCar(this.carData.filter((item: any) => {
      return item.latitude && item.longitude
    }), this.map)
    this.setCarWarning(this.carData.filter((item: any) => {
      return item.latitude && item.longitude
    }))
  }
  public mounted() {
    this.map = ShipFun.creatMap()
    this.map.updateSize()
    storeUtil.setMapInstance(this.map)
    storeUtil.setMapFun(ShipFun);
    ShipFun.setmap(this.map)
    ShipFun.setCenter([110, 19]);
    ShipFun.setZoom(9)
    ShipFun.changeMap(this.map, 'tdt')
    ShipFun.createMeasureTooltip(this.map) //测距显示
    // ShipFun.addFullScreen(this.map) // 全屏按钮显示
    ShipFun.addScaleLine(this.map) // 添加比例尺
    ShipFun.addMousePos(this.map) // 添加显示鼠标位置的经纬度信息
    ShipFun.addZoomListener(this.map, () => {
      this.map
        .getControls()
        .getArray()
        .forEach((item: any) => {
          if (
            item.values_ &&
            JSON.stringify(item.values_) !== '{}' &&
            Object.keys(item.values_).includes('units') &&
            item.values_.units === 'nautical'
          ) {
            ShipFun.plotting(parseInt(item.renderedHTML_))
          }
        })
    })
    ShipFun.addClick(async (res: any) => {
      if (res.isType === 'port') {
        let port: any = {}
        await HttpApi.getPortInfo(res.portId).then((res2: any) => {
          port = res2
          Object.assign(port, res)
        })
        port.cLon = port.portLon * 600000
        port.cLat = port.portLat * 600000
        DialogUtil.showDialog(PortQueryTemp, DialogType.PORT_QUERY, {
          dialogData: {
            title: `${port.nameCn}-${port.nameEn}`,
            vueName: DialogType.PORT_QUERY
          },
          infoData: {
            portInfo: port
          },
          show: true
        })
      } else if (res.isType === 'ship') {
        let shipData: any = {}
        let docData = {}
        await HttpApi.getShipMessage({shipId: res.shipId}).then((res: any) => {
          const SearchLog = (this as any).$SearchLog
          let flag = true
          if (SearchLog.length) {
            for (let i = 0; i < SearchLog.length; i++) {
              const item = SearchLog[i]
              if (item.shipId === res[0].shipId) {
                flag = false
                break
              }
            }
          }

          if (flag) {
            SearchLogUtil.addSearchLog(res[0])
          }
          storeUtil.setShipData(res[0])
          shipData = res[0]
        })
        await HttpApi.getShipDoc({shipId: res.shipId}).then((res: any) => {
          if (res) {
            docData = res
          }
        })
        await HttpApi.getShipCnName({mmsi: shipData.mmsi}).then((res: any) => {
          if (res) {
            shipData.shipnameCn = res.nameCn
          }
        })
        DialogUtil.showDialog(ShipInfoTemp, DialogType.SHIP_INFO, {
          dialogData: {
            title: shipData.shipnameCn,
            vueName: DialogType.SHIP_INFO
          },
          infoData: {
            shipData: shipData,
            docData: docData
          },
          show: true
        })
      } else if (res.isType === 'car') {
        DialogUtil.showDialog(CarInfoTemp, DialogType.CAR_INFO, {
          dialogData: {
            title: res.carNum,
            vueName: DialogType.CAR_INFO
          },
          infoData: {
            carData: res
          },
          show: true
        })
      }
    })
    // 当侧边栏修改的时候去地图去适应宽高的变化
    elementResizeDetectorMaker().listenTo(document.getElementById('map'), () => {
      this.map.updateSize()
    })
    this.getShips()
    this.getCars()
    bus.$on('showAllData', () => {
      this.showAllData()
    })
  }
}
</script>
<style scoped lang="scss">
.my-ships-main {
  width: 100%;
  height: 100%;
  position: relative;
  font-size: 0.875rem;

  ::v-deep .ol-zoom {
    position: absolute;
    background: none;
    left: 1.25rem !important;
    bottom: 6.25rem !important;
    top: auto !important;
  }

  ::v-deep .ol-full-screen {
    position: absolute;
    left: 1.25rem !important;
    margin: 0 !important;
    background: none !important;
    top: auto !important;
    right: auto !important;
    bottom: 9.375rem !important;
  }

  ::v-deep .ol-scale-line {
    position: absolute !important;
    left: 9.375rem !important;
    width: 7.5rem !important;
    height: 3.125rem !important;
    box-sizing: border-box !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;

    .ol-scale-line-inner {
      width: 6.875rem !important;
      height: 2.5rem !important;
      font-size: 0.875rem !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
    }
  }
}
</style>
