import CreateAbnormalEventInfoWindow from './messageWindow/CreateAbnormalEventInfoWindow';
import CreateTrajectoryInfoWindow from './messageWindow/CreateTrajectoryInfoWindow';
import CreateComponeyInfoWindow from './messageWindow/CreateComponeyInfoWindow';
import CreateAttendPointInfoWindow from './messageWindow/CreateAttendPointInfoWindow';
import CreateSearchAddressInfoWindow from './messageWindow/CreateSearchAddressInfoWindow';
import attendancePoint from "@assets/images/prevention/aPicture/attendancePoint.png";
import { isEmpty } from '@utils/utils';
import { recordAdd, getRecordLastJSON } from '@common/recordHistory';
import eventCenter from "@common/events"; // 引入 EventEmitter

//打点（人员跟驻勤点的样式）
//事件列表对搜索出的人员打点
export function markEventList(eventList, where = "") {
  let eventMarkers = [];
  eventList.length > 0 &&
    eventList.map((item, index) => {
      const map = this.state.map;
      if (item.lnglat) {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(item.lnglat[0], item.lnglat[1]), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: "负责人:" + item.name || "--",
          content:
            '<div class="amap_lib_placeSearch_poi poibox-icon">' +
            index +
            "</div>",
          key: item.id,
          indexText: index,
        });
        const that = this;
        // 手动驻的点给点击事件
        AMap.event.addListener(marker, "click", function () {
          that.props.dispatch({
            type: "command/setEventSelectIndex",
            payload: marker.w.key,
          });
          that.openEventInfo(item, map, marker);
        });
        marker.setAnimation("AMAP_ANIMATION_DROP");
        eventMarkers.push(marker);
      }
    });
  this.state.map.add(eventMarkers);
  this.state.map.setFitView(eventMarkers); //自适应显示所有的标注点
  return eventMarkers;
  // this.setState({ personMarkers });
}

//事件的打点更换
export function openEventInfo(item, map, marker) {
  let infoWindow = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: this.createEventInfoWindow(item),
    offset: new AMap.Pixel(16, -45),
  });
  infoWindow.open(this.state.map, marker.getPosition());
  const markers = this.state.eventMarkers;
  markers.map((itemMark, i) => {
    if (itemMark.w.key === item.id) {
      markers[i].setContent(
        '<div class="selected"><div class="amap_lib_placeSearch_poi poibox-icon">' +
        itemMark.w.indexText +
        "</div></div>"
      );
    } else {
      markers[i].setContent(
        '<div class="amap_lib_placeSearch_poi poibox-icon">' +
        itemMark.w.indexText +
        "</div>"
      );
    }
  });
  this.state.map.setZoomAndCenter(this.state.zoom, [
    marker.getPosition().lng,
    marker.getPosition().lat,
  ]); //同时设置地图层级与中心点
  // this.state.map.setCenter(marker.getPosition());//设置中心点
  // this.setState({
  //   personMarkers: markers,
  // });
  return markers;
}

//人员的打点更换图标，切换成未打点状态
export function closeEventMarkers() {
  const markers = this.state.eventMarkers;
  markers.map((itemMark, i) => {
    markers[i].setContent(
      '<div class="amap_lib_placeSearch_poi poibox-icon">' +
      itemMark.w.indexText +
      "</div>"
    );
  });
  return markers;
}

//人员图层对搜索出的人员打点
export function markPersonList(personList, where = "") {
  let selectComponeyInfo = this.props.selectComponeyInfo
  // where代表搜索的值，“软件园三期”“百川信”有特殊的打点位置需求
  if (!isEmpty(this.state.personMarkers)) {
    console.log('准备清除 markPersonList 标记');
    this.state.map.remove(this.state.personMarkers);
  }
  if (!isEmpty(this.state.beijingMarkers)) {
    this.state.map.remove(this.state.beijingMarkers);
  }
  if (!isEmpty(this.state.gaoqiMarkers)) {
    this.state.map.remove(this.state.gaoqiMarkers);
  }
  let personMarkers = [];
  personList.length > 0 &&
    personList.map((item, index) => {
      const map = this.state.map;
      if (item.lnglat) {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(item.lnglat[0], item.lnglat[1]), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: "负责人:" + item.name || "--",
          content:
            '<div class="amap_lib_placeSearch_poi poibox-icon">' +
            index +
            "</div>",
          key: item.perId,
          indexText: index,
        });
        const that = this;
        //手动驻的点给点击事件
        AMap.event.addListener(marker, "click", function () {
          selectComponeyInfo.clickType = 'personnel';
          recordAdd({
            from: 'ComponeyInfo',
            to: 'CreateTrajectoryInfoWindow',
            fromData: selectComponeyInfo,
            toID: ''
          });
          that.props.dispatch({
            type: "command/setPersonSelectIndex",
            payload: marker.w.key,
          });
          that.openPersonInfo(item, marker, 'police');
          // that.openPersonInfo(item, marker);
        });
        marker.setAnimation("AMAP_ANIMATION_DROP");
        personMarkers.push(marker);
      }
    });
  this.state.map.add(personMarkers);
  if (where === "厦门软件园三期" || where === "软件园三期") {
    let allMark = [];
    //假的点,用来居中到软三的作用
    var marker1 = new AMap.Marker({
      position: new AMap.LngLat(118.051211, 24.60608), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
    });
    allMark.push(marker1);
    var marker2 = new AMap.Marker({
      position: new AMap.LngLat(118.047843, 24.611016), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
    });
    allMark.push(marker2);
    this.state.map.setFitView(allMark);
  } else {
    this.state.map.setFitView(personMarkers); //自适应显示所有的标注点
  }
  return personMarkers;
  // this.setState({ personMarkers });
}
//人员的打点更换
export function openPersonInfo(item, marker, type) {
  let infoWindow
  if (type == 'police') {
    infoWindow = new AMap.InfoWindow({
      isCustom: true, //使用自定义窗体
      content: CreateTrajectoryInfoWindow.call(this, item, type, marker),
      offset: new AMap.Pixel(16, -45),
    });
  } else {
    infoWindow = new AMap.InfoWindow({
      isCustom: true, //使用自定义窗体
      content: this.createInfoWindow(item),
      offset: new AMap.Pixel(16, -45),
    });
  }

  infoWindow.open(this.state.map, marker.getPosition());
  const markers = this.state.personMarkers;
  if (type != 'place') {
    markers.map((itemMark, i) => {
      if (itemMark.w.key === item.perId) {
        markers[i].setContent(
          '<div class="selected"><div class="amap_lib_placeSearch_poi poibox-icon">' +
          itemMark.w.indexText +
          "</div></div>"
        );
      } else {
        markers[i].setContent(
          '<div class="amap_lib_placeSearch_poi poibox-icon">' +
          itemMark.w.indexText +
          "</div>"
        );
      }
    });
  }
  this.state.map.setZoomAndCenter(this.state.zoom, [
    marker.getPosition().lng,
    marker.getPosition().lat,
  ]);
  return markers;
}

//人员的打点更换图标，切换成未打点状态
export function closePersonMarkers() {
  const markers = this.state.personMarkers;
  markers.map((itemMark, i) => {
    markers[i].setContent(
      '<div class="amap_lib_placeSearch_poi poibox-icon">' +
      itemMark.w.indexText +
      "</div>"
    );
  });
  return markers;
}

//搜索出的驻勤点打点
export function markerAttendanceList(attendanceList, typeName = "") {
  //先删除之前的打点
  if (!!this.state.attendanceMarkers) {
    //如果是搜索列表的打点，先删除之前地图上的搜索的驻勤标记
    this.state.map.remove(this.state.attendanceMarkers);
  }
  let attendanceMarkers = [];
  const length = attendanceList.length;
  if (length > 0) {
    for (let i = 0; i < length; i++) {
      if (attendanceList[i].lnglat) {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(
            attendanceList[i].lnglat[0],
            attendanceList[i].lnglat[1]
          ), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: "负责人:" + attendanceList[i].name || "--",
          content: attendanceList[i].markerIcon
            ? '<div class="amap_lib_placeSearch_poi poibox-icon mark-icon" style="background:url(' +
            attendanceList[i].markerIcon +
            ')">' +
            "</div>"
            : '<div class="amap_lib_placeSearch_poi poibox-icon">' + "</div>",
          comTaskId: attendanceList[i].comTaskId,
          markerIcon: attendanceList[i].markerIcon,
          clickMarkerIcon: attendanceList[i].clickMarkerIcon,
        });
        marker.setAnimation("AMAP_ANIMATION_DROP");
        const that = this;
        //手动驻的点给点击事件
        AMap.event.addListener(marker, "click", function () {
          that.props.dispatch({
            type: "command/setSelectIndex",
            // payload: marker.w.comTaskId,
            payload: i,
          });
        });
        attendanceMarkers.push(marker);
      }
    }
  }
  this.state.map.add(attendanceMarkers);
  this.state.map.setFitView(attendanceMarkers); //自适应显示所有的标注点
  return attendanceMarkers;
  // this.setState({ attendanceMarkers });
}

//驻勤点的打点更换
export function openAttendanceInfo({
  item, map, marker, currentIndex, afterIndex, layerStatus = ''
}) {
  const that = this;
  const _defaultInfo = {
    isCustom: true, //使用自定义窗体
    content: this.createAttendanceInfoWindow(item),
    offset: new AMap.Pixel(16, -45),
  };
  const infoJson = isEmpty(layerStatus) || layerStatus != 'aPicture' ? _defaultInfo : {
    isCustom: true, //使用自定义窗体
    content: CreateAttendPointInfoWindow.call(that, item, '', marker),
    offset: new AMap.Pixel(16, -45),
  }
  let infoWindow = new AMap.InfoWindow(infoJson);
  infoWindow.open(map, marker.getPosition());
  map.setZoomAndCenter(this.state.zoom, [item.lnglat[0], item.lnglat[1]]); //同时设置地图层级与中心点
  // map.setCenter([item.lnglat[0], item.lnglat[1]]);
  const markers = this.state.attendanceMarkers;
  // markers.map((itemMark, i) => {
  //   if (itemMark.w.comTaskId == item.comTaskId) {
  //     markers[i].setContent(
  //       '<div class="amap_lib_placeSearch_poi poibox-icon mark-icon" style="background:url(' +
  //         itemMark.w.clickMarkerIcon +
  //         ')">' +
  //         "</div>"
  //     );
  //   } else {
  //     markers[i].setContent(
  //       '<div class="amap_lib_placeSearch_poi poibox-icon mark-icon" style="background:url(' +
  //         itemMark.w.markerIcon +
  //         ')">' +
  //         "</div>"
  //     );
  //   }
  // });
  // this.setState({
  //   attendanceMarkers: markers,
  // });
  markers[currentIndex].setContent(
    '<div class="amap_lib_placeSearch_poi poibox-icon mark-icon" style="background:url(' +
    markers[currentIndex].w.clickMarkerIcon +
    ')">' +
    "</div>"
  );
  if (afterIndex != null && afterIndex != currentIndex) {
    markers[afterIndex].setContent(
      '<div class="amap_lib_placeSearch_poi poibox-icon mark-icon" style="background:url(' +
      markers[afterIndex].w.markerIcon +
      ')">' +
      "</div>"
    );
  }
  return markers;
}

//驻勤点的打点更换图标，切换成未打点状态
export function closeAttendanceMarker() {
  const markers = this.state.attendanceMarkers;
  markers.map((itemMark, i) => {
    markers[i].setContent(
      '<div class="amap_lib_placeSearch_poi poibox-icon mark-icon" style="background:url(' +
      itemMark.w.markerIcon +
      ')">' +
      "</div>"
    );
  });
  // this.setState({
  //   attendanceMarkers: markers,
  // });
  return markers;
}

/****************一张图的图层*****************/
//数据展示的打点信息
export function markPicture(pictureList, type, where = '') {
  console.log('markPicture', pictureList, type);
  let selectComponeyInfo = this.props.selectComponeyInfo
  var pictureMarks = []
  var pictureDatas = [];
  pictureList.data.map((item, index) => {
    // item.longitude = "118."+parseInt(Math.random() * 1000000);
    // item.latitude = "24."+parseInt(Math.random() * 1000000);
    if (item.longitude && item.latitude) {
      item.mapIcon = pictureList.mapIcon ? pictureList.mapIcon : "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png";
      item.clickMapIcon = pictureList.clickMarkerIcon ? pictureList.clickMarkerIcon : item.mapIcon;
      if (type == 'attendancePoint' || type == 'attendance' || type == 'eventMarker') {
        item.mapIcon = item.markerIcon;
        item.clickMapIcon = item.clickMarkerIcon;
      }
      const key = !isEmpty(item.perId) ? item.perId : item.id;
      var marker = new AMap.Marker({
        icon: item.mapIcon,
        // markerIcon: mapIcon,
        // clickMarkerIcon: clickMarkerIcon,
        position: new AMap.LngLat(item.longitude, item.latitude),
        // position: [0,0],
        offset: new AMap.Pixel(-13, -30),
        key: key,
        indexText: index,
      });
      const that = this;
      switch (type) {
        //保安人员定位
        case 'securityResource':
        case 'attendancePolice':
          // 手动驻的点给点击事件
          AMap.event.addListener(marker, "click", function (e) {
            if (type == 'attendancePolice') {
              recordAdd({
                from: 'AttendInfo',
                to: 'CreateTrajectoryInfoWindow',
                fromData: item,
                toID: 'attendancePolice'
              });
            } else {
              const lastJSON = getRecordLastJSON();
              if (lastJSON.to != 'CreateTrajectoryInfoWindow') {
                const fromData = lastJSON.to == "ComponeyInfo" ? selectComponeyInfo : null
                recordAdd({
                  from: lastJSON.to,
                  to: 'CreateTrajectoryInfoWindow',
                  fromData: fromData,
                  toID: lastJSON.toID
                });
              }
            }
            if (isEmpty(where)) {
              eventCenter.emit('checkedMapTag', {
                type,
                item: item,
                checked: true
              });
            } else {
              // 周边搜索
              eventCenter.emit('checkedMapTag', {
                type: "securityResourceSearch",
                item: item,
                checked: true
              });
            }
          });
          break;
        //保安公司定位
        case 'securityCompany':

          let companyLogo = item.componeyLogo
          // 创建一个 Icon
          marker = new AMap.Marker({
            position: new AMap.LngLat(item.longitude, item.latitude),
            content: `<div class="amap-icon" style="position: absolute; overflow: hidden; width: 44px; height: 44px; top: -23px;left: -9px;background: white;border-radius: 33px;">
              <img src="${companyLogo}" style="    width: 34px;height: 34px;top: 5px;left: 5px;">
            </div>`,
            // position: [0,0],
            offset: new AMap.Pixel(-13, -30)
          });
          let infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            content: CreateComponeyInfoWindow.call(that, item, type, marker),
            offset: new AMap.Pixel(16, -45),
          });
          // 手动给驻点添加鼠标移入/移出事件
          AMap.event.addListener(marker, "mouseover", function () {
            infoWindow.open(that.state.map, marker.getPosition());
          });
          AMap.event.addListener(marker, "mouseout", function () {
            infoWindow.close();
          });

          // TAG: 根据需求 368。点击打开公司办公地点定位，并打开公司信息弹框
          // this.props.dispatch({
          //   type: 'command/clearInfoWindow',
          //   payload: true
          // })
          // this.props.dispatch({
          //   type: 'command/setSelectComponeyInfo',
          //   payload: item
          // })
          break;
        // 驻勤点
        case 'attendancePoint':
          // 手动驻的点给点击事件
          infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            content: CreateAttendPointInfoWindow.call(that, item, type, marker),
            offset: new AMap.Pixel(0, -15),
          });
          // 手动给驻点添加鼠标移入/移出事件
          AMap.event.addListener(marker, "mouseover", function () {
            if (isEmpty(selectComponeyInfo.componeyLogo)) {
              recordAdd({
                from: 'AttendInfo',
                to: 'CreateAttendPointInfoWindow',
                fromData: item,
                toID: ''
              });
            } else {
              selectComponeyInfo.clickType = 'attendancePoints';
              recordAdd({
                from: 'ComponeyInfo',
                to: 'AttendInfo',
                fromData: selectComponeyInfo,
                toID: ''
              });
            }
            infoWindow.open(that.state.map, marker.getPosition());
          });
          AMap.event.addListener(marker, "mouseout", function () {
            infoWindow.close();
          });
          // TAG: 根据需求 368。点击打开点击打开驻勤点定位，并打开驻勤点弹框
          this.props.dispatch({
            type: 'command/clearInfoWindow',
            payload: true
          })
          break;
        // 搜索地址
        case 'searchAddress':
          AMap.event.addListener(marker, "click", function () {
            infoWindow = new AMap.InfoWindow({
              isCustom: true,
              content: CreateSearchAddressInfoWindow.call(that, item, type, marker),
              offset: new AMap.Pixel(0, -15)
            })
            infoWindow.open(that.state.map, marker.getPosition())
          })
          break;
        // 事件标记
        case 'eventMarker':
          AMap.event.addListener(marker, "click", function(){
            infoWindow = new AMap.InfoWindow({
              isCustom: true,
              content: CreateAbnormalEventInfoWindow.call(that, item, type, marker),
              offset: new AMap.Pixel(0, -15)
            })
            infoWindow.open(that.state.map, marker.getPosition())
          })
          break;
        default:
          console.log("default");
          // 手动驻的点给点击事件
          AMap.event.addListener(marker, "click", function () {
            //执法记录仪目前使用假数据，与真实的执法记录仪进行交互
            if (pictureList.name == "执法记录仪") {
              let infoWindow = new AMap.InfoWindow({
                isCustom: true, //使用自定义窗体
                content: that.createEnforcementRecordWindow.call(that, item, type, marker),
                offset: new AMap.Pixel(16, -45),
              });
              infoWindow.open(that.state.map, marker.getPosition());
            } else {
              let infoWindow = new AMap.InfoWindow({
                isCustom: true, //使用自定义窗体
                content: that.createPicturePerception(item, pictureList.name, type),
                offset: new AMap.Pixel(16, -45),
              });
              infoWindow.open(that.state.map, marker.getPosition());
            }
          });
          break;
      }
      pictureMarks.push(marker)
      pictureDatas.push(item);
    }
  })
  return {
    pictureMarks,
    pictureDatas
  }
}

//实时异常的打点信息
export function markNowErrorEvent(data) {
  let lng = JSON.parse(data.position)
  let { latitude, longitude } = lng
  let infoWindow = new AMap.InfoWindow({
    content: CreateAbnormalEventInfoWindow(data)
  });
  infoWindow.open(this.state.map, latitude && longitude ? [longitude, latitude] : this.state.map.getCenter());
}

/****************警保联动图层****************/
export function markPolice(data) {
  var policeMarks = []
  data.map((item, index) => {
    if (item.longitude && item.latitude) {
      var marker = new AMap.Marker({
        position: new AMap.LngLat(item.longitude, item.latitude),
        title: "负责人:" + item.name || "--",
        content:
          '<div class="amap_lib_placeSearch_poi poibox-icon">' +
          index +
          "</div>",
        key: item.id,
        indexText: index,
      });
      const that = this;
      //手动驻的点给点击事件
      AMap.event.addListener(marker, "click", function () {
        //存储选中的点id
        that.props.dispatch({
          type: "command/setPoliceSelectIndex",
          payload: marker.w.key,
        });
        marker.setContent(
          '<div class="selected"><div class="amap_lib_placeSearch_poi poibox-icon">' +
          marker.w.indexText +
          "</div></div>"
        );
        that.openPersonInfo(item, marker, 'police');
      });
      policeMarks.push(marker)
    }
  })
  return policeMarks
}
