let vm = null;

const sendThis = ( _this )=> {
  vm = _this;
};

//定义地图
function getMapFn(domId, ip, mapImg, dataList ,callBack){
  let docWidth = document.documentElement.clientWidth;
  // console.log(docWidth)
  var yx = L.latLng;
  var xy = function xy(x, y) {
    if (L.Util.isArray(x)) {
      return yx(x[1], x[0]);
    }
    return yx(y, x);
  };
  var bounds = [xy(-600, -600), xy(300, 300)];
console.log({
  bounds
})
  var map = L.map(domId, {
    crs: L.CRS.Simple, //一个简单的CRS，可将经度和纬度直接映射到x其中y。可用于平面地图（例如游戏地图）
    center: L.latLng(50.5, 30.5),
    // center: L.latLng(-150, -165),
    minZoom: 0,
    maxZoom: 18,
    zoom: 0,
    maxBounds: bounds, // 地图拖动到边界后自动弹回
    maxBoundsViscosity: 0.2,
    attributionControl: false,
    zoomControl: false //zoomControl（缩放控制）：确定缩放控制是否默认加载在地图上。
  });




  var loadImg = mapImg
  if(mapImg.indexOf('http:') == -1){
    // 图片链接不包含http
    loadImg = ip + mapImg;
  }
  console.log(loadImg)

  L.imageOverlay(loadImg, bounds).addTo(map);
  L.control.zoom({
    zoomInTitle: '放大',
    zoomOutTitle: '缩小'
  }).addTo(map);
  map.fitBounds(bounds); // fitBounds（使适合边界）：将地图视图尽可能大地设定在给定的地理边界内。

  /*var popup = L.popup();
  map.on('click', onMapClick)
  // 测量点击位置的经纬度
  function onMapClick(e) {
    popup
      .setLatLng(e.latlng)
      .setContent("You clicked the map at " + e.latlng.toString())
      .openOn(map);
  }*/



  let levelArr = [];
  let level1 = [];
  let level2 = [];
  let level3 = [];
  let level4 = [];
  let level5 = [];
  let level6 = [];
  let level7 = [];
  let level8 = [];

  let riskArr = L.layerGroup();
  let risk1 = L.layerGroup();
  let risk2 = L.layerGroup();
  let risk3 = L.layerGroup();
  let risk4 = L.layerGroup();
  let risk5 = L.layerGroup();
  let risk6 = L.layerGroup();
  let risk7 = L.layerGroup();
  let risk8 = L.layerGroup();

  //按照风险点等级分类 |风险点等级 （1-4）重大，较大，一般，较低 |
  dataList.forEach((item) => {

    levelArr.push(item);
    if(item.hdangerCount >= 0 && item.hdangerLevel){
      //隐患
      if(item.hdangerLevel == 1){
        //重大隐患
        level5.push(item);
      }
      if(item.hdangerLevel == 2){
        level6.push(item);
      }
      if(item.hdangerLevel == 3){
        level7.push(item);
      }
      if(item.hdangerLevel == 4){
        level8.push(item);
      }
    }else{
      if(item.riskPointLevel == 1){
        level1.push(item);
      }
      if(item.riskPointLevel == 2){
        level2.push(item);
      }
      if(item.riskPointLevel == 3){
        level3.push(item);
      }
      if(item.riskPointLevel == 4){
        level4.push(item);
      }
    }

  });

  // console.log('全部风险点',levelArr)
  // console.log('重大', level1)
  // console.log('较大', level2)
  // console.log('一般', level3)
  // console.log('较低', level4)

  //按照点、线、面分类 |地图数据类型 （1 点 2 线 3 区域）|

  levelFn(levelArr, riskArr);
  levelFn(level1, risk1);
  levelFn(level2, risk2);
  levelFn(level3, risk3);
  levelFn(level4, risk4);
  levelFn(level5, risk5);
  levelFn(level6, risk6);
  levelFn(level7, risk7);
  levelFn(level8, risk8);


  function levelFn(level, risk){
    let potintArr = [];
    let lineArr = [];
    let faceArr = [];

    level.forEach((item) => {
      //点
      if(item.markerType == 1){
        potintArr.push(item);
      }

      // 线
      if(item.markerType == 2){
        lineArr.push(item);
      }

      // 面
      if(item.markerType == 3){
        faceArr.push(item);
      }

    });
    // console.log('点',potintArr);
    // console.log('线',lineArr);
    // console.log('面',faceArr);

    //调用 绘制点函数
    drawPointFn(potintArr, risk);

    //调用 绘制线函数
    drawLineFn(lineArr, risk);

    //调用 绘制面函数
    drawFaceFn(faceArr, risk);

  }

  //绘制点
  function drawPointFn(potintArr, risk){
    // console.log(potintArr,'..........')

    potintArr.forEach((item) => {
      let point =  JSON.parse(item.markerData);

      let icon = '';
      let iconSize = [];
      // console.log(item.hdangerCount)
      if(item.hdangerCount >= 0 && item.hdangerLevel){
        // 隐患
        iconSize = [70*docWidth/1920, 70*docWidth/1920];

        if(item.hdangerLevel == 1){
          icon = 'icon5';
        }
        if(item.hdangerLevel == 2){
          icon = 'icon6';
        }
        if(item.hdangerLevel == 3){
          icon = 'icon7';
        }
        if(item.hdangerLevel == 4){
          icon = 'icon8';
        }
        if(item.isWeightyDangerSrc == 1){
          // 是否是重大危险源
          icon = icon + ' iconhover' + (item.hdangerLevel + 4);
        }
        if(item.isWeightyDangerSrc == 1 && item.isOutOfControl == 1){
          icon = icon + ' iconhoverJump' + (item.hdangerLevel + 4);
        }
        icon = icon+' hightIndex'; //将隐患风险点显示在最上面

        /*if(item.isWeightyDangerSrc == 1 && item.isOutOfControl == 1){
          // 既是重大危险源 也失控
          icon = icon + ' iconDangerControl'
        }else{
          if(item.isWeightyDangerSrc == 1){
            // 是否是重大危险源
            icon = icon + ' iconhover' + (item.hdangerLevel + 4);
          }
          //   isOutOfControl == 1 失控,预警
          if(item.isOutOfControl == 1){
            icon = icon + ' jump';
          }
        }*/

      }else{
        // 风险点
        iconSize = [60*docWidth/1920, 70*docWidth/1920];

        if(item.riskPointLevel == 1){
          icon = 'icon1';
        }
        if(item.riskPointLevel == 2){
          icon = 'icon2';
        }
        if(item.riskPointLevel == 3){
          icon = 'icon3';
        }
        if(item.riskPointLevel == 4){
          icon = 'icon4';
        }
        if(item.isWeightyDangerSrc == 1 ){
          icon = icon + ' iconhover' + item.riskPointLevel;
        }
        if(item.isWeightyDangerSrc == 1 && item.isOutOfControl == 1){
          icon = icon + ' iconhoverJump' + item.riskPointLevel;
        }
      }

      if(item.markerTitle == '橙-设备场所类风险点1'){
        console.log(item)
      }
      if(item.markerTitle == '橙-设备场所类风险点2'){
        console.log(item)
      }
      if(item.markerTitle == '超标准洪水、粉尘'){
        console.log(item)
      }
      if(item.markerTitle == '降排水'){
        console.log(item)
      }

      //   isOutOfControl == 1 失控,预警
      if(item.isOutOfControl == 1){
        icon = icon + ' jump';
      }


      var myIcon = L.divIcon({
        className: icon,
        iconSize: iconSize,
      });

      let marker = L.marker(point, {...item, icon : myIcon});

      marker.on('mouseover', function (ev) {
        marker
          .bindPopup(item.markerTitle)
          .openPopup();
      });
      marker.on('mouseout', function (ev) {
        marker
          .closePopup();
      });

      //给每个点都加事件
      marker.on('click', function(ev) {
        vm.$emit('loadingFunc', true) //点击后显示loading加载

        //console.log(ev); // ev is an event object (MouseEvent in this case)
        callBack(ev, '点');

        let _this = vm;
        /*let obj = {
          gId:641,
          cId:1,
          riskPointId:7759
        }*/
        let obj = {
          gId:vm.$port.gId,
          cId:vm.$port.cId,
          riskPointId: item.riskPointId
        };
        // console.log(obj)

        vm.$axios.AxiosMethods("get", vm.$api.getRiskPointDetails,obj,function (res) {
          // let data = JSON.parse(res.data);
          // console.log('0000000000000000', res);

          let result = riskPointDetailmap(res);
          // console.log(result)
          _this.$store.commit('setPointDetail',result);
          _this.$store.commit('setRiskPointId',item.riskPointId);
          // console.log(_this.$store.state.riskPointDetail)

          if (_this.$store.state.riskPointDetail != null) {
            _this.$emit('loadingFunc', false) //数据加载后隐藏loading
            _this.$emit('func', true) // 显示dialog弹出层
          }
        });

      })
      marker.addTo(risk);

    });

  }

  //绘制线
  function drawLineFn(lineArr, risk){
    // console.log(lineArr);
    let colorArr = ['#FF4B28', '#FF6C00', '#FFDF0E', '#00C0FF'];

    lineArr.forEach((item) => {
      let line = JSON.parse(item.markerData);
      for(let i=0; i<line.length; i++){
        line[i] = [line[i][1], line[i][0]]
      }

      let color = colorArr[0];
      if(item.riskPointLevel == 1){
        color = colorArr[0];
      }
      if(item.riskPointLevel == 2){
        color = colorArr[1];
      }
      if(item.riskPointLevel == 3){
        color = colorArr[2];
      }
      if(item.riskPointLevel == 4){
        color = colorArr[3];
      }

      var polyline = L.polyline(line, {color: color, ...item})

      //给每条线都加事件
      polyline.on('click', function(ev) {
        // console.log(ev); // ev is an event object (MouseEvent in this case)
        callBack(ev,'线');
      });
      polyline.addTo(risk);
    })

  }

  //绘制面
  function drawFaceFn(faceArr, risk){
    // console.log(faceArr);
    let colorArr = ['#FF4B28', '#FF6C00', '#FFDF0E', '#00C0FF'];
    faceArr.forEach((item) => {
      let face = JSON.parse(item.markerData);
      face.splice(face.length-1, 1);
      for(let i=0; i<face.length; i++){
        face[i] = [face[i][1], face[i][0]]
      }
      // console.log(face);

      let color = colorArr[0];
      if(item.riskPointLevel == 1){
        color = colorArr[0];
      }
      if(item.riskPointLevel == 2){
        color = colorArr[1];
      }
      if(item.riskPointLevel == 3){
        color = colorArr[2];
      }
      if(item.riskPointLevel == 4){
        color = colorArr[3];
      }

      var polygon = L.polygon(face, {color: color, ...item});

      //给每个面都加事件
      polygon.on('click', function(ev) {
        // console.log(ev); // ev is an event object (MouseEvent in this case)
        callBack(ev,'面');

      });
      polygon.addTo(risk);
    })
  }

  var overlays = {
    "全部": riskArr,
    "重大风险点": risk1,
    "较大风险点": risk2,
    "一般风险点": risk3,
    "低风险点": risk4,
    "重大隐患点": risk5,
    "较大隐患点": risk6,
    "一般隐患点": risk7,
    "低隐患点": risk8,
  };

  let control1 = L.control.layers(null, overlays, {})
  control1.addTo(map);
  overlays['全部'].addTo(map);


  function riskPointDetailmap(result) {   // 风险点点击详情显示
    // console.log('风险点点击详情显示----------------------------------')
    // console.log(result)

    // console.log(result.data.data.riskCheckedRecordDtos)
    if(result.data!=null){
      let dataList=result.data;
      let baseInfo="";//基本信息
      let riskList="";//风险
      let workSitePerson =[]; // 现场人员
      let checkListRecord=[]; // 检查记录
      let hiList=[];//隐患
      let warningInfo=[];//警告
      let checkSafeList=[];//安全检查表

      let workInstructionList = [];//作业指导书


      if(dataList){//基本信息
        baseInfo=dataList;
      }
      if(dataList.riskCheckedRecord){//检查记录
        checkListRecord=dataList.riskCheckedRecord;
      }
      if(dataList.hiddenDangerList){//隐患
        hiList=dataList.hiddenDangerList;
      }
      // console.log(hiList)
      if(dataList.riskPointWarn){//警告
        warningInfo=dataList.riskPointWarn;
      }

      // console.log('dataList.workInstructionList___________________________')
      // console.log(dataList)
      // console.log(dataList.workInstruction)
      if(dataList.riskDto){//风险
        riskList=dataList.riskDto;
      }
      if(dataList.riskMeasuresInfo){//安全检查表
        checkSafeList=dataList.riskMeasuresInfo;
      }
      if (dataList.workSitePerson) { // 现场人员
        workSitePerson = dataList.workSitePerson
      }
      if (dataList.workInstruction) { //作业指导书
        workInstructionList=dataList.workInstruction
      }
      return {
        baseInfo,
        riskList,
        workSitePerson,
        checkListRecord,
        hiList,
        warningInfo,
        checkSafeList,
        workInstructionList,
        tabActive:'baseInfo',
        cIndex1:"0",
        cIndex2:"0",
        cIndex3:"0",
        cIndex4:"0",
      }
    }
  }

}



export default {
  getMapFn,
  sendThis
}
