var opts = {
  subdistrict: 0,
  extensions: 'all',
  level: 'city',
};
var district = new AMap.DistrictSearch(opts);

var object3Dlayer = new AMap.Object3DLayer({ zIndex: 1 });
var menu;
var MTOOL;

// function renderMap() {
// 渲染地图
district.search('赞皇', function (status, result) {
  var bounds = result.districtList[0].boundaries;
  // var mask = [];
  // for (var i = 0; i < bounds.length; i += 1) {
  //   mask.push([bounds[i]]);
  // }
  var defaultCenter = [114.72995, 38.37417];
  map = new AMap.Map('container', {
    // mask: mask,
    center: defaultCenter,
    // resizeEnable: true,
    disableSocket: true,
    viewMode: '3D',
    showLabel: true,
    // labelzIndex: 110,
    pitch: 8,
    zoom: 11.5,
    // mapStyle: 'amap://styles/darkblue',
    mapStyle: 'amap://styles/3b679a15f448a4740ba2ff7524e1a4ae',
  });
  //与态势标绘冲突 map.on('dblclick', () => {
  //   map.clearMap();
  // });
  
  //绑定radio点击事件
    var radios = document.querySelectorAll("#map-styles input");
	// var radios = document.getElementsByClassName(".input-item");
    radios.forEach(function(ratio) {
      ratio.onclick = setMapStyle;
    });

    function setMapStyle() {
      var styleName = "amap://styles/" + this.value;
      map.setMapStyle(styleName);
    }

  //添加高度面
  map.add(object3Dlayer);
  var height = 0;
  var color = '#99ffff';
  var wall = new AMap.Object3D.Wall({
    path: bounds,
    height: height,
    color: color,
  });
  wall.transparent = true;
  object3Dlayer.add(wall);
  //添加描边
  for (var i = 0; i < bounds.length; i += 1) {
    new AMap.Polyline({
      path: bounds[i],
      strokeColor: '#3edfe1',
      strokeWeight: 5,
	    strokeOpacity: 7,
      map: map,
    });
  }

  // 地图控件
  map.plugin(['AMap.OverView', 'AMap.MapType', 'AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar'], function () {
    // map.addControl(
    //   new AMap.OverView({
    //     // isOpen: true,
    //     // visible: true,
    //     // tileLayer: new AMap.TileLayer({
    //     //   //显示的是google上显示的图层
    //     //   tileUrl: 'http://mt{1,2,3,0}.google.cn/vt/lyrs=m@142&hl=zh-CN&gl=cn&x=[x]&y=[y]&z=[z]&s=Galil', //图块取图地址
    //     // })
    //   }),
    // );
	map.addControl(new AMap.MapType({defaultType: 0 ,showroad: true }));
    map.addControl(new AMap.Scale({ visible: true }));
    map.addControl(new AMap.ToolBar({ position: 'LT', ruler: false, direction: false }));
  });

  // 右键菜单
  //创建右键菜单
  menu = new ContextMenu(map);

  //态势标绘
  var mouseTool = new AMap.MouseTool(map);
  var mouseToolObj = {
    drawMarker: function () {
      //标记
      mouseTool.marker({
        id: 'flag',
        icon: new AMap.Icon({
          size: [128, 128],
          image: 'images/fla01g.png',
          imageSize: [60, 60],
        }),
        zIndex: 9999,
      });
    },
    drawPolyline() {
      //线段
      mouseTool.polyline({
        strokeColor: '#3366FF',
        strokeOpacity: 1,
        strokeWeight: 6,
        strokeStyle: 'solid',
      });
    },
    drawCircle() {
      //圆形
      mouseTool.circle({
        strokeColor: '#FF33FF',
        strokeOpacity: 1,
        strokeWeight: 4,
        fillColor: '#1791fc',
        fillOpacity: 0.4,
        strokeStyle: 'solid',
      });
    },
    drawPolygon() {
      //多边形
      mouseTool.polygon({
        strokeColor: '#0dec66',
        strokeOpacity: 1,
        strokeWeight: 4,
        strokeOpacity: 1,
        fillColor: '#ee6a38',
        fillOpacity: 0.3,
        strokeStyle: 'solid',
      });
    },
    drawRule() {
      //测距
      mouseTool.rule({
        startMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(128, 128),
            imageSize: new AMap.Size(50, 50),
            image: 'images/qi.png',
          }),
          offset: new AMap.Pixel(-25, -50),
        },
        endMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(128, 128),
            imageSize: new AMap.Size(40, 40),
            image: 'images/zhong.png',
          }),
          offset: new AMap.Pixel(-20, -40),
        },
        midMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(128, 128),
            imageSize: new AMap.Size(40, 40),
            image: 'images/jing.png',
          }),
          offset: new AMap.Pixel(-20, -40),
        },
        lineOptions: {
          strokeStyle: 'solid',
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 3,
        },
      });
    },
    drawMeasureArea() {
      //面积
      mouseTool.measureArea({
        strokeColor: '#80d8ff',
        fillColor: '#80d8ff',
        fillOpacity: 0.5,
      });
    },
  };
  var editorObject = {
    editorArr: [],
    tabAct: '',
    toolBoxShow: false,
  };
  MTOOL = {
    toggleTool(wd, _this) {
      $('.toolBar li.bjt').removeClass('cl');
      $(_this).addClass('cl');
      editorObject.tabAct = wd;
      mouseToolObj[wd]();
    },
    getAllDrawLays() {
      let laysArr = map.getAllOverlays(),
        CircleArr = [],
        MarkerArr = [],
        PolylineArr = [],
        PolygonArr = [];
      laysArr.forEach((ele) => {
        if (ele.CLASS_NAME == 'AMap.Circle') CircleArr.push(ele);
        if (ele.CLASS_NAME == 'AMap.Polygon') PolygonArr.push(ele);
        if (ele.CLASS_NAME == 'AMap.Polyline') PolylineArr.push(ele);
        if (ele.CLASS_NAME == 'AMap.Marker' && ele.getzIndex() == 9999) {
          MarkerArr.push(ele);
        }
      });
      let allDrawLays = [...CircleArr, ...MarkerArr, ...PolylineArr, ...PolygonArr];
      return {
        allDrawLays,
        CircleArr,
        MarkerArr,
        PolylineArr,
        PolygonArr,
      };
    },
    editOverlays() {
      let layobj = MTOOL.getAllDrawLays(),
        type = editorObject.tabAct.substring(4);
      switch (type) {
        case 'Circle':
          if (layobj.CircleArr.length > 0)
            layobj.CircleArr.forEach((ele) => {
              let editor = new AMap.CircleEditor(map, ele);
              editor.open();
              editorObject.editorArr.push(editor);
            });
          break;
        case 'Polyline':
          if (layobj.PolylineArr.length > 0)
            layobj.PolylineArr.forEach((ele) => {
              let editor = new AMap.PolyEditor(map, ele);
              editor.open();
              editorObject.editorArr.push(editor);
            });
          break;
        case 'Polygon':
          if (layobj.PolygonArr.length > 0)
            layobj.PolygonArr.forEach((ele) => {
              let editor = new AMap.PolyEditor(map, ele);
              editor.open();
              editorObject.editorArr.push(editor);
            });
          break;
      }
    },
    alertFun(len, type, isedit) {
      let stype = '',
        html = '';
      switch (type) {
        case 'Circle':
          stype = '圆形';
          break;
        case 'Polyline':
          stype = '线段';
          break;
        case 'Polygon':
          stype = '多边形';
          break;
      }
      for (let i = 0; i < len; i++) {
        let lena = i + 1;
        if (isedit) html += `<input name="in" type="radio" onClick="window.clickRadioLays(${lena})"/>第${lena}个${stype} `;
        else html += `<input name="in" type="radio" onClick="window.delRadioLays(${lena})"/>第${lena}个${stype} `;
      }
      layLayer.open({
        content: html,
      });
    },
    endEditOverlays() {
      if (editorObject.editorArr.length > 0) {
        editorObject.editorArr.forEach((ele) => {
          ele.close();
        });
      }
    },
    delAllOverlays() {
      mouseTool.close(true);
      $('.toolBar li.bjt').removeClass('cl');
    },
    endOverlays() {
      mouseTool.close(false);
      $('.toolBar li.bjt').removeClass('cl');
    },
    delOverlays() {
      let layobj = MTOOL.getAllDrawLays(),
        html = '',
        type = editorObject.tabAct.substring(4),
        len = layobj[type + 'Arr'] ? layobj[type + 'Arr'].length : '';
      window.delRadioLays = function (num) {
        map.remove(layobj[type + 'Arr'][num - 1]);
      };
      if (len > 0) MTOOL.alertFun(len, type, false);
    },
  };
});

// 画圆圈
function renderCircle(lnglat, distance) {
  var circle = new AMap.Circle({
    center: lnglat,
    radius: distance,
    borderWeight: 3,
    strokeColor: '#00ff00',
    strokeWeight: 1,
    strokeOpacity: 0.5,
    fillOpacity: 0.1,
    strokeStyle: 'dashed',
    strokeDasharray: [10, 10],
    // 线样式还支持 'dashed'
    fillColor: '#00ff00',
    zIndex: 50,
  });

  circle.on('dblclick', function (e) {
    map.remove(circle);
  });

  circle.setMap(map);
  // 缩放地图到合适的视野级别
  map.setFitView([circle]);
}

// 雷达扫描
var radar;
var buildRadar = function (lnglat, distance) {
  if (!lnglat || !distance) {
    layLayer.alert('参数为空');
  }
  if (radar) {
    object3Dlayer.remove(radar);
  }
  radar = new AMap.Object3D.Mesh();
  radar.transparent = true;
  radar.backOrFront = 'front';

  var geometry = radar.geometry;
  var radius = distance; // 米
  radius = radius / map.getResolution(lnglat, 20);
  var unit = 1;
  var range = 300;
  var count = range / unit;

  for (var i = 0; i < count; i += 1) {
    var angle1 = (i * unit * Math.PI) / 180;
    var angle2 = ((i + 1) * unit * Math.PI) / 180;

    var p1x = Math.cos(angle1) * radius;
    var p1y = Math.sin(angle1) * radius;
    var p2x = Math.cos(angle2) * radius;
    var p2y = Math.sin(angle2) * radius;

    geometry.vertices.push(0, 0, 0);
    geometry.vertices.push(p1x, p1y, 0);
    geometry.vertices.push(p2x, p2y, 0);

    var opacityStart = getOpacity(i / count);
    var opacityEnd = getOpacity((i + 1) / count);

    geometry.vertexColors.push(0.8, 0.2, 0, opacityStart);
    geometry.vertexColors.push(0.8, 0.1, 0, opacityStart);
    geometry.vertexColors.push(0.8, 0.2, 0, opacityEnd);
  }

  radar.position(lnglat);

  object3Dlayer.add(radar);

  map.setFitView();
};

function getOpacity(scale) {
  return 1 - Math.pow(scale, 0.75);
}

function scan() {
  radar.rotateZ(-3);
  AMap.Util.requestAnimFrame(scan);
}

// buildRadar();
// scan();

//自定义菜单类
function ContextMenu(map) {
  var me = this;

  //地图中添加鼠标工具MouseTool插件
  this.mouseTool = new AMap.MouseTool(map);

  this.contextMenuPositon = null;

  var content = [];

  content.push('<div class="layui-card" style="width: 560px;">');
  content.push('<div class="layui-card-header">资源搜索</div>');
  content.push('<div class="layui-card-body">');
  content.push('  <form class="layui-form">');
  content.push('    <div class="layui-form-item">');
  content.push(
    '      <div class="layui-input-inline" style="width: 120px;"><input type="text" name="distance" autocomplete="off" placeholder="范围半径" class="layui-input" onkeyup="this.value=this.value.replace(/[^0-9-]+/,\'\')" /></div>',
  );
  content.push('      <div class="layui-form-mid layui-word-aux">米</div>');
  content.push(
    '      <div class="layui-input-inline"><input type="text" name="keywords" autocomplete="off" placeholder="请输入关键字" class="layui-input" /></div>',
  );
  content.push(
    '      <div class="layui-input-inline" style="width:auto;"><button type="button" onclick="menu.viewResources(this)" class="layui-btn">立即搜索</button><button class="layui-btn layui-btn-danger" type="button" onclick="menu.clearMap()">清屏</button></div>',
  );
  content.push('    </div>');
  content.push('  </form>');
  content.push('</div>');
  content.push('</div>');

  //通过content自定义右键菜单内容
  this.contextMenu = new AMap.ContextMenu({ isCustom: true, content: content.join('') });

  //地图绑定鼠标右击事件——弹出右键菜单
  map.on('rightclick', function (e) {
    me.contextMenu.open(map, e.lnglat);
    me.contextMenuPositon = e.lnglat;
  });
}

ContextMenu.prototype.clearMap = function () {
  map.clearMap();
};

ContextMenu.prototype.viewResources = function (self) {
  this.mouseTool.close();
  // var marker = new AMap.Marker({
  //   map: map,
  //   position: this.contextMenuPositon, //基点位置
  // });
  // console.log(self);
  // console.log(this);

  map.setCenter(this.contextMenuPositon);

  var distance = $(self).closest('form').find('input[name="distance"]').val();
  var keywords = $(self).closest('form').find('input[name="keywords"]').val();

  if (distance >= 1) {
    buildRadar(this.contextMenuPositon, distance);
    scan();
  }

  map.clearMap();

  mapSearch(
    {
      distance: distance / 1000,
      keywords: keywords,
      latitude: this.contextMenuPositon.lat,
      longitude: this.contextMenuPositon.lng,
    },
    () => {
      var searchTimer = setTimeout(() => {
        clearTimeout(searchTimer);
        object3Dlayer.remove(radar);
        renderCircle(this.contextMenuPositon, distance);
      }, 3000);
    },
  );

  this.contextMenu.close();
};

// });
// }

// 加载云台
function loadPTZ(deviceId) {
  PTZ_idx = layLayer.open({
    type: 1,
    title: '云台控制',
    anim: 2,
    shade: false,
    content: $('.controlBtn'),
  });
  $("#controllerDeviceId").val(deviceId);
}

//添加 marker
function addMarker(pois, category, warn) {
  marker[category] = [];

  var pois = pois;
  var centerFlag = true;

  for (var i in pois) {
    var startIcon = new AMap.Icon({
      size: new AMap.Size(32, 32),
      image: './images/legend/' + pois[i]['legendCode'] + '.png',
      imageSize: new AMap.Size(32, 32),
      imageOffset: new AMap.Pixel(0, 0),
    });
    var poiIcon = startIcon;

    if (pois[i].deviceType && pois[i].deviceType === 'q2') {
      poiIcon = new AMap.Icon({
        size: new AMap.Size(32, 32),
        image: './images/legend/' + pois[0]['legendCode'] + '.png',
        imageSize: new AMap.Size(32, 32),
        imageOffset: new AMap.Pixel(0, 0),
      });
    }

    var mk = new AMap.Marker({
      map: map,
      icon: poiIcon,
      offset: new AMap.Pixel(-20, -20),
      position: [pois[i].longitude, pois[i].latitude],
    });
    marker[category].push(mk);

    mk.setLabel({
      offset: new AMap.Pixel(0, -5),
      content: pois[i].aliasName,
      direction: 'top',
    });

    // 地图中心跳转到第一个marker位置
    if (centerFlag) {
      map && map.setCenter([pois[i].longitude, pois[i].latitude]);
      centerFlag = false;
    }
    if (warn) {
      mk.setAnimation('AMAP_ANIMATION_BOUNCE');
    }

    // 鼠标点击marker弹出信息窗体
    listenerMarkerClick(mk, pois[i]);
  }
}

// 监听 marker 点击事件
function listenerMarkerClick(marker, poi) {
  var iMaker = marker;
  var poi = poi;
  AMap.event.addListener(iMaker, 'click', function () {
    // 根据不同分类设备不同操作
    if (poi.showType === '1') {
      if (poi.deviceType === 'q2') {
          console.log(poi,"=============poi==============")
        poi['content'] = `<div class='${poi.legendCode}${poi.id}' style='position:relative'></div>
                                  <div class="layui-layer-btn layui-layer-btn-">
                                    <a class="layui-layer-btn0" onclick="loadPTZ('${poi.resourceNo}')">启动云台控制</a>
                                  </div>`;
      } else {
        poi['content'] = `<div class='${poi.legendCode}${poi.id}' style='position:relative'></div>`;
      }

      createInfoWindow(poi, iMaker.getPosition());
    } else if (poi.showType === '2') {
      poi['content'] = `<form name="myForm">
                          <table>
                            <tr>
                              <th>姓名</th>
                              <td>${poi.fullName}</td>
                            </tr>
                            <tr>
                              <th>单位</th>
                              <td>${poi.contacts}</td>
                            </tr>
                            <tr>
                              <th>电话</th>
                              <td><button class="layui-btn layui-btn-xs" onclick="makeCall(${poi.telephone})">${poi.telephone}</button></td>
                            </tr>
                            <tr>
                              <th>起始时间</th>
                              <td><input type="datetime-local" name="startTime" step="1" ></td>
                            </tr>
                            <tr>
                              <th>结束时间</th>
                              <td><input type="datetime-local" name="endTime" step="1" ></td>
                            </tr>
                          </table>
                          <div class="layui-layer-btn soldierBtn${poi.memId}">
                            <a class="layui-layer-btn0 layui-btn-xs" data-soldierid=${poi.memId} onclick="renderSoldierTrack(this)">轨迹查询</a>
                            <a class="layui-layer-btn0 layui-btn-xs" data-soldierid=${poi.memId} onclick="">入会</a>
                            <a class="layui-layer-btn0 layui-btn-xs btn-callSoldier" data-soldierid=${poi.memId} onclick="callSoldier(this)">呼叫单兵</a>
                          </div>
                        </form>
                        `;
      createInfoWindow(poi, iMaker.getPosition());
    } else if (poi.showType === '3' || poi.showType === '4') {
      renderEnterpriseDeviceData(poi, iMaker.getPosition());
    } else if (poi.showType === '5') {
      createNormalInfoWindow(poi, iMaker.getPosition());
      // renderEnterpriseDeviceData(poi, iMaker.getPosition());
    } /* else {
      createZHDeviceInfoWindow(poi, iMaker.getPosition());
    } */
  });
}

// 清除 marker
function removeMaker(category) {
  if (category) {
    try {
      map.remove(marker[category]);
      closeInfoWindow();
    } catch (err) { }
  } else {
    for (var i in marker) {
      map.remove(marker[i]);
      // $('#legend').find('li').removeClass('selected');
    }
  }
}

// 创建并打开默认信息窗
function createInfoWindow(options, position) {
  if (mulitVideoFlag) {
    if (options.showType === '1') {
      // initVideo(options.legendCode + options.id, options.deviceNo);
      // var timer = setTimeout(() => {
      // $('.mulitVideo').append($('.iframeHandler'));
      // $('.videoHandler').find('.video-main-full').addClass('mode-1').removeClass('mode-4');
      // $('.videoHandler').find('.info').show();
      // console.log(options.resourceNo);
      // videoController.setWindowsNum(16);
      // videoController.playByOrder(options.resourceNo, options.resourceNo, {
      //   name: options.resourceNo,
      // });
        getVideoUrl(options.resourceNo,options.id);
      //$('.iframeHandler').find('iframe').src = "./video/index.html?camNo=" + options.resourceNo + "&name=";
      // clearTimeout(timer);
      // }, 100);
    }
    return;
  }
  var info = [];
  var title = options.fullName ? options.fullName : options.resourceNo ? '编号：' + options.resourceNo : '信息';
  info.push('<div style="padding:7px 0px 0px 0px;"><h4>' + title + '</h4>');
  info.push(options.content);

  if (!infoWindows[options.id]) {
    infoWindows[options.id] = new AMap.InfoWindow({
      anchor: options.anchor ? options.anchor : 'middle-left',
      content: info.join(''),
    });
  }
  infoWindows[options.id].on('open', function (d) {
    if (options.showType === '1') {
      // initVideo(options.legendCode + options.id, options.deviceNo);
      var ele = '.' + options.legendCode + options.id;

      var timer = setTimeout(() => {

          // $('.iframeHandler')&&  $('.iframeHandler').empty();
          $('.iframeHandler').empty();
        $(ele).append($('.iframeHandler'));
        // $('.videoHandler').find('.video-main-full').addClass('mode-1').removeClass('mode-4');
        // $('.videoHandler').find('.info').show();
        // console.log(options.resourceNo);
        // videoController.setWindowsNum(1);
        // videoController.playByOrder(options.resourceNo, options.resourceNo, {
        //   name: options.resourceNo,
        // });
        // console.log(options)
        //getVideoUrl(options.resourceNo);
        getVideoUrl(options.resourceNo,options.id);
        //$('.iframeHandler').find('iframe')[0].src = "./video/index.html?camNo=" + options.resourceNo + "&name=" + encodeURI(encodeURI(options.fullName));
        clearTimeout(timer);
      }, 100);
    }
  });

    infoWindows[options.id].on('close', function () {
        if (options.showType === '1') {
           // $("#player").remove();
            $('.iframeHandler').empty();
           /* player.JS_Stop().then(
                () => { console.log('stop realplay success') },
            e => { console.error(e) }
        )*/
        }
    });

  // infoWindows[options.id].on('close', function (d) {
  //   // 关闭云台控制
  //   videoController && videoController.closeAll();
  //   PTZ_idx && layLayer.close(PTZ_idx);
  //   for (var i in infoWindows) {
  //     infoWindows[i].close();
  //   }
  // });
  infoWindows[options.id].open(map, position);
}

// 关闭信息窗
function closeInfoWindow() {
  if (infoWindows.length > 0) {
    for (var i in infoWindows) {
      infoWindows[i].close();
    }
  }
}

function renderLineArr(arr) {
  var poiIcon = new AMap.Icon({
    size: new AMap.Size(32, 32),
    image: './images/legend/soldier.png',
    imageSize: new AMap.Size(32, 32),
    imageOffset: new AMap.Pixel(0, 0),
  });
  marker = new AMap.Marker({
    position: arr[0],
    icon: './images/legend/soldier.png',
    map: map,
    icon: poiIcon,
    offset: new AMap.Pixel(-20, -20),
  });

  // 绘制轨迹
  var polyline = new AMap.Polyline({
    map: map,
    path: arr,
    showDir: true,
    strokeColor: '#28F', //线颜色
    // strokeOpacity: 1,     //线透明度
    strokeWeight: 6, //线宽
    // strokeStyle: "solid"  //线样式
  });

  var passedPolyline = new AMap.Polyline({
    map: map,
    // path: lineArr,
    strokeColor: '#AF5', //线颜色
    // strokeOpacity: 1,     //线透明度
    strokeWeight: 6, //线宽
    // strokeStyle: "solid"  //线样式
  });

  marker.on('moving', function (e) {
    passedPolyline.setPath(e.passedPath);
  });

  map.setCity('河北省', function(e){
    map.setCenter(arr[0]);
    map.setZoom(13.5);
  });
  map.setFitView();
  marker.moveAlong(arr, 200);
}
//百度坐标转高德（传入经度、纬度）
function bd_decrypt(bd_lng, bd_lat) {
  var X_PI = Math.PI * 3000.0 / 180.0;
  var x = bd_lng - 0.0065;
  var y = bd_lat - 0.006;
  var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
  var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
  var gg_lng = z * Math.cos(theta);
  var gg_lat = z * Math.sin(theta);
  return {lng: gg_lng, lat: gg_lat}
}
