$(function () {
  layui.use(["layer", "table", "element"], function () {
    layLayer = layui.layer;
    layTable = layui.table;
    element = layui.element;

    start();
  });
  var overlays = [],
    isAdd = false;
  function addCircle(lng, lat, radius) {
    //初步研判
    let circle = new AMap.Circle({
      center: new AMap.LngLat(lng, lat), // 圆心位置
      radius: radius, //半径
      strokeColor: "#F33", //线颜色
      strokeOpacity: 1, //线透明度
      strokeWeight: 1, //线粗细度
      fillColor: "#ee2200", //填充颜色
      fillOpacity: 0.35, //填充透明度
    });
    let poiIcon = new AMap.Icon({
      size: new AMap.Size(102, 102),
      image: "./images/flag.png",
      imageSize: new AMap.Size(62, 62),
      imageOffset: new AMap.Pixel(0, 0),
    });
    let marker = new AMap.Marker({
      map: map,
      icon: poiIcon,
      offset: new AMap.Pixel(-20, -20),
      position: [lng, lat],
    });
    overlays.push(circle);
    overlays.push(marker);
    console.log(overlays);
    map.add(overlays);
    isAdd = true;
    map.setFitView([circle]);
  }
  function removeCircle() {
    map.remove(overlays);
    overlays = [];
    isAdd = false;
  }
  var defaultCenter = [114.195771, 38.247808];
  //清除所有覆盖物
  function removeAllOverlay() {
    map.clearMap();
    map.setCenter(defaultCenter);
    $("#legend a").removeClass("selected");
  }
  //搜索按钮
  function getBtmSearchData(param) {
    let opts = {
      url: apis.mapSearch,
      type: "post",
      data: JSON.stringify({ keywords: param }),
      success: function (res) {
        if (res.code === 0) {
          let arr = res.data.pageData;
          if (arr.length > 0) {
            let html = "";
            removeAllOverlay();
            $("#legend li a").removeClass("selected");
            arr.map((ele) => {
              html += `<div class="btm-list-item" data-id="${ele.id}">${ele.fullName}</div>`;
              let ar = [];
              ar.push(ele);
              addMarker(ar, ele.showType, null);
            });
            $("#listWrap").html(html);
            // $('.btm-list-item').click(function(){
            //   let id = $(this).attr('data-id');
            //   let rowobj = arr.filter(ele => ele.id = id)
            //   addMarker(rowobj, rowobj.showType, null)
            // })
          } else {
            $("#listWrap").html(
              '<div class="btm-list-item" style="text-align:center;">无搜索结果！</div>'
            );
          }
        }
      },
    };
    jQueryAjax(opts);
  }
  $(".uative").on("click", function () {
    $("#btmSearch > *").fadeIn(100);
    $(this).hide();
  });
  $(".activebtn").on("click", function (e) {
    let val = $("#btnInput").val();
    getBtmSearchData(val);
  });
  $(".guan").click(function () {
    $("#btmSearch > *").hide();
    $(".uative").show();
  });
  $("#removeSerBtn").click(function () {
    removeAllOverlay();
  });
  $("#mulitVideoBtn").click(function () {
    showMulitVideo();
  });
  $("#btnInput").bind("input", function (e) {
    let val = e.target.value;
    if (!val) {
      $("#listWrap").html("");
      removeAllOverlay();
    }
  });

  // 云台控制
  /*$('.controlBtn .button').click(function () {
    var self = this;
    /!*if (!videoController) {
      return;
    }
    if (videoController.getInChoiceVideo() === undefined) {
      layLayer.msg('请先点击视频以选中');
      return;
    }
    videoController.setChoiceWindow(0);
    videoController.holder($(self).data('action'), { speed: 200, group: 0, present: 0, time: 0 }, false);
    var controlTimer = setTimeout(function () {
      videoController.holder($(self).data('action'), { speed: 200, group: 0, present: 0, time: 0 }, true);
      clearTimeout(controlTimer);
    }, 200);*!/

  });*/

  $(".controlBtn .button").mousedown(function () {
    var self = this;
    console.log(
      $(self).data("action"),
      "dfdf===----------------===============",
      $("#controllerDeviceId").val()
    );
    videoControlling($("#controllerDeviceId").val(), 0, $(self).data("action"));
  });

  $(".controlBtn .button").mouseup(function () {
    var self = this;
    console.log(
      $(self).data("action"),
      "dfdf===----------------===============",
      $("#controllerDeviceId").val()
    );
    videoControlling($("#controllerDeviceId").val(), 1, $(self).data("action"));
  });

  // 鼠标滚动放大缩小
  $(".reset").on("mousewheel DOMMouseScroll", function (e) {
    var delta =
      (e.originalEvent.wheelDelta &&
        (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || // chrome & ie
      (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1)); // firefox

    if (!videoController) {
      return;
    }
    if (videoController.getInChoiceVideo() === undefined) {
      layLayer.msg("请先点击视频以选中");
      return;
    }

    if (delta > 0) {
      // 向上滚
      videoController.setChoiceWindow(0);
      videoController.holder(
        "zoomout",
        { speed: 4000, group: 0, present: 0, time: 0 },
        false
      );
      var mousewheelUpTimer = setTimeout(function () {
        videoController.holder(
          "zoomout",
          { speed: 4000, group: 0, present: 0, time: 0 },
          true
        );
        clearTimeout(mousewheelUpTimer);
      }, 500);
    } else if (delta < 0) {
      // 向下滚
      videoController.setChoiceWindow(0);
      videoController.holder(
        "zoomin",
        { speed: 4000, group: 0, present: 0, time: 0 },
        false
      );
      var mousewheelDownTimer = setTimeout(function () {
        videoController.holder(
          "zoomin",
          { speed: 4000, group: 0, present: 0, time: 0 },
          true
        );
        clearTimeout(mousewheelDownTimer);
      }, 500);
    }
  });

  // 监听图例点击事件
  $("#legend").on("click", function (ev) {
    const target = $(ev.target);
    const li = target.closest("li");
    let isJkelected = $(".layui-layer-btn .jkBtn").hasClass("selected");

    if (isJkelected) {
      removeMaker("jk");
      $(".layui-layer-btn .jkBtn").removeClass("selected");
    }
    // 当点的不是a标签
    if (ev.target.tagName.toLowerCase() !== "a") {
     
      // 根据li的active属性拍判断是否是选中状态，因为初始是undefind 所哟要!!转化为boolea,状态是在点击a标签的时候发生改变的
      // 如果全选了 那li状态就味true，否则都是false
      const aciveFlag = !!li.data("active");
      const clickArr = li.find("a");
      filterClick(clickArr, aciveFlag);

    } else {
      // 当点的是a
      if ($(ev.target)[0].classList.toString().indexOf("selected") === -1) {
        removeMaker($(ev.target).data("id"));
        addCateMarker(
          $(ev.target).data("id"),
          $(ev.target).closest("li").data("id")
        );
      } else {
        removeMaker($(ev.target).data("id"));
      }
      $(ev.target).toggleClass("selected");
      
      // 获取当先元素下的a
      const domArr = $(ev.target).closest(".legendchild").find("a");
      // 计算a是否都被选中
      const selectedFlag = domArr.get().every((item) => {
        return $(item).hasClass("selected");
      });
      // 如果全被选中，就让li状态改为全选，否则状态就是未被全选
      if (selectedFlag) {
        $(ev.target).closest("li").data("active", true);
        li.css({ backgroundImage: "url(images/vectorbot.png)" });

      } else {
        $(ev.target).closest("li").data("active", false);
      }
    }
  });

  // 当点击li时，如果a元素自身场景选择是否被点击，li选中状态的时候，a标签要全都选中，l没被选中的时候，a标签要全部清楚
  function filterClick(clickArr, bool) {
    $.each(clickArr, function (index, ele) {
      if ($(ele).hasClass("selected") == bool) {
        $(ele).click();
      }
    });
  }
  let timer = null;
  let timer2 = null;
  $(".legendcss").on("mouseover", function (ev) {
    const target = $(ev.target);
    // if (target.get(0).tagName == "UL") return;
    const li = target.closest("li");
    // 当被li是被选中状态
    if (li.data("active")) {
    } else {
      // 当li不是选中状态才触发自动换背景颜色
      li.css({ backgroundImage: "url(images/vectorbot.png)" });
      li.data("hover", true);
    }

    const arr = $("#legend").find("li");
    // 全体归位清零
    $.each(arr, function (index, ele) {
      $(ele).children(".legendchild").hide();
    });
    // 当前div出现
    li.find(".legendchild").show();
  });

  $(".legendcss").on("mouseout", function (ev) {
    const target = $(ev.target);

    const li = target.closest("li");
    if (li.data("active")) {
    } else {
      // 当li不是选中状态才触发自动换背景颜色，只有移出的时候才切换北京颜色
      li.css({ backgroundImage: "url(images/re.png)" });
      li.data("hover", false);
    }
    li.find(".legendchild").hide();
  });
  /*全局变量*/
  var currentEventObj = {}; //点击评估处理时当前事件obj
  (currEventsArr = []), //当前事件Arrary
    (getCurrEventsArr = []),
    (socketCurrEventsArr = []),
    (checkEventEype = ""), //回顾事件 review 处理当前 current
    (stepWord = 0); //处理中事件 到了哪一步了 0-3 step
  /*
   * 绑定window操作事件*
   */
  window.CAEVT = {
    //查看预案详情
    check(d) {
      $(".yjdetali").show();
      $(".yjdetali").html(`<h1>${d.planTitle} ${d.planLevel + "级"}</h1>
    <table id="members" lay-filter="members"></table>${d.planContents}`);
      layTable.render({
        elem: "#members",
        size: "sm",
        skin: "nob",
        cols: [
          [{ align: "center", title: "人员列表", colspan: 5 }],
          [
            { field: "deptName", title: "部门" },
            { field: "userName", title: "联系人" },
            { field: "mobilePhone", title: "手机号" },
            { field: "phone", title: "电话" },
            { field: "email", title: "邮箱" },
          ],
        ],
        data: d.rdeptInfoList,
      });
    },
    //查看预案详情
    checkPlan(planid) {
      BOTMTOOLBAR.genericPlan("", planid);
    },
    //关联预案
    connect(d) {
      let obj = {
        planId: d.id,
        eventId: currentEventObj.id,
      };
      layLayer.confirm(`确定关联此预案《${d.planTitle}》吗？`, function () {
        let opt = {
          url: apis.contentPlan,
          type: "post",
          data: JSON.stringify(obj),
          success: function (res) {
            if (res.code == 0) layLayer.msg("关联成功！", { icon: 1 });
            //修改事件状态
            STEPEVENTS.changeStatus("2");
            //关联预案成功跳转到态势决策
            $("#yingjlistbox").hide();
          },
        };
        jQueryAjax(opt);
      });
    },
  };
  var CARYEVENTS = {
    //获取标题
    getMainiTit() {
      let opt = {
        url: apis.getSysTitle,
        success: function (res) {
          if (res.code == 0) {
            if (res.data) {
              $("#mainTitle span").html(res.data.value);
            }
          }
        },
      };
      jQueryAjax(opt);
    },
    //评估处理
    handleEvent(obj) {
      currentEventObj = { ...obj };
      if (obj.eventStatus == 0) STEPEVENTS.changeStatus("1");
      else STEPEVENTS.toStepChange(obj.eventStatus);
    },
    //执行预案
    carryPlanEv() {
      let carryOpt = {
          /* 启动预案 */ url: apis.carryPlan + currentEventObj.id,
          success: function (res) {
            if (res.code == 0) {
              layLayer.msg("启动预案成功！", { icon: 1 });
              STEPEVENTS.changeStatus("3");
            }
          },
        },
        addOpt = {
          /* 增补预案 */ type: "post",
          data: JSON.stringify({
            addPlanContent: $("textarea[name=addPlan]").val(),
          }),
          url: apis.addPlan + currentEventObj.id,
          success: function (res) {
            if (res.code == 0) {
              layLayer.msg("增补预案成功！", { icon: 1 });
              jQueryAjax(carryOpt);
            }
          },
        };
      jQueryAjax(addOpt);
    },
    //弹窗
    tanDialogFun(title, id, addhtml) {
      let defaultHtml = `<div id="${id}" class="fixedbox">
      <div class="fixedbox-tit">${title}<span class="cbtn"><i class="layui-icon layui-icon-close"></i></span></div></div>`;
      if ($(`#${id}`).length == 0) {
        $("body").append(defaultHtml);
        $(`#${id} .fixedbox-tit`).after(addhtml);
        $(`#${id}`).show();
      }
      $("body").on("click", `#${id} .cbtn`, function () {
        $(`#${id}`).remove();
      });
    },
    //查询事件列表
    getEventList() {
      let _this = this,
        opt = {
          url: apis.getEventInfoList,
          success: function (res) {
            if (res.code == 0) {
              let resData = res.data.pageData;
              /* 当前事件 */
              let currarr = resData.newEventList;
              getCurrEventsArr = [...currarr];
              _this.renderEventList();
              /* 历史事件 */
              $(".hisEvNum").html(resData.historyEventNum);
              _this.historyEvent(resData.historyEventList);
            }
          },
        };
      jQueryAjax(opt);
    },
    //渲染当前事件列表
    renderEventList() {
      currEventsArr = [...getCurrEventsArr, ...socketCurrEventsArr];
      $(".currEvNum").html(currEventsArr.length);
      if (getCurrEventsArr.length > 0)
        $(".escbox-txt").html('<font style="color:red">有待处理事件！</font>');
      if (socketCurrEventsArr.length > 0)
        $(".escbox-txt").html('<font style="color:red">发生事件！</font>');
      layTable.render({
        elem: "#currEvents",
        size: "sm",
        cols: [
          [
            { field: "alarmTime", title: "时间" },
            {
              field: "eventName",
              title: "事件名称",
              event: "tanDetail",
              templet: function (d) {
                return `<span style="text-decoration:underline;cursor:pointer">${d.eventName}</span>`;
              },
            },
            {
              field: "",
              title: "操作",
              templet: function (d) {
                let txt;
                if (d.eventStatus == 0) txt = "评估处理";
                else txt = evenStepNameArr[Number(d.eventStatus) - 1];
                return '<span class="txtbtn">' + txt + "</span>";
              },
              event: "handle",
            },
          ],
        ],
        data: currEventsArr,
      });
      layTable.on("tool(currEvents)", function (obj) {
        let rowData = obj.data,
          rowEvent = obj.event;
        if (rowEvent == "handle") {
          //评估处理
          checkEventEype = "current";
          CARYEVENTS.handleEvent(rowData);
        } else if (rowEvent == "tanDetail") {
          let detaliHtml =
            `<div class="eventDeatail">` +
            `<P>事件名称：${rowData.eventName}</p>` +
            `<P>事件等级：${rowData.eventLevel}级</p>` +
            `<P>事发地点：${rowData.eventAddress}</p>` +
            `<P>报案人：${rowData.alarmPeople}</p>` +
            `<P>报案人联系电话：${rowData.alarmPeoplePhone}</p>` +
            `<P>事发时间：${rowData.alarmTime}</p>` +
            `</div>`;
          CARYEVENTS.tanDialogFun("事件详情", "eventDetail", detaliHtml);
        }
      });
    },
    //渲染历史事件列表
    historyEvent(historyList) {
      layTable.render({
        elem: "#esctable",
        size: "sm",
        cols: [
          [
            { field: "alarmTime", title: "时间" },
            {
              field: "eventName",
              title: "事件名称",
              event: "tanDetail",
              templet: function (d) {
                return `<span style="text-decoration:underline;cursor:pointer">${d.eventName}</span>`;
              },
            },
            {
              field: "",
              title: "操作",
              templet: function (d) {
                return '<span class="txtbtn layui-tab layui-tab-brief">回顾</span>';
              },
              event: "review",
            },
          ],
        ],
        data: historyList,
      });
      layTable.on("tool(esctable)", function (obj) {
        let rowData = obj.data,
          rowEvent = obj.event;
        if (rowEvent == "review") {
          $(`#esc-tit`).show();
          $(`#esc-tit .abt`).addClass("done").removeClass("not");
          currentEventObj = { ...rowData };
          checkEventEype = "review";
          STEPEVENTS.switchItem(1);
          // STEPEVENTS.estimateEvent();
        }
        if (rowEvent == "tanDetail") {
          let detaliHtml =
            `<div class="eventDeatail">` +
            `<P>事件名称：${rowData.eventName}</p>` +
            `<P>事件等级：${rowData.eventLevel}级</p>` +
            `<P>事发地点：${rowData.eventAddress}</p>` +
            `<P>报案人：${rowData.alarmPeople}</p>` +
            `<P>报案人联系电话：${rowData.alarmPeoplePhone}</p>` +
            `<P>事发时间：${rowData.alarmTime}</p>` +
            `</div>`;
          CARYEVENTS.tanDialogFun("事件详情", "eventDetail", detaliHtml);
        }
      });
    },
    //事件接报中-scoket
    currEventScoket() {
      let _this = this,
        ws = new WebSocket(iocWsUrl);
      ws.onopen = function () {
        ws.onmessage = function (evt) {
          let reciveObj = JSON.parse(evt.data);
          if (reciveObj.dataType == 3) {
            //评估提交数据
            STEPEVENTS.changeStatus(4);
          } else if (reciveObj.dataType == 2) {
            //事件过程数据
            STEPEVENTS.changeStatus(3);
          } else if (reciveObj.dataType == 1) {
            //当前事件数据
            resobj = reciveObj.param;
            let term = currEventsArr.filter((ele, index) => {
              if (ele.id == resobj.id) ind = index;
              return ele.id == resobj.id;
            });
            if (term.length == 0) {
              socketCurrEventsArr.push(resobj);
            } else {
              currEventsArr.splice(ind, 1, resobj);
            }
            _this.renderEventList();
          }
        };
      };
    },
  };
  /*
   * 处理事件 流程*
   */
  var STEPEVENTS = {
    //初步研判
    estimateEvent() {
      if (checkEventEype == "review") {
        $("#connectPlanBtn").hide();
        $(".resouce").show();
      } else {
        $("#connectPlanBtn").show();
      }
      let obj = { ...currentEventObj };
      /*加载应急资源*/
      function getResource(keywords = "") {
        let opt = {
          type: "post",
          url: apis.mapSearch,
          data: JSON.stringify({
            distance: 3000,
            keywords: keywords,
            latitude: obj.latitude,
            longitude: obj.longitude,
          }),
          success: function (res) {
            let resArr = res.data.numList;
            if (resArr.length > 0) {
              let html = "";
              resArr.map((ele, index) => {
                html += `<p>${ele.legendName}<font class="num">${ele.num}</font></p>`;
              });
              $("#escboxBottomItem1 .resouce .tbl").html(
                '<p>资源名称<font class="num">资源数量</font></p>' + html
              );
            } else {
              $("#escboxBottomItem1 .resouce .tbl").html("暂无资源！");
            }
          },
        };
        jQueryAjax(opt);
      }
      /*标注地图资源*/
      function maps() {
        map.clearMap();
        buildRadar([obj.longitude, obj.latitude], 3000);
        scan();
        mapSearch(
          {
            distance: 3000,
            keywords: "",
            latitude: obj.latitude,
            longitude: obj.longitude,
          },
          () => {
            var searchTimer = setTimeout(() => {
              clearTimeout(searchTimer);
              object3Dlayer.remove(radar);
              renderCircle([obj.longitude, obj.latitude], 3000);
              addFlag();
            }, 3000);
          },
          "close"
        );
      }
      /*加中心点旗帜*/
      function addFlag() {
        let overlays = [],
          poiIcon = new AMap.Icon({
            size: new AMap.Size(102, 102),
            image: "./images/flag.png",
            imageSize: new AMap.Size(100, 100),
            imageOffset: new AMap.Pixel(0, 0),
          });
        let marker = new AMap.Marker({
          map: map,
          icon: poiIcon,
          offset: new AMap.Pixel(-20, -20),
          position: [obj.longitude, obj.latitude],
        });
        overlays.push(marker);
        map.add(overlays);
      }
      getResource();
      maps();
    },
    //态势决策
    carryPlan() {
      let html = "",
        _this = this,
        opt = {
          /* 查询已关联预案 */ url: apis.searchEventPlan + currentEventObj.id,
          success: function (res) {
            if (res.code == 0) {
              if (res.data.length > 0) {
                let obj = res.data[0];
                html =
                  `<p style="text-decoration: underline;cursor:pointer;" onclick="window.CAEVT.checkPlan(&quot;${obj.planId}&quot;)">预案标题：${obj.planTitle}</p>` +
                  `<p>预案等级：${obj.planLevel}级</p>` +
                  `<p>所属部门：${obj.deptName}</p>`;
                if (checkEventEype == "review") {
                  html += `<p>增补预案内容：${obj.addPlanContent}</p>`;
                  $("#addPlan, #carryPalnBtn").hide();
                } else {
                  $("#addPlan, #carryPalnBtn").show();
                }
                $(".item2 .cn").html(html);
              }
            }
          },
        };
      $("body").on("click", "#carryPalnBtn", function () {
        layLayer.confirm(`确定启动预案吗？`, function () {
          CARYEVENTS.carryPlanEv();
        });
      });
      jQueryAjax(opt);
    },
    //事件处理过程
    eventCirculate() {
      let html = "",
        opt = {
          url: apis.checkCirculate + currentEventObj.id,
          success: function (res) {
            if (res.code == 0) {
              if (res.data.length > 0) {
                res.data.map((ele, inde) => {
                  let date = ele.handleTime.substring(0, 10),
                    time = ele.handleTime.substring(11, 16);
                  html += `<li><p>${date}<br><span>${time}</span></p><div class="con">${
                    inde + 1 + "."
                  } ${ele.handleContent}</div></li>`;
                });
                $("ul.timeLine").html(html);
                $(`#esc-tit .abt:eq(2)`).addClass("done");
              } else {
                $("ul.timeLine").html("暂无处理过程！");
              }
            }
          },
        };
      jQueryAjax(opt);
    },
    //事件评估
    eventEvaluate() {
      let opt = {
        url: apis.eventEvaluateInfo + currentEventObj.id,
        success: function (res) {
          if (res.code == 0) {
            if (res.data && res.data.evaluateContent) {
              $("#evaluatCon").html(res.data.evaluateContent);
              $(`#esc-tit .abt:eq(3)`).addClass("done");
            } else {
              $("#evaluatCon").html("暂无评估内容！");
            }
          }
        },
      };
      jQueryAjax(opt);
    },
    //修改事件状态
    changeStatus(step, EventId = null) {
      let _this = this,
        opt = {
          url:
            apis.changeStatus +
            `${EventId == null ? currentEventObj.id : EventId}/${step}`,
          success: function (res) {
            if (res.code == 0 && EventId == null) {
              _this.toStepChange(step); //跳转
              if (step == 1) {
                let index = socketCurrEventsArr.findIndex(
                  (ele) => ele.id == currentEventObj.id
                );
                socketCurrEventsArr.splice(index, 1);
              }
              CARYEVENTS.getEventList(); //刷新列表
            }
          },
        };
      jQueryAjax(opt);
    },
    //流程跳转
    toStepChange(toIndex) {
      /* 参数 1:初步研判-4 */
      let _this = this;
      toIndex = Number(toIndex);
      $(`.escbox-bottom, #esc-tit`).show();
      $(`#esc-tit .abt`).addClass("not").removeClass("done");
      if (toIndex > 0) {
        let num = toIndex - 1;
        while (num > 0) {
          num--;
          $(`#esc-tit .abt:eq(${num})`).addClass("done");
        }
      }
      $(`#esc-tit .abt:eq(${toIndex - 1})`).removeClass("not");
      $(`.escbox-bottom .item${toIndex}`).show().siblings().hide();
      _this.switchItem(toIndex);
    },
    //获取相应item的内容
    switchItem(toIndex) {
      let _this = this;
      $(`.escbox-bottom .item${toIndex} h3`).html(
        `事件名称：${currentEventObj.eventName}`
      );
      switch (toIndex) {
        case 1:
          _this.estimateEvent();
          break;
        case 2:
          _this.carryPlan();
          break;
        case 3:
          _this.eventCirculate();
          break;
        case 4:
          _this.eventEvaluate();
          break;
      }
    },
  };
  /*
   * 底部ToolBar*
   */
  var cont = 0;
  var heatmap;
  marker["heatmk"] = [];
  var BOTMTOOLBAR = {
    //GIS调度
    eventDevelopAnalysis() {
      /*removeAllOverlay();
      map.setCenter([114.195771, 38.247808]);
      $('#legend a').removeClass('selected');*/

      if (cont == 0) {
        this.initEventDevelope();
        cont++;
      } else {
        cont = 0;
        heatmap.hide();
        map.remove(marker["heatmk"]);
        map.setZoom(11);
      }
    },
    //查询事件列表
    getHeatmap() {
      var data = {};
      if ("year" == $("#choiceTime input[type = 'radio']:checked").val()) {
        if (0 == $("#sel_year").val() || "" == $("#sel_year").val()) {
          layLayer.alert("请选择年份！");
          return;
        }
        data.year = $("#sel_year").val();
      } else {
        if (
          0 == $("#sel_year").val() ||
          "" == $("#sel_year").val() ||
          00 == $("#sel_month").val() ||
          "" == $("#sel_month").val()
        ) {
          layLayer.alert("请选择年月！");
          return;
        }
        if ($("#sel_month").val() < 10) {
          data.yearAndMonth =
            $("#sel_year").val() + "-0" + $("#sel_month").val();
        } else {
          data.yearAndMonth =
            $("#sel_year").val() + "-" + $("#sel_month").val();
        }
      }
      if (heatmap) {
        heatmap.hide();
        map.remove(marker["heatmk"]);
      }
      let _this = this,
        opt = {
          url: apis.getEventInfoList,
          data: data,
          success: function (res) {
            if (res.code == 0) {
              let resData = res.data.pageData;
              let history = resData.historyEventList;
              let data = [];
              for (var i = 0; i < history.length; i++) {
                let location = {};
                location.lat = history[i].latitude;
                location.lng = history[i].longitude;
                location.count = 50;
                data.push(location);
                //_this.estimateEvent(aa[i]);
                var poiIcon = new AMap.Icon({
                  size: new AMap.Size(0, 0),
                });
                var heatmk = new AMap.Marker({
                  map: map,
                  icon: poiIcon,
                  offset: new AMap.Pixel(-20, -20),
                  position: [history[i].longitude, history[i].latitude],
                });
                marker["heatmk"].push(heatmk);
                heatmk.setLabel({
                  offset: new AMap.Pixel(0, -5),
                  content: history[i].eventName,
                  direction: "top",
                });
              }
              map.plugin(["AMap.Heatmap"], function () {
                //初始化heatmap对象
                heatmap = new AMap.Heatmap(map, {
                  radius: 27, //给定半径
                  opacity: [0, 0.8],
                  gradient: {
                    0.5: "#8CFC0A",
                    0.8: "yellow",
                    1.0: "red",
                  },
                });
                heatmap.setDataSet({
                  data: data,
                  max: 100,
                });
              });
              map.setZoom(12);
            }
          },
        };
      jQueryAjax(opt);
    },
    //初始化事态查询
    initEventDevelope() {
      var date = new Date();
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      var nowTime = "" + y + "-0" + m + "-" + d;
      var detaliHtml =
        '<div style="width: 570px;height: 200px;margin: 23px;" id="choiceTime">' +
        '<div style="height: 30px;">' +
        "<div>" +
        '<input name="data" type="radio" style="float: left;position: relative;top: 3px;" value="year" checked/>' +
        '<p style="float: left; margin-left: 5px;">年份</p>' +
        " </div>" +
        "<div>" +
        '<input name="data" type="radio" style="float: left;margin-left: 50px;position: relative;top: 3px;" value="month"/>' +
        '<p style="margin-left: 5px;">月份</p>' +
        " </div>" +
        "</div>" +
        ' <p style="float: left;height: 30px;line-height: 30px;">年份：</P>' +
        '<select id="sel_year" style="float: left;position: relative;top: 6px;width: 73px;border: 1px solid #708090;border-radius: 2px;"></select>' +
        ' <p style="float: left;margin-left: 45px;height: 30px;line-height: 30px;">月份：</P>' +
        '<select id="sel_month" style="position: relative;top: -5px;width: 60px;border: 1px solid #708090;border-radius: 2px;"></select>' +
        '<button id="eventBtn" style="position: relative;top: 81px;left: -61px;background-color: #4476a7;color: white;width: 157px;height: 43px;border-radius: 5px;">事态分析查询</button>' +
        "</div>";
      CARYEVENTS.tanDialogFun("事态分析", "qqfdsf", detaliHtml);
      $.ms_DatePicker({
        YearSelector: ".sel_year",
        MonthSelector: ".sel_month",
        DaySelector: ".sel_day",
      });
      $.ms_DatePicker();

      if ("year" == $("#choiceTime input[type = 'radio']:checked").val()) {
        $("#sel_month").attr("disabled", "disabled");
      }
      $("#choiceTime input[type = 'radio']").click(function () {
        if ("year" == $(this).val()) {
          $("#sel_month").attr("disabled", "disabled");
        } else {
          $("#sel_month").removeAttr("disabled");
        }
      });

      $("#eventBtn").click(function () {
        BOTMTOOLBAR.getHeatmap();
      });
    },
    //值守通讯
    dutyBookFun() {
      CARYEVENTS.tanDialogFun(
        "值守通讯录",
        "dutyBooklist",
        '<div id="Booklist"></div>'
      );
      layTable.render({
        elem: "#Booklist",
        url: iocUrl + "/frontApi/getDutyContactsList",
        method: "get",
        cols: [
          [
            { field: "deptName", title: "部门", align: "center" },
            { field: "userName", title: "姓名", align: "center" },
            {
              field: "sex",
              title: "姓别",
              align: "center",
              templet: function (obj) {
                return obj.sex == 1 ? "男" : "女";
              },
            },
            { field: "mobliePhone", title: "手机号", align: "center" },
            { field: "phone", title: "座机", align: "center" },
            { field: "email", title: "邮箱", align: "center" },
          ],
        ],
      });
    },
    //事件接报
    // eventReciev() {
    //   CARYEVENTS.tanDialogFun('事件接报', 'eventslistbox', '<div class="frame"></div>');
    //   $('#eventslistbox .frame').html('<img onclick="openhtml()" src="../ioc_frontweb/images/eventPic.jpg" width="100%" alt="" />');
    //   window.openhtml = function () {
    //     $('#eventslistbox .frame').html('<iframe src="http://192.168.2.18:8089/EventsMg" scorlling="no" width="800" height="500"></iframe>');
    //   };
    // },
    //事件回顾
    EventReview() {
      $(".escbox-top").show();
      element.tabChange("layTAb", "layTAb_hisy");
    },
    //综合保障
    guaranteeFun() {
      let opt = {
        url: iocUrl + "/frontApi/getSecurityInfoNum",
        success: function (res) {
          let html = "";
          CARYEVENTS.tanDialogFun(
            "综合保障",
            "ensurelistbox",
            '<div id="numbox" class="xstty"></div><div id="ensurelist"></div>'
          );
          if (res.data.length > 0) {
            res.data.map((ele) => {
              html += `<div class="item" data-code="${ele.legendCode}"><span class="itemTitle">${ele.legendAliasName}</span>&ensp;<span class="num">${ele.num}</span></div>`;
            });
            $("#numbox").html(html);
            $("body").on("click", ".xstty .item", function () {
              $("#ensurelistbox .layui-table-view").show();
              $(this).addClass("active").siblings().removeClass("active");
              let lcode = $(this).attr("data-code");
              layTable.render({
                elem: "#ensurelist",
                url: iocUrl + `/frontApi/getSecurityInfoList/${lcode}`,
                method: "get",
                cols: [
                  [
                    { field: "fullName", title: "名称", align: "center" },
                    { field: "contacts", title: "联系人", align: "center" },
                    { field: "telephone", title: "电话", align: "center" },
                    { field: "address", title: "地址", align: "center" },
                    { field: "introduce", title: "介绍", align: "center" },
                  ],
                ],
              });
            });
          } else {
            $("#numbox").html("无记录！");
          }
          $("#ensurelistbox").show();
        },
      };
      jQueryAjax(opt);
    },
    //知识库
    // konwlegeFun() {
    //   $('#zsbox').show(function () {
    //     layTable.render({
    //       elem: '#zslist',
    //       size: 'sm',
    //       cols: [
    //         [
    //           { field: 'decr', title: '类型' },
    //           { field: 'mc', title: '名称' },
    //           { field: 'dw', title: '状态' },
    //           { field: 'time', title: '时间' },
    //           {
    //             field: '',
    //             title: '详情',
    //             templet: function (d) {
    //               return '<span class="txtbtnca">查看</span>';
    //             },
    //           },
    //         ],
    //       ],
    //       data: [{ dw: '已广播', time: '2020-03-01', decr: '防火', mc: '春季防火' }],
    //       done: function () {
    //         $('body').on('click', '.txtbtnca', function () {
    //           $('.zsdetali').show();
    //         });
    //       },
    //     });
    //   });
    // },
    //应急预案
    genericPlan(key = "", planID = "") {
      function getPlansli() {
        let opt = {
          type: "post",
          url: apis.plansGetList,
          data: JSON.stringify({
            page: 1,
            size: 1000,
          }),
          success: function (res) {
            let Arr = res.data.pageData,
              resArr;
            if (planID != "") resArr = Arr.filter((ele) => ele.id == planID);
            else resArr = [...Arr];
            if (resArr.length > 0) {
              layTable.render({
                elem: "#yingjlist",
                size: "sm",
                cols: [
                  [
                    { field: "deptName", title: "所属单位" },
                    { field: "planTitle", title: "预案标题" },
                    {
                      field: "planLevel",
                      title: "预案登记",
                      templet: function (d) {
                        return d.planLevel + "级";
                      },
                    },
                    {
                      field: "",
                      title: "操作",
                      templet: function (d) {
                        let s;
                        if (key == "gl") {
                          s = `<span class="txtbtn yjck" onclick="window.CAEVT.check(${JSON.stringify(
                            d
                          ).replace(
                            /"/g,
                            "&quot;"
                          )})">查看</span>&nbsp;&nbsp;<span class="txtbtn glya" onclick="window.CAEVT.connect(${JSON.stringify(
                            d
                          ).replace(/"/g, "&quot;")})">关联预案</span>`;
                        } else if (planID != "") {
                          s = `<span class="txtbtn yjck" onclick="window.CAEVT.check(${JSON.stringify(
                            d
                          ).replace(/"/g, "&quot;")})">详情</span>`;
                        } else {
                          s = `<span class="txtbtn yjck" onclick="window.CAEVT.check(${JSON.stringify(
                            d
                          ).replace(/"/g, "&quot;")})">查看</span>`;
                        }
                        return s;
                      },
                    },
                  ],
                ],
                data: resArr,
              });
            }
          },
        };
        jQueryAjax(opt);
      }
      CARYEVENTS.tanDialogFun(
        "应急预案",
        "yingjlistbox",
        '<div id="yingjlist"></div><div class="yjdetali detali"></div>'
      );
      $("#yingjlistbox").addClass("yjbs");
      getPlansli();
    },
  };

  // $('#bottomMenu').click(function() {
  //   layLayer.alert('此功能正在开发中...');
  // });

  $(document).ready(function () {
    function defalutMApP() {
      cont = 0;
      map.clearMap();
      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",
        });

        //添加描边
        for (var i = 0; i < bounds.length; i += 1) {
          new AMap.Polyline({
            path: bounds[i],
            strokeColor: "#22eae4",
            strokeWeight: 5,
            strokeOpacity: 7,
            map: map,
          });
        }
      });

      $("#esc-tit , .escbox-bottom, .escbox-bottom .item").hide();
      $(".abt").addClass("not").removeClass("done");
    }
    $(".escTitClose").click(function () {
      // defalutMApP();
      $("#esc-tit ").hide();
    });
    $(".closeBtn").click(function () {
      $(".escbox-top,.escbox-bottom,#esc-tit").hide();
      defalutMApP();
    });
    $(".escbox-tip-b .item").click(function () {
      let inde = $(this).index(".escbox-tip-b .item");
      $(".escbox-top").show();
      element.on("tab(layTAb)", function (data) {
        defalutMApP();
      });
      if (inde == 0) element.tabChange("layTAb", "layTAb_curr");
      if (inde == 1) element.tabChange("layTAb", "layTAb_hisy");
    });
    //关联按钮事件
    $("body").on("click", "#connectPlanBtn", function () {
      BOTMTOOLBAR.genericPlan("gl");
    });
    $("#bottomMenu .btn").click(function () {
      let inde = $(this).index("#bottomMenu .btn");
      //if (inde == 0) BOTMTOOLBAR.GISFun();
      if (inde == 0) BOTMTOOLBAR.eventDevelopAnalysis();
      if (inde == 1) BOTMTOOLBAR.dutyBookFun();
      // if (inde == 2) BOTMTOOLBAR.eventReciev();
      if (inde == 2) BOTMTOOLBAR.EventReview();
      if (inde == 3) BOTMTOOLBAR.guaranteeFun();
      if (inde == 4) BOTMTOOLBAR.genericPlan();
      // if (inde == 6) BOTMTOOLBAR.konwlegeFun();
    });
    $("body").on("click", ".cbtn", function () {
      let id = $(this).parent().parent().attr("id");
      $(`#${id}`).hide();
      if (id == "ensurelistbox") $("#ensurelistbox .layui-table-view").hide();
      if (id == "zsbox") $(".yjbs .detali").hide();
    });
    $(".ty")
      .find("a.abt")
      .click(function () {
        if (checkEventEype == "review") {
          let ind = $(this).index("a.abt");
          $(".escbox-bottom").show();
          $(`.escbox-bottom .item${ind + 1}`)
            .show()
            .siblings()
            .hide();
          STEPEVENTS.switchItem(ind + 1);
        } else {
          return;
        }
      });
  });

  $("#mouseToolBtn").click(function () {
    $(".toolsbox").show("fast");
  });
  $(".toolsbox h3 span").click(function () {
    $(".toolsbox").hide();
  });

  // 启动
  function start() {
    CARYEVENTS.getEventList();
    CARYEVENTS.currEventScoket();
    CARYEVENTS.getMainiTit();
    login();
    // renderMap();
    createLegendList();
    // renderAlarmNum();
    renderEventNum();
    createDeviceNumPieChart("deviceNumPie");
    createDeviceNumLineChartday("deviceNumLineday");
    createDeviceNumLineChartmouth("deviceNumLinemouth");
    renderLegendTypeNum("categoryAlarmNum");
    initVideo("videoHandler");
    getAlarmData();
    //调用当前值班信息接口
    getDutyInfo();
    // showMulitVideo();

    // 连接 websocket
    ws = new App.NewSocket({
      url: wsUrl,
      onmessageHandle: function (resData) {
        reciveWsMessage(resData);
      },
    });
  }
});
