import createPop from "./createPop";
import regulatorBox from "../components/PopWindow/regulatorBox.vue";
import valveWell from "../components/PopWindow/valveWell.vue";
import flowMeter from "../components/PopWindow/flowMeter.vue";
import dutyPerson from "../components/PopWindow/dutyPerson.vue";
import pipelineView from "../components/PopWindow/pipelineView.vue";
import lineInfoWindow from "../components/PopWindow/lineInfoWindow.vue";
import markerInfoWindow from "../components/PopWindow/markerInfoWindow.vue";
import vue from "../main";
let defaultCenter = "石家庄";
export let map;
export const DEVICE_TYPE = {
  PIPEPLINE: "1",
  REGEULATORBOX: "2",
  VALUEWELL: "3",
  FLOWMETER: "4",
  DUTYPERSON: "5"
};
class gaodeMap {
  // 所有线的数组
  polyLines = [];
  // 是否开启新增
  lineType = 0;
  // 创建一个新的lineObj
  newLineObj = null;
  mouseTool = null;
  //构造函数中设置中央点默认值
  constructor(center) {
    this.markers = [];
    this.center = center ? center : defaultCenter;
    map = new AMap.Map("container", {
      //mask: addMask(result.districtList[0].boundaries),
      center: [114.72995, 38.37417],
      // resizeEnable: true,
      disableSocket: true,
      viewMode: "3D",
      showLabel: true,
      // labelzIndex: 110,
      pitch: 8,
      zoom: 9
      //mapStyle: 'amap://styles/darkblue',
      // mapStyle: 'amap://styles/3b679a15f448a4740ba2ff7524e1a4ae',
    });
    this.districtBoundaries();
  }

  /**
   * 获取map
   * @returns {AMap.Map}
   */
  get getMap() {
    return this.map;
  }

  /**
   * 重新设置中央点
   * @param value
   */
  set setCenter(value) {
    this.center = value;
    this.districtBoundaries();
  }

  /**
   * 设置城市边界
   */

  districtBoundaries() {
    let that = this;
    let opts = {
      subdistrict: 0,
      extensions: "all",
      level: "city"
    };
    let district = new AMap.DistrictSearch(opts);
    district.search(that.center, function(status, result) {
      if (status == "complete") {
        let defaultCenter = [];
        defaultCenter.push(result.districtList[0].center.lng);
        defaultCenter.push(result.districtList[0].center.lat);
        map.setCenter(defaultCenter);
        let bounds = result.districtList[0].boundaries;
        for (let i = 0; i < bounds.length; i += 1) {
          new AMap.Polyline({
            path: bounds[i],
            strokeColor: "#0088ff",
            strokeWeight: 5,
            strokeOpacity: 7,
            map: map
          });
        }
      }
    });
  }

  /**
   * 添加Market
   * @param markerType
   * @param lnglats
   */
  addMarker(markerType, data) {
    let that = this;
    that.markerType = markerType;
    let infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(-13, -70) });
    let marker = new AMap.Marker({
      position: [data.longitude,data.latitude],
      map: map,
      offset: new AMap.Pixel(-13, -30)
    });
    marker.content = this.getMarketContent(data);
    this.setMarkerIcon(marker);
    marker.on("mouseover", infoOpen);
    marker.on("mouseout", infoClose);
    that.deviceType = markerType;
    let editWindow = that.createInfowindow();
    marker.on("click", function(e) {
      if ("edit" == that.mapOperateType) {
        editWindow.show();
      } else if ("delete" == that.mapOperateType) {
        if (confirm("确认删除") == true) {
          map.remove(marker);
        }
      } else {
        map.setZoomAndCenter(13, e.target.getPosition());
        let infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(-13, -70)
        });
        infoWindow.setContent(e.target.content);
        infoWindow.open(map, e.target.getPosition());
      }
    });
    marker.on("dragend", function(e) {
      editWindow.editForm.longitude = e.lnglat.lng;
      editWindow.editForm.latitude = e.lnglat.lat;
      console.log(e.lnglat, "rrrr====");
    });
    this.markers.push(marker);
    map.setZoom("11");
    //map.setFitView();

    function infoClose(e) {
      infoWindow.close(map, e.target.getPosition());
    }

    function infoOpen(e) {
      infoWindow.setContent(e.target.content);
      infoWindow.open(map, e.target.getPosition());
    }
  }

  /**
   * marker添加拖拽事件
   */
  addMarkerDragg() {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setDraggable(true);
    }
  }

  /**
   * marker移除拖拽事件
   */
  removeMarkerDragg() {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setDraggable(false);
    }
  }

  /**
   * 添加marker信息
   * @param data
   * @returns {string}
   */
  getMarketContent(data) {
   /* const dom = createPop(markerInfoWindow,{});
    const html = dom.$el;
    dom.remove();
    switch (this.markerType) {
      case DEVICE_TYPE.REGEULATORBOX: {
        return html;
      }
      case DEVICE_TYPE.VALUEWELL: {
        return html;
      }
      case DEVICE_TYPE.FLOWMETER: {
        return html;
      }
      case DEVICE_TYPE.DUTYPERSON: {
        return html;
      }
    }*/

    let html = "<div>" +
      "<table>" +
      "<tr>" +
      "<td>所属燃气公司</td>" +
      "<td>正元</td>" +
      "</tr>" +
      "<tr>" +
      "<td>名称</td>" +
      "<td>1234</td>" +
      "</tr>" +
      "<tr>" +
      "<td>地址</td>" +
      "<td>石家庄市新华区</td>" +
      "</tr>" +
      "</table>" +
      "</div>";
    switch (this.markerType){
      case DEVICE_TYPE.REGEULATORBOX :{
        return html;
      }
      case DEVICE_TYPE.VALUEWELL :{
        return html;
      }
      case DEVICE_TYPE.FLOWMETER :{
        return html;
      }
      case DEVICE_TYPE.DUTYPERSON :{
        return html;
      }
    }
  }

  /**
   * 设置设备图标
   * @param marker
   */
  setMarkerIcon(marker){
    switch (this.markerType) {
      case DEVICE_TYPE.REGEULATORBOX: {
        let icon = new AMap.Icon({
          //size: new AMap.Size(51, 23),
          image: require("../assets/images/tiaoyaxiang.png"),
        });
        marker.setIcon(icon);
        break;
      }
      case DEVICE_TYPE.VALUEWELL: {
        let icon = new AMap.Icon({
          //size: new AMap.Size(51, 23),
          image: require("../assets/images/famenjing.png"),
        });
        marker.setIcon(icon);
        break;
      }
      case DEVICE_TYPE.FLOWMETER: {
        let icon = new AMap.Icon({
          //size: new AMap.Size(51, 23),
          image: require("../assets/images/liuliangji.png"),
        });
        marker.setIcon(icon);
        break;
      }
      case DEVICE_TYPE.DUTYPERSON: {
        let icon = new AMap.Icon({
          //size: new AMap.Size(51, 23),
          image: require("../assets/images/tiaoyaxiang.png"),
        });
        marker.setIcon(icon);
        break;
      }
    }
  }

  /**
   * 添加折线
   * @param path
   */
  addPolyline(path) {
    console.log(path);
    // this` polyLines = [];
    for (let i = 0; i < path.length; i++) {
      let polyline = new AMap.Polyline({
        path: path[i],
        strokeColor: "green",
        strokeWeight: 8,
        strokeOpacity: 0.9,
        zIndex: 50,
        bubble: true,
        geodesic: true,
        extData: {
          type: "line",
          //当前line状态 0:正常状态 1:正在编辑状态
          isState: 0
        }
      });
      this.polyLines.push(polyline);
      // 信息窗体
      const dom = createPop(lineInfoWindow, {
        obj: { a: 123 }
      });

      console.log("dom", dom.$el);
      var infoWindow = new AMap.InfoWindow({
        isCustom: true,
        content: dom.$el,
        //信息船体偏移量
        offset: new AMap.Pixel(20, -20),
        anchor: "left-top"
      });

      this.newLineAddEvent(polyline);
      // // 编辑状态
      // let polyEditor = new AMap.PolyEditor(map, polyline);
      // //创建右键菜单
      // let contextMenu = new AMap.ContextMenu();
      // //菜单选择
      // contextMenu.addItem(
      //   "编辑Polyline",
      //   function() {
      //     polyEditor.setTarget(polyline);
      //     polyEditor.open();
      //     contextMenu.close();
      //   },
      //   0
      // );
      // // 结束编辑
      // contextMenu.addItem(
      //   "结束编辑",
      //   function() {
      //     polyEditor.close();
      //     contextMenu.close();
      //   },
      //   0
      // );

      // contextMenu.addItem(
      //   "保存信息",
      //   function() {
      //     console.log("折线数组", polyline.getPath());
      //     // polyEditor.close();
      //     // contextMenu.close()
      //   },
      //   0
      // );

      //添加事件
      polyline.on("mouseover", e => {
        polyline.setOptions({ strokeColor: "red" });
        infoWindow.open(map, e.lnglat);
      });
      polyline.on("mouseout", e => {
        polyline.setOptions({ strokeColor: "green" });
        infoWindow.close();
      });

      // polyline.on("rightclick", e => {
      //   console.log(this.lineType);
      //   // if(!this.lineFlag==0) return;
      //   // lineFlag 1新建 2编辑 3删除 0啥也不让干
      //   switch (this.lineType) {
      //     case 2: {
      //       contextMenu.open(map, e.lnglat);
      //       break;
      //     }
      //     default:
      //       break;
      //   }
      // });
    }
    map.add(this.polyLines);
    // 缩放地图到合适的视野级别
    // map.setFitView();
  }
  // 创建一条新的线
  createNewLine() {
    this.mouseTool.polyline({
      strokeWeight: 9,
      strokeColor: "#80d8ff",
      extData: {
        type: "newLine",
        //当前line状态 0:正常状态 1:正在编辑状态
        isState: 0
      }
      //同Polyline的Option设置
    });
  }
  // 新建line增加编辑以及右键菜单
  addEditorAndMenu(obj) {
    let polyEditor = new AMap.PolyEditor(map, obj);
    let contextMenu = new AMap.ContextMenu();
    contextMenu.addItem(
      "编辑",
      function() {
        polyEditor.setTarget(obj);
        polyEditor.open();
        contextMenu.close();
      },
      0
    );
    contextMenu.addItem(
      "结束编辑",
      function() {
        polyEditor.close();
        contextMenu.close();
        console.log(obj.getPath());
      },
      0
    );
    contextMenu.addItem(
      "保存",
      () => {
        polyEditor.close();
        contextMenu.close();
        this.addPolyline([obj.getPath()]);
        map.remove(obj);
      },
      0
    );
    contextMenu.addItem(
      "删除",
      function() {
        polyEditor.setTarget(obj);
        polyEditor.open();
        contextMenu.close();
      },
      0
    );
    obj.on("rightclick", e => {
      if (this.lineType == 1) {
        contextMenu.open(map, e.lnglat);
      }
    });
  }
  // 新line与老line添加点击事件
  newLineAddEvent(obj) {
    obj.polyEditor = new AMap.PolyEditor(map, obj);
    obj.on("click", () => {
      // 获取当前状态 0普通状态，1是正编辑状态
      const { isState, type } = obj.getExtData();
      // 如果不是新线的时候并且没点编辑，点击是无效的
      if (type != "newLine" && this.lineType != 2) return;
      if (isState == 0) {
        // 如果是0，就打开编辑，变成编辑状态
        obj.polyEditor.open();
        let opstions = obj.getExtData();
        opstions.isState = 1;
        console.log(opstions);
        obj.setExtData(opstions);
      } else {
        this.infoWindowPipelineView({ obj, lineType: type });
      }
    });
  }
  // 传进组件的会调 点确认的时候调
  lineOkCallBack(target) {
    target.polyEditor.close();
    const index = this.polyLines.indexOf(target);
    // 如果是老线，就要线删除原来的，然后重新包装一遍
    if (index >= 0) {
      this.polyLines.splice(index, 1);
    }
    this.addPolyline([target.getPath()]);
    map.remove(target);
    // console.log('polyLines',this.polyLines)
  }
  // 上传服务器用的组件

  infoWindowPipelineView(options) {
    const notice = createPop(pipelineView, {
      title: "管道",
      //线是新线还是老线
      lineType: options.lineType,
      target: options.obj,
      //把当前对象当作that传进去
      gaodeMap: this,
      lineOkCallBack: this.lineOkCallBack
    });
    notice.show();
  }
  /**
   * 添加鼠标事件
   */
  addMouseTool() {
    this.mouseTool = new AMap.MouseTool(map);
    //监听draw事件可获取画好的覆盖物
    this.overlays = [];
    let that = this;
    this.mouseTool.on("draw", function(e) {
      if (e.obj.getExtData().type != "newLine") {
        const device = that.createInfowindow();
        e.obj.on("click", function(aa) {
          let postion = aa.target._position;
          device.editForm.longitude = postion.lng;
          device.editForm.latitude = postion.lat;
          device.show();
        });
      }

      if (e.obj.getExtData().type == "newLine") {
        console.log("挂上菜单");
        that.newLineAddEvent(e.obj);
        // 右键菜单
        // that.addEditorAndMenu(e.obj)
      }
      that.overlays.push(e.obj);
      // if(e.obj.getExtData().type=="line"){
      //   return;
      // }
      that.mouseTool.close();
    });
  }

  /**
   * 创建弹框事件
   */
  createInfowindow() {
    switch (this.deviceType) {
      case DEVICE_TYPE.PIPEPLINE: {
        break;
      }
      case DEVICE_TYPE.REGEULATORBOX: {
        return createPop(regulatorBox, {
          title: "调压箱"
        });
      }
      case DEVICE_TYPE.VALUEWELL: {
        return createPop(valveWell, {
          title: "阀门井"
        });
      }
      case DEVICE_TYPE.FLOWMETER: {
        return createPop(flowMeter, {
          title: "流量计"
        });
      }
      case DEVICE_TYPE.DUTYPERSON: {
        return createPop(dutyPerson, {
          title: "值班人员"
        });
      }
    }
  }

  /**
   * 鼠标画图事件
   * @param deviceType 设备类型
   */
  draw(deviceType) {
    let that = this;
    that.deviceType = deviceType;
    if (
      DEVICE_TYPE.REGEULATORBOX == deviceType ||
      DEVICE_TYPE.VALUEWELL == deviceType ||
      DEVICE_TYPE.FLOWMETER == deviceType ||
      DEVICE_TYPE.DUTYPERSON == deviceType
    ) {
      that.mouseTool.marker({
        draggable: true
      });
    }
    if (DEVICE_TYPE.PIPEPLINE == deviceType) {
      that.mouseTool.polyline({
        strokeWeight: 9,
        strokeColor: "#80d8ff"
        //同Polyline的Option设置
      });
    }
  }

  /**
   * 添加地图控件
   */
  addMapControl() {
    AMap.plugin(
      [
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.HawkEye",
        "AMap.MapType",
        "AMap.Geolocation"
      ],
      function() {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        //map.addControl(new AMap.ToolBar());

        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        map.addControl(new AMap.Scale());

        // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
        map.addControl(new AMap.HawkEye({ isOpen: true }));

        // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
        map.addControl(
          new AMap.MapType({ position: { top: "10px", left: "100px" } })
        );

        // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
        // map.addControl(new AMap.Geolocation());
      }
    );
  }
}
export default gaodeMap;
