// var videoPlatUrl = 'http://27.128.189.131:8089';
// var apiUrl = 'http://47.104.61.232:8902';
// var pushUrl = 'http://47.104.61.232:8905';
// var wsUrl = 'ws://47.104.61.232:8905/iocdata/websocket';
// var iocUrl = 'http://47.104.61.232:8902/ioc';
// var iocWsUrl = 'ws://47.104.61.232:8902/ioc/websocket';

var videoPlatUrl = 'http://27.128.189.131:8089';
var apiUrl = 'http://36.148.23.59:8901';
var pushUrl = 'http://36.148.23.59:8901';
var wsUrl = 'ws://36.148.23.59:8901/iocdata/websocket';
var iocUrl = 'http://36.148.23.59:8901/ioc';
var iocWsUrl = 'ws://36.148.23.59:8901/ioc/websocket';


// var apiUrl = 'http://localhost:8902';
// var pushUrl = 'http://localhost:8905';
// var wsUrl = 'ws://localhost:8905/iocdata/websocket';
// var iocUrl = 'http://localhost:8902/ioc';
// var iocWsUrl = 'ws://localhost:8902/ioc/websocket';



// var iocUrl = 'http://192.168.1.188:8902/ioc'
// var wsUrl = 'ws://47.104.61.232:8902/ioc/websocket';
// var videoPlatUrl = 'http://27.128.189.131:8089';

var App = window.App;
var mulitVideoFlag = false;

var map;
var ws;
var PTZ_idx;
var heartTime;
var callingSoldier;
var soldierStatus;
var marker = {};
var videoController = {};
var infoWindows = {};
var myEcharts = [];
var layLayer;
var layTable;

// 接口地址
var apis = {
	getDutyInfo:iocUrl + '/onDutyInfo/getCurrentOnDutyInfo',
  pushAlarmData: pushUrl + '/iocdata/zhDeviceInfo/pushAlarmData',
  getAlarmData: pushUrl + '/iocdata/zhDeviceInfo/getAlarmData',
  getLegendInfoList: apiUrl + '/ioc/frontApi/getLegendInfoList',
  getMapData: apiUrl + '/ioc/frontApi/getMapData',
  getZHDeviceData: apiUrl + '/ioc/frontApi/getZHDeviceData',
  // getEnterpriseDeviceDataByEnterpriseId: apiUrl + '/ioc/frontApi/getEnterpriseDeviceDataByEnterpriseId',
  // getDeviceNum: apiUrl + '/ioc/frontApi/getDeviceNum',
  getEventsNum: apiUrl + '/ioc/frontApi/getEventsNum',
  getDeviceReportDatasNum: apiUrl + '/ioc/frontApi/getDeviceReportDatasNum',
  getSoldierTrackBySoldierId: apiUrl + '/ioc/frontApi/getSoldierTrackBySoldierId',
  getEventNum: apiUrl + '/ioc/frontApi/getEventNum',
  getLegendTypeNum: apiUrl + '/ioc/frontApi/getLegendTypeNum',
  getEnterpriseDeviceInfoById: apiUrl + '/ioc/frontApi/getEnterpriseDeviceInfoById',
  getEnterpriseDeviceListById: apiUrl + '/ioc/frontApi/getEnterpriseDeviceListById',
  getEnterpriseCameraById: apiUrl + '/ioc/frontApi/getEnterpriseCameraById',
  getEleDeviceInfoListByUserId: apiUrl + '/ioc/frontApi/getEleDeviceInfoListByUserId',
  mapSearch: apiUrl + '/ioc/frontApi/mapSearch',
  getPreviewURLs: apiUrl + '/ioc/artemis/getPreviewURLs',
  videoControlling: apiUrl + '/ioc/artemis/videoControlling',
  scooper: {
    cometd: videoPlatUrl + '/scooper-msg-queue/cometd',
    queryGisTrails: videoPlatUrl + '/scooper-app-msg/gis/queryGisTrails',
    loginTo: videoPlatUrl + '/scooper-core-rest/data/system/authManage/loginTo',
    heartbeat: videoPlatUrl + '/scooper-core-rest/data/system/authManage/heartbeat',
    logout: videoPlatUrl + '/scooper-core-rest/data/system/authManage/logout',
    makeCall: videoPlatUrl + '/dispatch-web/api/call/makeCall',
    makeVideoCall: videoPlatUrl + '/dispatch-web/api/call/makeVideoCall',
    hangup: videoPlatUrl + '/dispatch-web/api/call/hungup',
    answer: videoPlatUrl + '/dispatch-web/api/call/answer',
    hold: videoPlatUrl + '/dispatch-web/api/call/hold',
    unhold: videoPlatUrl + '/dispatch-web/api/call/unhold',
    transfer: videoPlatUrl + '/dispatch-web/api/call/transfer',
    retrieve: videoPlatUrl + '/dispatch-web/api/call/retrieve',
    tripleBreakin: videoPlatUrl + '/dispatch-web/api/call/tripleBreakin',
    tripleHungup: videoPlatUrl + '/dispatch-web/api/call/tripleHungup',
    tripleMonitor: videoPlatUrl + '/dispatch-web/api/call/tripleMonitor',
    groupNotify: videoPlatUrl + '/dispatch-web/api/call/groupNotify',
    queryGroupNotifyResult: videoPlatUrl + '/dispatch-web/api/call/queryGroupNotifyResult',
    queryCallRecord: videoPlatUrl + '/dispatch-web/api/call/queryCallRecord',
    telsStatus: videoPlatUrl + '/dispatch-web/api/call/telsStatus',
  },
  plansGetList: iocUrl + '/frontApi/getPlanInfoList',
  contentPlan: iocUrl + '/frontApi/addEventPlanRelation',
  searchEventPlan: iocUrl + '/frontApi/getEventPlanInfoListByEventId/',
  addPlan: iocUrl + '/frontApi/addPlanContent/',
  carryPlan: iocUrl + '/frontApi/startEventPlanById/',
  checkCirculate: iocUrl + '/frontApi/getEventHandleProcessListByEventId/',
  eventEvaluateInfo: iocUrl + '/frontApi/getEventEvaluateInfoByEventId/',
  changeStatus: iocUrl + '/frontApi/editEventStatusByEventId/',
  getEventInfoList: iocUrl + '/frontApi/getEventInfoList',
  getSysTitle: iocUrl + '/frontApi/getSysTitle',
};

// 信息窗设备参数名称
var deviceReportName = {
  deviceName: '设备名称',
  deviceIp: '设备ip',
  address: '设备地址',
  contacts: '联系人',
  telephone: '联系电话',
  deviceType: '设备类型id',
  categoryName: '类型名称',
  deviceNo: '设备编号',
  reportValue: '上报数值',
  zhHostStatusId: '主机状态id',
  hostStatusName: '主机状态',
  deviceStatusId: '设备状态id',
  deviceStatusName: '设备状态',
  reportTime: '上报时间',
};

// getMapData key
var mapDataKey = {
  fullName: '名称',
  contacts: '联系人',
  telephone: '联系电话',
  address: '地址',
  introduce: '简介',
  // longitude: '经度',
  // latitude: '纬度',
};

// 智能用电设备信息窗名称
var eleDeviceReportName = {
  userId: '设备编号',
  deviceName: '设备名称',
  address: '设备地址',
  number: '设备编号',
  // 0正常1故障2报警
  deviceStatus: '设备状态',
  deviceTypeName: '状态类型名称',
  deviceModel: '产品型号',
};

// 报警信息名称
var eventNum = {
  eventTotal: '事件总数',
  handledNum: '已处理',
  noHandledNum: '待处理',
};

// 企业监测设备列表表头
var enterpriseDeviceInfo = {
  legendId: 'legendId',
  deviceType: '设备类型',
  deviceNum: '设备数量',
  onLineNum: '在线设备',
  offLineNum: '离线设备',
  historyAlarmNum: '历史报警',
  cancelAlarmNum: '已处理报警',
  processingAlarmNum: '报警中',
};

//事件处理步骤名称
var evenStepNameArr = ['初步调研', '态势决策', '事件处理', '事后评估'];

// 生成设备数量堆积图
function createBarChart(options) {
  var option = {
    name: options.name,
    eleId: options.eleId,
    opts: {
      tooltip: {
        formatter: '{a}: {c}',
      },
      grid: {
        left: 0,
        right: 0,
        bottom: 0,
        top: 0,
      },
      xAxis: {
        show: false,
      },
      yAxis: {
        show: false,
        data: ['数量'],
      },
      series: options.series,
    },
  };
  createEchart(option);
}

// 生成不同类型设备报警数量图  应急资源监控
function createDeviceAlarmNumBarChart(options) {
  var option = {
    name: options.name,
    eleId: options.eleId,
    opts: {
      color: ["#FDF070", "#E8F2EE", "#50B06B","#F18231", "#009CF3", "#76D5F4"],
      title: {
        left: 'left',
        textStyle: {
          color: '#fff',
          fontSize: '20',
          lineHeight: '36',
        },
      },
      // tooltip: {
      //   trigger: 'item'
      // },
	   toolbox: {
	      show: true,
	      feature: {
	        mark: { show: true },
	        // dataView: { show: true, readOnly: false },
	        // restore: { show: true },
	        // saveAsImage: { show: true }
	      }
	    },
      series: [
        {
          name: 'Access From', 
          type: 'pie',
          radius: ["80%", "70%"],
          // center: ["50%", "50%"],
          itemStyle: {
            borderRadius: 20,
          },
          label: {
            normal: {
              show: false,
              textStyle: {
                fontSize: 13,
              },
              position: "outside",
            },
            emphasis: {
              show: false,
            },
          },
          labelLine: {
            normal: {
              show: false,
              length: 20,
              length2: 35,
            },
            emphasis: {
              show: true,
            },
          },
          data: options.seriesData,
        },
        // {
        //   name: "外边框",
        //   type: "pie",
        //   clockWise: false, //顺时加载
        //   hoverAnimation: false, //鼠标移入变大
        //   center: ["50%", "50%"],
        //   radius: ["80%", "80%"],
        //   label: {
        //     normal: {
        //       show: false,
        //     },
        //   },
        //   data: [
        //     {
        //       value: 9,
        //       name: "",
        //       itemStyle: {
        //         normal: {
        //           borderWidth: 2,
        //           borderColor: "#61bad3",
        //         },
        //       },
        //     },
        //   ],
        // },
      ],
    },
  };

  createEchart(option);
}

// 创建环形 chart
function createPieChart(options) {
  var opts = {
    name: options.name,
    eleId: options.eleId,
    opts: {
      title: {
        left: 'left',
        textStyle: {
          color: '#fff',
          fontSize: '20',
          lineHeight: '36',
        },
      },
      // tooltip: {
      //   trigger: 'item'
      // },
	   toolbox: {
	      show: true,
	      feature: {
	        mark: { show: true },
	        // dataView: { show: true, readOnly: false },
	        // restore: { show: true },
	        // saveAsImage: { show: true }
	      }
	    },
      series: [
        {
		  // name: 'Nightingale Chart', 
		  type: 'pie',
		  // radius: [15, 80],
      center: ['50%', '50%'],
      label : {
  　　　　normal : {
  　　　　　　formatter: '{b} {c}',
  　　　　　　textStyle : {
  　　　　　　　　fontWeight : 'normal',
  　　　　　　　　fontSize : 14
  　　　　　　}
  　　　　}
  　　},
		  roseType: 'area',
		  itemStyle: {
			borderRadius: 8
		  },
		   data: options.seriesData,
		}
      ],
	
    },
  };
  createEchart(opts);
}

// 创建折线chart
function createLineChartday(options) {
  var opts = {
    name: options.name,
    eleId: options.eleId,
    opts: {
		grid:{
			x:50,
			y:10,
			x2:20,
			y2:60,
      borderWidth:1,
      top: '10%',			
			bottom:'35%'
		},
      xAxis: {
          type: 'category',
          data: options.xAxisData,
          // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          axisLabel: {
            textStyle: {
              color: '#ddd',
            },
          rotate: 60,
          },
            },
            yAxis: {
              type: 'value',
          axisLabel: {
            textStyle: {
              color: '#ddd',
            fontSize:'14',
            },
          },
        },
        series: [
          {
            data: options.seriesData,
            // data: [50, 200, 150, 80, 70, 110, 130],
            type: 'bar',
            markPoint: {
              symbol:'image://../ioc_frontweb/images/gr.svg',//url替换成你的图片地址
              symbolSize:15,//图片大小
              symbolOffset:[0,'-50%'],//图片相对于柱形图x,y轴偏移量，注意要往上移y要是负的
              data:[{
                  coord:[0,40]//需要展示图片的柱型索引，y轴的value
              }],
              label:{
                  show:false,//顶部默认会展示y轴的值，可以设置false,不展示
              }
            },
            barWidth: 8, //柱图宽度
              itemStyle: {
                normal: {
                  label: {
                    show: true, //开启显示
                    position: "top", //在上方显示
                    textStyle: {
                      //数值样式
                      color: "#688AB6",
                      fontSize: 12,
                    },
                  },
                  barBorderRadius: [5, 5, 0, 0],
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#DFB73E' },
                    { offset: 0.5, color: '#DFB73E' },
                    { offset: 1, color: '#141f364d' }
                  ])
                },
                
              },
          }
        ]
    },
  };
  createEchart(opts);
}
// 创建折线chart
function createLineChartmouth(options) {
  var opts = {
    name: options.name,
    eleId: options.eleId,
    opts: {
      grid:{
        x:50,
        y:10,
        x2:20,
        y2:60,
        borderWidth:1,
        top: '15%',			
        bottom:'25%'
      },
        xAxis: {
            type: 'category',
            data: options.xAxisData,
            // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            axisLabel: {
              textStyle: {
                color: '#ddd',
              },
            rotate: 60,
            },
              },
              yAxis: {
                type: 'value',
            axisLabel: {
              textStyle: {
                color: '#ddd',
              fontSize:'14',
              },
            },
          },
          series: [
            {
              data: options.seriesData,
              // data: [120, 200, 150, 80, 70, 110, 130],
              type: 'bar',
              markPoint: {
                symbol:'image://../ioc_frontweb/images/gr.svg',//url替换成你的图片地址
                symbolSize:15,//图片大小
                symbolOffset:[0,'-50%'],//图片相对于柱形图x,y轴偏移量，注意要往上移y要是负的
                data:[{
                    coord:[0,40]//需要展示图片的柱型索引，y轴的value
                }],
                label:{
                    show:false,//顶部默认会展示y轴的值，可以设置false,不展示
                }
              },
              barWidth: 8, //柱图宽度
                itemStyle: {
                  normal: {
                    label: {
                      show: true, //开启显示
                      position: "top", //在上方显示
                      textStyle: {
                        //数值样式
                        color: "#688AB6",
                        fontSize: 12,
                      },
                    },
                    barBorderRadius: [5, 5, 0, 0],
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#DFB73E' },
                      { offset: 0.5, color: '#DFB73E' },
                      { offset: 1, color: '#141f364d' }
                    ])
                  },
                  
                },
            }
          ]
    },
  };
  createEchart(opts);
}

// 创建 chart
function createEchart(options) {
  // 基于准备好的dom，初始化echarts实例
  myEcharts[options.name] = echarts.init(document.getElementById(options.eleId), 'shine');

  // 指定图表的配置项和数据
  var defaults = {
    // color: ['#0175ee', '#d89446', '#373693', '#25ae4f', '#06b5c6', '#ac266f', '#26ac51', '#ac9026', '#ac5326', '#ac2626', '#2667ac']
  };

  var opts = $.extend({}, defaults, options.opts);
  // 使用刚指定的配置项和数据显示图表。
  myEcharts[options.name].setOption(opts);
}

// 播放视频
// function videoListenEvent() {
//     var timer = setTimeout(function () {
//         videoController.playByOrder(ele, ele, {
//             name: ele
//         });
//         clearTimeout(timer);
//     }, 3000);
// }

// 初始化视频播放器
function initVideo(ele) {
  var url = videoPlatUrl + '/scooper-video/conf/data';
  var param = {};
  //从接口获取视频的参数信息
  $.getJSON(url, param, function (data) {
    //创建视频对象
    var conf = data;
    //参数
    var videoOpts = {
      //初始化时的界面显示的分屏树
      windows: 1,
      //共有哪几种分屏
      windowsArr: [1, 16],
      //总的窗口数
      windowsNum: 16,
      conf: {
        user: conf['video.username'],
        passwd: conf['video.password'],
        // ip: conf['video.ip'],
        ip: '27.128.189.131',
        //videoServer port
        port: conf['video.port'],
        // janusUrl: conf['video.janus.url']
        janusUrl: 'ws://27.128.189.131:8188',
      },
      //码流类型，默认0
      streamType: conf['video.stream'],
      //是否截屏
      capImage: conf['video.cap.image'] === 'true',
      //截屏默认保存的地址
      videoCapImagePath: conf['video.cap.image.path'],
    };
    //轮巡的时间，单位秒
    conf['video.poll.time'] && (videoOpts.pollInterval = conf['video.poll.time']);
    var cla = '.' + ele;

    // var timer = setTimeout(() => {
    videoController = new scooper.video($(cla), videoOpts);
    // videoListenEvent();
    // clearTimeout(timer);
    // }, 2000);
  });
}

/**
 * jQuery的ajax请求
 *
 * @param {Object} options
 */
function jQueryAjax(options) {
  var defaults = {
    type: 'get',
    dataType: 'json',
    contentType: 'application/json',
    error: function (err) {
      layLayer.alert('请求异常！');
    },
  };
  var lockOpts = {
    success: function (result, textStatus, resObj) {
      if (result.code == 0) {
        options.success && options.success(result);
      } else {
        // globalMsg.msg(result.message);
        layLayer.alert(result.msg ? result.msg : result.message);
      }
    },
  };
  var opts = $.extend({}, defaults, options, lockOpts);
  $.ajax(opts);
}

// 根据不同分类的坐标数据创建 marker
function addCateMarker(category, parent) {
  if (!category) {
    layLayer.alert('缺少参数');
    return;
  }

  var url = category;

  if (parent) {
    url = parent + '?childId=' + category;
  }

  var opts = {
    url: apis.getMapData + '/' + url,
    success: function (res) {
      if (res.code === 0) {
        var pois = res.data;
        addMarker(pois, category);
      }
    },
  };
  jQueryAjax(opts);
}

/* 生成图例列表 */
function createLegendList() {
  var opts = {
    url: apis.getLegendInfoList,
    success: function (res) {
      if (res.code === 0) {
        var items = res.data;
        var tmpLi = '';
        if (items.length > 0) {
          for (var i = 0; i < items.length; ++i) {
            tmpLi +=
              '<li data-id="' +
              items[i].id +
              '" class="legendItem"><div class="first"><img class="legendPic" style="padding: 7px 0;" src="./images/legend/' +
              items[i].legendCode +
              '.png" alt=""/><span class="legendTitle">' +
              items[i].legendName +
              '</span></div><div class="legendchild">';
            var children = items[i].childList;
            for (var j = 0; j < children.length; ++j) {
              tmpLi += '<a data-id="' + children[j].id + '" href="#" class="childa" title="' + children[j].legendName + '">' + children[j].legendName + '</a>';
            }
            tmpLi += '</div></li>';
          }
          $('#legend').html(tmpLi);

          
          var legenditem=document.getElementsByClassName("legendItem");
          var legendchild=document.getElementsByClassName("legendchild");
          for (var i=0; i<legenditem.length;i++){
            // legenditem[i].index = i;
            // legenditem[i].onclick = function(){
            //   if(this.lastChild.style.display == "none"){
            //     this.style.backgroundImage="url(images/vectorbot.png)";
            //     this.lastChild.style.display = "block";
            //   }else{
            //     this.style.backgroundImage="url(images/re.png)";
            //     this.lastChild.style.display = "none";
            //   }
            // };
          }
          // 默认显示视频监控设备
          // $('.legendItem').eq(0).click();
        } else {
          layLayer.alert('数据为空');
        }
      }
      
    },
  };
  jQueryAjax(opts);
}

// 弹出ZH设备对应 marker 的信息窗
// function createZHDeviceInfoWindow(poi, position) {
//   if (!poi && !position) {
//     layLayer.alert('缺少参数');
//     return;
//   }
//   var url = poi.deviceType === 'ele8' ? apis.getEleDeviceInfoListByUserId : apis.getZHDeviceData;
//   var poi = poi;
//   var opts = {
//     url: url + '/' + poi['legendId'],
//     success: function (res) {
//       if (res.code === 0) {
//         poi['content'] = '<table>';
//         for (var i in res.data) {
//           if (poi.deviceType === 'ele8') {
//             poi['content'] +=
//               '<tr><th style="text-align:center">设备类型</th><th style="text-align:center">安装地址</th></tr>';
//             var deviceStatus =
//               res.data[i].deviceStatus == 1
//                 ? "<span style='color:orange;font-weight:600;'>#故障#</span>"
//                 : res.data[i].deviceStatus == 2
//                 ? "<span style='color:red;font-weight:600;'>#报警#</span>"
//                 : "<span style='color:green;font-weight:600;'>#正常#</span>";
//             for (var i in res.data) {
//               poi['content'] +=
//                 '<tr><td style="text-align:center">' +
//                 res.data[i].deviceModel +
//                 '&nbsp;' +
//                 deviceStatus +
//                 '</td><td>' +
//                 res.data[i].address +
//                 '</td></tr>';
//             }
//           } else {
//             for (var i in res.data) {
//               poi['content'] += '<tr><th>' + deviceReportName[i] + '</th><td>' + res.data[i] + '</td></tr>';
//             }
//           }
//           poi['content'] += '</table>';
//           createInfoWindow(poi, position);
//         }
//       }
//     },
//   };
//   jQueryAjax(opts);
// }

// 弹出普通的信息窗
function createNormalInfoWindow(poi, position) {
  if (!poi && !position) {
    layLayer.alert('缺少参数');
    return;
  }

  poi['content'] = '<table>';
  for (var i in poi) {
    switch (i) {
      case 'id':
      case 'resourceNo':
      case 'legendId':
      case 'legendCode':
      case 'deviceType':
      case 'aliasName':
      case 'showType':
      case 'status':
      case 'content':
        continue;
        break;
    }
    if( mapDataKey[i] ) poi['content'] += '<tr><th>' + mapDataKey[i] + '</th><td>' + poi[i] + '</td></tr>';
  }
  poi['content'] += '</table>';
  console.log(poi);
  createInfoWindow(poi, position);
}

// 弹出企业设备信息层
function renderEnterpriseDeviceData(poi, position) {
  if (!poi || !position) {
    layLayer.alert('缺少参数');
    return;
  }
  poi['deviceName'] = poi.enterpriseName;
  var opts = {
    url: apis.getEnterpriseDeviceInfoById + '/' + poi.resourceNo,
    success: function (res) {
      var data = res.data.pageData;
      if (res.code === 0) {
        var table = '<table style="margin: 0 auto;padding: 0;background-color: rgba(0,0,0,.7);width:750px">';
        table += `<thead><tr style="background-color: #333;"><td style="text-align:right">联系人：</td><td>${poi.contacts}</td><td style="text-align:right">联系电话：</td><td>${poi.telephone}</td><td style="text-align:right">地址：</td><td colspan='2'>${poi.address}</td></tr>`;
        table += `</table><table style="margin: 10px auto 0;padding: 0;background-color: rgba(0,0,0,.7);width:750px">`;
        table += `<tr style="background-color: #222;border-bottom: 2px solid #999;"><td>${enterpriseDeviceInfo['deviceType']}</td><td>${enterpriseDeviceInfo['deviceNum']}</td><td>${enterpriseDeviceInfo['onLineNum']}</td><td>${enterpriseDeviceInfo['offLineNum']}</td><td>${enterpriseDeviceInfo['historyAlarmNum']}</td><td>${enterpriseDeviceInfo['cancelAlarmNum']}</td><td>${enterpriseDeviceInfo['processingAlarmNum']}</td></tr></thead><tbody>`;

        table += `<div class="companyInfo">${poi.introduce}</div>`

        for (var i in data) {
          table += `<tr><td>${data[i].typeName}</td><td>${data[i].deviceNum}</td><td>${data[i].onLineNum}</td><td>${data[i].offLineNum}</td><td>${data[i].historyAlarmNum}</td><td>${data[i].cancelAlarmNum}</td><td>${data[i].processingAlarmNum}</td></tr>`;
        }

        table += '</tobdy></table>';
        table += `<div class="layui-layer-btn">
                    <a class="layui-layer-btn0 jkBtn" data-enterprisename=${poi.fullName} data-resourceno=${poi.resourceNo} onclick="renderEnterpriseCameraById(this)">监控摄像头</a>
                    <a class="layui-layer-btn0" data-enterprisename=${poi.fullName} data-resourceno=${poi.resourceNo} onclick="renderEnterpriseDeviceListById(this)">感知设备</a>
                  </div>`;

        poi['content'] = table;
        createInfoWindow(poi, position);
      }
    },
  };
  jQueryAjax(opts);
}

// 弹出企业感知设备列表层
function renderEnterpriseDeviceListById(ele) {
  if (!ele) {
    layLayer.alert('缺少参数');
    return;
  }
  layTable.render({
    elem: '#enterpriseDeviceList',
    url: apis.getEnterpriseDeviceListById + '/' + $(ele).data('resourceno'),
    dataType: 'json',
    request: {
      pageName: 'pageNum',
      limitName: 'pageSize',
    },
    parseData: function (res) {
      return {
        code: res.code,
        msg: res.msg,
        count: res.data.total,
        data: res.data.pageData,
      };
    },
    cols: [
      [
        { field: 'deviceName', title: '设备名称', align: 'center' },
        { field: 'deviceNo', title: '设备编号', align: 'center' },
        { field: 'contacts', title: '联系人', align: 'center' },
        { field: 'telephone', title: '联系电话', align: 'center' },
        {
          field: 'deviceStatus',
          title: '设备状态',
          align: 'center',
          templet: function (d) {
            return d.deviceStatus === '0' ? '正常' : '<span style="color:red;font-weight:600">报警</span>';
          },
        },
        { field: 'alarmTime', title: '报警时间', align: 'center' },
        { field: 'createTime', title: '创建时间', align: 'center' },
      ],
    ],
    page: {
      prev: '上一页',
      next: '下一页',
      groups: 5,
      first: '首页',
      layout: ['first', 'prev', 'page', 'next', 'limit'],
    },
    done: function () {
      layer.open({
        type: 1,
        title: $(ele).data('enterprisename') || '信息',
        area: ['1260px'],
        shade: false,
        content: $('.enterpriseDeviceList'),
        success: function () {
          layTable.resize('enterpriseDeviceList');
        },
      });
    },
  });
}

// 弹出企业监控摄像头列表层
function renderEnterpriseCameraById(ele) {
  if (!ele) {
    layLayer.alert('缺少参数');
    return;
  }
  if( $(ele).hasClass('selected') ){
    return
  }
  $(ele).addClass('selected');
  removeMaker('12343dd02b2b4412b012f9709876890')//清除企业监控
  var opts = {
    url: apis.getEnterpriseCameraById + '/' + $(ele).data('resourceno'),
    success: function (res) {
      if (res.code === 0) {
        if (res.data.pageData.length == 0) {
          layLayer.alert('没有监控设备！')
          return
        }
        var pois = res.data.pageData;
        addMarker(pois, 'jk');
      }
    },
  };
  jQueryAjax(opts);
  /* 去掉列表改为监控标注 layTable.render({
    elem: '#enterpriseDeviceList',
    url: apis.getEnterpriseCameraById + '/' + $(ele).data('resourceno'),
    dataType: 'json',
    request: {
      pageName: 'pageNum',
      limitName: 'pageSize',
    },
    parseData: function (res) {
      return {
        code: res.code,
        msg: res.msg,
        count: res.data.total,
        data: res.data.pageData,
      };
    },
    cols: [
      [
        { field: 'resourceNo', title: '设备编号', align: 'center' },
        { field: 'fullName', title: '设备名称', align: 'center' },
        { field: 'contacts', title: '联系人', align: 'center' },
        { field: 'telephone', title: '联系电话', align: 'center' },
        {
          field: 'deviceType',
          title: '设备类型',
          align: 'center',
          templet: function (d) {
            return d.deviceType === '1' ? '枪机' : '球机';
          },
        },
        {
          field: 'status',
          title: '设备状态',
          align: 'center',
          templet: function (d) {
            let val = '';
            switch (d.status) {
              case '0':
                val = '正常';
                break;
              case '1':
                val = '离线';
                break;
              default:
                val = '<span style="color:red;font-weight:600">报警</span>';
            }
            return val;
          },
        },
      ],
    ],
    page: {
      prev: '上一页',
      next: '下一页',
      groups: 5,
      first: '首页',
      layout: ['first', 'prev', 'page', 'next', 'limit'],
    },
    done: function () {
      layer.open({
        type: 1,
        title: $(ele).data('enterprisename') || '信息',
        area: ['1260px'],
        shade: false,
        content: $('.enterpriseDeviceList'),
        success: function () {
          layTable.resize('enterpriseDeviceList');
        },
      });
    },
  });*/
}

// 创建各种设备数量的图表
function createDeviceNumPieChart(eleId) {
  if (!eleId) {
    layLayer.alert('缺少参数');
    return;
  }
  var opts = {
    url: apis.getEventsNum,
    success: function (res) {
		console.log("11111111111",res.data)
      if (res.code === 0) {
        var options = {
          eleId: eleId,
          name: 'categoryAlarmNum',
          legendData: [],
          seriesData: [],
          series: [],
        };
        for (var i in res.data) {
          options.legendData.push(res.data[i].typeName);
          options.seriesData.push({
            // name: res.data[i].typeName,
            // value: res.data[i].deviceNum,
            name: res.data[i].eventType,
            value: res.data[i].eventNum,
            
          });
          options.series.push({
            name: res.data[i].key,
            type: 'bar',
            stack: 'all',
            data: [res.data[i].value],
          });
        }
        createPieChart(options);
      }
    },
  };
  jQueryAjax(opts);
}


// 日期折线图接口数据
function createDeviceNumLineChartday(eleId) {
  if (!eleId) {
    layLayer.alert('缺少参数');
    return;
  }
  var opts = {
    url: apis.getDeviceReportDatasNum,
    success: function (res) {
		console.log("2222222",res.data)
      if (res.code === 0) {
        var options = {
          eleId: eleId,
          name: 'deviceNumLineday',
          legendData: [],
		  xAxisData: [],
          seriesData: [],
          series: [],
        };
        for (var i in res.data.dayList) {
          options.xAxisData.push(res.data.dayList[i].date);
          options.seriesData.push(res.data.dayList[i].number);
          // options.series.push({
          //   name: res.data[i].key,
          //   type: 'bar',
          //   stack: 'all',
          //   data: [res.data[i].value],
          // });
        }
        createLineChartday(options);
      }
    },
  };
  jQueryAjax(opts);
}

// 月份折线图接口数据
function createDeviceNumLineChartmouth(eleId) {
  if (!eleId) {
    layLayer.alert('缺少参数');
    return;
  }
  var opts = {
    url: apis.getDeviceReportDatasNum,
    success: function (res) {
		console.log("2222222",res.data)
      if (res.code === 0) {
        var options = {
          eleId: eleId,
          name: 'deviceNumLinemouth',
          legendData: [],
		  xAxisData: [],
          seriesData: [],
          series: [],
        };
        for (var i in res.data.monthList) {
          options.xAxisData.push(res.data.monthList[i].date);
          options.seriesData.push(res.data.monthList[i].number);
          // options.series.push({
          //   name: res.data[i].key,
          //   type: 'bar',
          //   stack: 'all',
          //   data: [res.data[i].value],
          // });
        }
        createLineChartmouth(options);
      }
    },
  };
  jQueryAjax(opts);
}


// 渲染单兵轨迹
function renderSoldierTrack(self, id) {
  var soldierId = id ? id : $(self).data('soldierid') ? $(self).data('soldierid') : false;

  if(!myForm.startTime.value){
    alert("请选择起始时间");
    return;
  }
  if(!myForm.endTime.value){
    alert("请选择结束时间");
    return;
  }
  var startTime = myForm.startTime.value;
  var endTime = myForm.endTime.value;
  startTime = startTime.replace("T", " ");
  endTime = endTime.replace("T", " ");
  queryGisTrails(soldierId, startTime, endTime);
}

// 渲染报警数量
function renderEventNum() {
  // var opts = {
  //   url: apis.getEventNum,
  //   success: function (res) {
  //     if (res.code === 0) {
  //       var tmpHtml = '';
  //       for (var i in res.data) {
  //         tmpHtml += `
  //                   <div class="item">
  //                     <span class="num">${res.data[i]}</span><span class="itemTitle">${eventNum[i]}</span>
  //                   </div>`;
  //       }
  //       $('#alarm').html(tmpHtml);
  //     }
  //   },
  // };
  // jQueryAjax(opts);
}

// 渲染各类设备报警数量图表
function renderLegendTypeNum(eleId) {
  var opts = {
    url: apis.getLegendTypeNum,
    success: function (res) {
      console.log("333333333",res.data)
      $('.wu').append(res.data[0].num + res.data[1].num + res.data[2].num + res.data[3].num + res.data[4].num + res.data[5].num);
      $('.p1').append(res.data[0].num);
      $('.p2').append(res.data[1].num);
      $('.p3').append(res.data[2].num);
      $('.p4').append(res.data[3].num);
      $('.p5').append(res.data[4].num);
      $('.p6').append(res.data[5].num);
      if (res.code === 0) {
        var options = {
          eleId: eleId,
          name: 'deviceNumPie',
          series: [],
          xAxisData: [],
          seriesData: [],
        };
        for (var i in res.data) {
          // options.xAxisData.push(res.data[i].legendName);
          // options.seriesData.push(res.data[i].num);
          // options.legendData.push(res.data[i].typeName);
          options.seriesData.push({
            // name: res.data[i].typeName,
            // value: res.data[i].deviceNum,
            name: res.data[i].legendName,
            value: res.data[i].num,
          });
          options.series.push({
            name: res.data[i].key,
            type: 'bar',
            stack: 'all',
            data: [res.data[i].value],
          });
         
        }
        createDeviceAlarmNumBarChart(options);
        // createBarChart(options);
      }
    },
  };
  jQueryAjax(opts);
}

function renderAlarmList(obj) {
  if (obj.pageData.length > 0) {
    var totalTmpHtml = `
					<div class="itemh2">
            预警监控
            <img src="images/vector12.png" alt="" style="width: 14px;margin-right: 10px;">
					</div>
					<div class="itemout">
						<div class="item">
              <div class="itemTitle">预警总数</div><div class="num">${obj.totalNum}</div>
						</div>
						<div class="item">
              <div class="itemTitle">已处理</div><div class="num">${obj.handledNum}</div>
						</div>
						<div class="item">
              <div class="itemTitle">未处理</div><div class="num">${obj.noHandeldNum}</div>
						</div>
					</div>
                    `;
    $('#alarm').html(totalTmpHtml);

    var tmpHtml = '<ul>';
    var pageData = obj.pageData;
    for (var i in pageData) {
      tmpHtml += `<li class="${i % 2 == 0 ? 'odd' : ''}" title="${pageData[i].deviceNo} - ${pageData[i].unitName} - ${new Date(
        pageData[i].alarmTime,
      )}">
      <div style="width: 20%; overflow: hidden;">${pageData[i].unitName}</div>
      <div style="width: 15%; overflow: hidden;">${pageData[i].typeName}</div>
      <div style="width: 20%; overflow: hidden;">${pageData[i].statusName}</div>
      <div style="width: 25%; overflow: hidden;">${new Date(pageData[i].alarmTime).toLocaleString('zh-CN', {
        hour12: false,
      })}</div>
      <div style="width: 15%; overflow: hidden;">${pageData[i].handledStatus}</div>
    </li>`;
    }
    tmpHtml += '</ul>';
    $('.listContent').html(tmpHtml);

    $('.listContent').FontScroll({ time: 2000, num: 1 });
  } else {
    layLayer.alert('暂无数据');
  }
}

// 处理收到的 websocket 消息
function reciveWsMessage(res) {
  // console.log('ws recv: ', res);
  try {
    if (typeof res=== 'string') {
      console.log(res);
      return;
    }
    var resParse = JSON.parse(res);
    if (typeof resParse === 'object') {
      // addMarker([resParse], resParse.legendCode, 'warn');
      renderAlarmList(resParse);
    }
  } catch (err) {
    console.log(err);
  }
}

// 保持心跳
function keepHeart() {
  var opts = {
    url: apis.scooper.heartbeat,
    data: { token: token },
    contentType: 'application/x-www-form-urlencoded',
    success: function (res) {
      if (res.code != 0) {
        console.log('账号心跳保持失败，' + data.message);
      }
    },
  };
  jQueryAjax(opts);
}

// 报警数据初始请求
function getAlarmData(minute) {
  var opts = {
    url: apis.getAlarmData,
    success: function (res) {
      if (res.code == '0') {
        renderAlarmList(res.data);
      }
    },
  };
  jQueryAjax(opts);
}

// 搜索地图资源
function mapSearch(data, cb, isOpenLayer = null) {
  var opts = {
    url: apis.mapSearch,
    type: 'post',
    data: JSON.stringify(data),
    success: function (res) {
      if (res.code == 0) {
        if (res.data.pageData.length < 1) {
          layLayer.alert('暂无数据');
        } else {
          var tmpHtml = '<table style="width:100%;" class="layui-table"><colgroup><col width="150"><col width="200"><col></colgroup><tbody>';

          for (var i = 0; i < res.data.numList.length; ++i) {
            tmpHtml += '<tr><td>' + res.data.numList[i].legendName + '</td><td>' + res.data.numList[i].num + '</td></tr>';
          }

          tmpHtml += '</tbody></table>';
          if (isOpenLayer == null) {
            layer.open({
              type: 1,
              skin: 'layui-layer-rim',
              content: tmpHtml,
            });
          }
          addMarker(res.data.pageData);
        }
        cb();
      } else {
        alert(data.message);
      }
    },
  };
  jQueryAjax(opts);
}

// 指挥调度
function login() {
  var opts = {
    url: apis.scooper.loginTo,
    type: 'post',
    data: { accUsername: 'psxyj2', accPassword: sha256_digest('abc123') },
    contentType: 'application/x-www-form-urlencoded',
    success: function (res) {
      if (res.code == 0) {
        window.token = res.data;

        //启动心跳保持
        if (heartTime) {
          clearInterval(heartTime);
        }
        heartTime = setInterval(keepHeart, 15000);

        // 初始化订阅
        window._sub.init();
      } else {
        alert('登录失败，' + data.message);
      }
    },
  };
  jQueryAjax(opts);
}

// 单兵轨迹
function queryGisTrails(memId, startTime, endTime) {
  console.log(startTime, endTime);
  var opts = {
    url: apis.scooper.queryGisTrails,
    type: 'get',
    data: { token: window.token, memId: memId, startTime: startTime, endTime: endTime },
    contentType: 'application/x-www-form-urlencoded',
    success: function (res) {
      if (res.code == 0) {
        var list = res.data.list;
        var lineArr = [];
        for (var i = 0; i < list.length; ++i) {
          console.log(list[i].gis.split(','));
          var lng = list[i].gis.split(',')[0];
          var lat = list[i].gis.split(',')[1];
          var map = bd_decrypt(lng, lat);
          lineArr.push([map.lng, map.lat]);
          // lineArr.push(list[i].gis.split(','));
        }
        renderLineArr(lineArr);
      } else {
        alert(data.message);
      }
    },
  };
  jQueryAjax(opts);
}

// 语音呼叫
function makeCall(callee) {
  var opts = {
    url: apis.scooper.makeCall,
    type: 'post',
    data: {
      token: token,
      caller: '8001',
      callee: callee,
      businessId: '998',
      isRecord: 1,
    },
    contentType: 'application/x-www-form-urlencoded',
    success: function (res) {
      if (res.code == 0) {
        console.log(res);
      } else {
        alert('呼叫失败：' + data.message);
      }
    },
  };
  jQueryAjax(opts);
}

// 视频呼叫
function makeVideoCall(callee, callback) {
  var opts = {
    url: apis.scooper.makeVideoCall,
    type: 'post',
    data: {
      token: token,
      caller: '8001',
      callee: callee,
      businessId: '998',
      isRecord: 1,
    },
    contentType: 'application/x-www-form-urlencoded',
    success: function (res) {
      if (res.code == 0) {
        if (callback) {
          callback();
        }
      } else {
        layLayer.alert('呼叫失败：' + data.message);
      }
    },
  };
  jQueryAjax(opts);
}

// 呼叫单兵
function callSoldier(self) {
  var soldierId = $(self).data('soldierid') ? $(self).data('soldierid') : false;
  if (!soldierId) {
    layLayer.alert('参数错误');
    return;
  }

  callingSoldier = String(soldierId);
  makeVideoCall(String(soldierId), function () {
    var timer = setInterval(() => {
      if (soldierStatus !== 'callst_idle') {
        layLayer.open({
          title: soldierId,
          btn: false,
          content: `<div id="soldierVideo${soldierId}" style='width:100%;height:300px;position:relative'></div>`,
          area: ['290px'],
          success: function (layero, index) {
            $(`#soldierVideo${soldierId}`).append($('.videoHandler'));
            $('.videoHandler').find('.video-main-full').addClass('mode-1').removeClass('mode-4');
            $('.videoHandler').find('.info').show();
            videoController.playByOrderExpandWindow(`${soldierId}`, `${soldierId}`, {
              name: soldierId,
            });
          },
          cancel: function () {
            videoController && videoController.closeAll();
            $('.videoHome').append($('.videoHandler'));
            $('.iframeHandler').append($('.videoHandler'));
            layLayer.closeAll();
          },
        });

        clearInterval(timer);
      }
    }, 2000);
  });
}

function showMulitVideo() {
  layer.open({
    id:'videoW',
    type: 1,
    title: '视频监控查看',
    shade: 0,
    maxmin: true,
    shadeClose: false,
    area: ['800px', '600px'],
    content: '<div class="mulitVideo" style="height:100%"></div>',
    success: function () {
      mulitVideoFlag = true;
      $('.mulitVideo').append($('.videoHandler'));
      $('.videoHandler').find('.video-main-full').addClass('mode-1').removeClass('mode-4');
      $('.videoHandler').find('.info').show();
      videoController.setWindowsNum(16);
      for (var i in infoWindows) {
        infoWindows[i].close();
      }
    },
    cancel: function () {
      videoController && videoController.closeAll();
      $('.videoHome').append($('.videoHandler'));
      $('.iframeHandler').append($('.videoHandler'));
      mulitVideoFlag = false;
    },
  });
}

// 值班信息请求
function getDutyInfo() {
  var opts = {
    url: apis.getDutyInfo,
    success: function (res) {
		console.log(res.data);
      if (res.code == '0') {
        // alert(res)
		var strs = res.data.dutyMan.split(",");
		for(var i = 0;i< strs.length;i++){
			var html = "<dl>";
			var duteManInfo = strs[i].split("|");
			for(var a =0;a<duteManInfo.length;a++){
				if(a==2){
					var phone = "'"+duteManInfo[a]+"'";
					html+= '<dd><button class="layui-btn layui-btn-xs" onclick="makeCall('+phone+')">'+duteManInfo[a]+'</button></dd>';
				}else{
					html+= "<dd>"+duteManInfo[a]+"</dd>";
				}
			}
			html+= "</dl>";
		    $("#tbmsg").children().append(html);
		}
      }
    },
  };
  jQueryAjax(opts);
}
var video;

/*function getVideoUrl(cameraIndexCode) {
    var opts = {
        url: apis.getPreviewURLs,
        data:{
          "cameraIndexCode":cameraIndexCode
        },
        success: function (res) {
            if ("0" == res.code ) {

              if($("#example-video").size()>0){
                  videojs('example-video').dispose();
                  // $('.iframeHandler').empty();
              }
              $('.iframeHandler').append(
                  '<video id="example-video" width="auto" height="170px" class="video-js vjs-default-skin vjs-big-play-centered" poster="">' +
                  '  <source src="'+res.data.url+'" type="application/x-mpegURL" id="target">' +
                  '</video>');

                video = videojs('example-video', { "poster": "", "controls": "true","autoplay": "true","muted": "true" }, function() {
                    this.on('play', function() {
                        console.log('正在播放');
                    });
                    //暂停--播放完毕后也会暂停
                    this.on('pause', function() {
                        console.log("暂停中")
                    });
                    // 结束
                    this.on('ended', function() {
                        console.log('结束');
                    })
                });
            }
        }
    };
    jQueryAjax(opts);
}*/

/**
 * 海康视频
 * @param cameraIndexCode
 */
function getVideoUrl(cameraIndexCode,optionId) {
    var opts = {
        url: apis.getPreviewURLs,
        data:{
            "cameraIndexCode":cameraIndexCode
        },
        success: function (res) {
            if ("0" == res.code ) {
                if($("#player"+optionId).size() == 0){
                    $('.iframeHandler').append('<div id="player'+ optionId +'" style="width: calc(20vw - 8px);height: calc((20vw - 8px) * 5 / 8);"></div>');
                    const IS_MOVE_DEVICE = document.body.clientWidth < 992 // 是否移动设备
                    var player = new window.JSPlugin({
                        szId: 'player'+ optionId,
                        szBasePath: "/",
                        iMaxSplit: 1,
                        iCurrentSplit: IS_MOVE_DEVICE ? 1 : 2,
                        openDebug: true,
                        oStyle: {
                            borderSelect: IS_MOVE_DEVICE ? '#000' : '#FFCC00',
                        }
                    });

                    player.JS_Play(res.data.url,
                        {playURL: res.data.url, mode:"0" }, "0").then(() => { console.log('realplay success') },
                    e => { console.error(e) }
                )

                }
            }
        }
    };
    jQueryAjax(opts);
}



function videoControlling(cameraIndexCode,action,command) {
    var opts = {
        url: apis.videoControlling,
        data:{
            "cameraIndexCode" : cameraIndexCode,
            "command": command,
            "action" : action
        },
        success: function (res) {
            if ("0" != res.code ) {
                layLayer.alert('云控操作失败！');
            }
        }
    };
    jQueryAjax(opts);
}