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 pipelineView from "../components/PopWindow/pipelineView.vue";
import lineInfoWindow from "../components/PopWindow/lineInfoWindow.vue";
import  { delDeviceInfo } from "@/api/device/deviceInfo";
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",
  WORKORDER: "6"
};
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({ isCustom: true, offset: new AMap.Pixel(12, -65),anchor: "left-top" });
    let marker = new AMap.Marker({
      position: [data.longitude,data.latitude],
      map: map,
      offset: new AMap.Pixel(-13, -30)
    });
    this.setMarkerIcon(marker);
    if(DEVICE_TYPE.WORKORDER != markerType){
      marker.content = this.getMarketContent(data);   
      marker.on("mouseover", infoOpen);
      marker.on("mouseout", infoClose);
      marker.setExtData(data);
      that.deviceType = markerType;
      let editWindow = that.createInfowindow();
      marker.on("click", function(e) {
        if ("edit" == that.mapOperateType) {
          editWindow.form = e.target.getExtData();
          editWindow.show();
        } else if ("delete" == that.mapOperateType) {
          if (confirm("确认删除") == true) {
            map.remove(marker);
            that.deleteMarker(markerType,data.deviceId);
          }
        } else {
          map.setZoomAndCenter(13, e.target.getPosition());
          let infoWindow = new AMap.InfoWindow({
            isCustom: true,
            offset: new AMap.Pixel(12, -65),
            anchor: "left-top"
          });
          infoWindow.setContent(e.target.content);
          infoWindow.open(map, e.target.getPosition());
        }
      });
      marker.on("dragend", function(e) {
        editWindow.form.longitude = e.lnglat.lng;
        editWindow.form.latitude = e.lnglat.lat;
      });

    }
    
    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) {
    switch (this.markerType) {
      case DEVICE_TYPE.REGEULATORBOX: {
        const dom = createPop(markerInfoWindow,{
          title: "调压箱",
          data: data,
          map:map
        });
        const html = dom.$el;
        dom.remove();
        return html;
      }
      case DEVICE_TYPE.VALUEWELL: {
        const dom = createPop(markerInfoWindow,{
          title: "阀门井",
          data: data,
          map:map
        });
        const html = dom.$el;
        dom.remove();
        return html;
      }
      case DEVICE_TYPE.FLOWMETER: {
        const dom = createPop(markerInfoWindow,{
          title: "流量计",
          data: data,
          map:map
        });
        const html = dom.$el;
        dom.remove();
        return html;
      }
      
    }
  }

  /**
   * 删除marker
   * @param delType
   * @param deviceId
   */
  deleteMarker(delType,deviceId){
    if(DEVICE_TYPE.REGEULATORBOX == delType || DEVICE_TYPE.VALUEWELL == delType || DEVICE_TYPE.FLOWMETER == delType){
      delDeviceInfo(deviceId);
    }

  }

  /**
   * 设置设备图标
   * @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/zhibaorenyuan.png"),
        });
        marker.setIcon(icon);
        break;
      }
      case DEVICE_TYPE.WORKORDER: {
        let icon = new AMap.Icon({
          //size: new AMap.Size(51, 23),
          image: require("../assets/images/zhibaorenyuan.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: "#F7FE38",
        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, editorPage: true }
      });

      console.log("dom", dom.$el);

      let infoWindow = new AMap.InfoWindow({
        isCustom: true,
        content: dom.$el,
        //信息船体偏移量
        offset: new AMap.Pixel(0, 0),
        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 => {
        // console.log("屏幕宽高",document.body.clientWidth,document.body.clientHeight)
        // console.log('窗口大小',infoWindow.dom.offsetWidth)
        // console.log("鼠标的位置",e.originEvent.clientX,e.originEvent.clientY);
        // 上方导航的高
        const topBar = 81;
        // 坐标导航的宽
        const leftBar = 100;
        // 屏幕可视区的宽高
        const {
          clientWidth: windowClientWidth,
          clientHeight: windowClientHeight
        } = document.body;
        // 弹出的信息窗口的宽高
        // const { offsetWidth:infoWindowWidth,offsetHeight:infoWindowHeight} =infoWindow.dom;
        // 406,316
        const {
          offsetWidth: infoWindowWidth,
          offsetHeight: infoWindowHeight
        } = { offsetWidth: 406, offsetHeight: 316 };
        // 鼠标碰到线后的位置
        const { clientX: mouseClientX, clientY: mouseClientY } = e.originEvent;
        // 鼠标到左边界的距离
        const offsetLeftX = mouseClientX - 100;
        // 鼠标到右边界的距离
        const offsetRightX = windowClientWidth - mouseClientX;
        const offsetTopY = mouseClientY - 81;
        const offsetBottomY = windowClientHeight - mouseClientY;

        const offsetY = mouseClientY - 80 - infoWindowHeight;
        let X = 20,
          Y = -20;
        if (offsetLeftX <= infoWindowWidth) {
          console.log("靠左了");
          X = 20;
        } else if (offsetRightX <= infoWindowWidth) {
          console.log("靠右了");
          X = -infoWindowWidth - 20;
        }
        if (offsetTopY <= infoWindowHeight) {
          console.log("靠上了");
          Y = 20;
        } else if (offsetBottomY <= infoWindowHeight + 81) {
          console.log("靠下了");
          Y = -infoWindowHeight - 20;
        }
        polyline.setOptions({ strokeColor: "#FF5A67" });
        infoWindow.setOffset(new AMap.Pixel(X, Y));
        infoWindow.open(map, e.lnglat);

        // const
      });
      polyline.on("mouseout", e => {
        polyline.setOptions({ strokeColor: "#F7FE38" });
        infoWindow.close();
      });
      // 计算info的位置
      // function infoPosition() {}

      // 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", () => {
      console.log(this.lineType)
      // 获取当前状态 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 {
        // 经纬度
        const lnglatsArr = obj.getPath().map(item=>([item.lng,item.lat]));
        // 管道总长度
        const pipeLength = obj.getLength();
        // 传回来的数据 如果是新管道就是空
        const lineData = type == "newLine" ? {} : obj.getExtData().lineData;
        this.infoWindowPipelineView({ target:obj, lineType: type,lnglatsArr, pipeLength,lineData });
      }
    });
  }
  // 关闭所有已经上传的线的编辑状态
  linePolyEditorAllClose() {
    this.polyLines.forEach(item => {
      item.polyEditor.close();
      // let opstions = obj.getExtData();
      // opstions.isState = 1;
      item.setExtData({isState:0});
      item.setOptions({ strokeColor: "#F7FE38" });
    });
  }

  // 传进组件的会调 点确认的时候调
  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 {} =options;
    const notice = createPop(pipelineView, {
      title: "管道",
      // 数据
      // lineData: options.lineData,
      // lnglatsArr:options.lnglatsArr,
      // pipeLength:options.pipeLength,
      // //线是新线还是老线
      // lineType: options.lineType,
      // target: options.obj,
      ...options,
      //把当前对象当作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();
        device.map = map;
        device.obj = e.obj;
        device.gaoMap = that;
        e.obj.on("click", function(aa) {
          console.log(aa,"fdsfdsfdsa===click")
          let postion = aa.target._position;
          //兼容拖拽后单击事件，拖拽后点击事件返回位置为数组
          if(postion instanceof Array){
            device.form.longitude = postion[0];
            device.form.latitude = postion[1];
          }else{
            device.form.longitude = postion.lng;
            device.form.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: "流量计"
        });
      }
    }
  }

  /**
   * 鼠标画图事件
   * @param deviceType 设备类型
   */
  draw(deviceType) {
    let that = this;
    that.deviceType = deviceType;
    if (
      DEVICE_TYPE.REGEULATORBOX == deviceType ||
      DEVICE_TYPE.VALUEWELL == deviceType ||
      DEVICE_TYPE.FLOWMETER == 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());
      }
    );
  }

  searchTips(inputId){
    let that = this;
    AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], function () {
      //输入提示
      var autoOptions = {
        input: inputId
      };
      var auto = new AMap.AutoComplete(autoOptions);
      that.placeSearch = new AMap.PlaceSearch({
        map: map
      });
      //构造地点查询类
      auto.on('select', function(e){
        console.log(e,"eeeeee========")
        that.placeSearch.clear();
        that.placeSearch.setCity(e.poi.adcode);
        that.placeSearch.search(e.poi.name);  //关键字查询查询
      })
    })
  }

  searchKeyWord(keyWord){
    AMap.plugin(['AMap.AutoComplete'], function () {
      var placeSearch = new AMap.PlaceSearch({
        map: map
      });
      placeSearch.search(keyWord);  //关键字查询查询
    })
  }
}
export default gaodeMap;
