import createPop from "./createPop";
import { lineColor } from "./mapCommon.js";
import regulatorBox from "../components/PopWindow/regulatorBox.vue";
import valveWell from "../components/PopWindow/valveWell.vue";
import flowMeter from "../components/PopWindow/flowMeter.vue";
import pressureGage from "../components/PopWindow/pressureGage.vue";
import pipelineView from "../components/PopWindow/pipelineView.vue";
import lineInfoWindow from "../components/PopWindow/lineInfoWindow.vue";
import { delDeviceInfo, updateDeviceInfo } from "@/api/device/deviceInfo";
import markerInfoWindow from "../components/PopWindow/markerInfoWindow.vue";
import { getArray } from "@/utils/gassafety.js";
import { delPipe, updatePipe } from "@/api/device/pipe.js";

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",
  PRESSUREGAGE: "7",
  INSPECTOR: "8"
};
class gaodeMap {
  // 所有线的数组
  polyLines = [];
  // 是否开启新增
  lineType = 0;
  // 创建一个新的lineObj
  newLineObj = null;
  // onceFlag=false;
  lineFlag = false;
  mouseTool = null;
  myMap = null;
  showInfoWindow = null;
  view = null;
  // 地图移动结束后出现infowindow用的函数
  handleInfoWindowOpenFunc = null;
  // 点击左侧抽屉的时候，改变的flag
  leftListClick = false;

  //构造函数中设置中央点默认值
  constructor(center, latlng) {
    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/1c84d2203793b0f622df2cda53db1afd"
      // mapStyle: 'amap://styles/darkblue',
      // mapStyle: 'amap://styles/3b679a15f448a4740ba2ff7524e1a4ae',
    });
    this.myMap = map;

    this.myMap.on("click", e => {
      // if (this.lineType !=1 || this.lineFlag) return;
      this.closeInfoWindow();
      this.polyLinesColorClear();
      if (this.lineType != 1 || this.lineFlag) return;

      // 除了这里，还要利用vue页面的window事件辅助，当组件出来的时候，就得利用window事件
      if (this.newLineObj) {
        vue
          .$confirm("是否重新画管道")
          .then(() => {
            this.newLineObj.polyEditor.close();
            map.remove(this.newLineObj);
            this.newLineObj = null;
            this.lineFlag = false;
            this.createNewLine();
            console.log("map点击事件新建");
          })
          .catch(() => {});
      }
      // console.log("抬起来了");
    });

    // 地图开始平移删除infowindow
    this.myMap.on("movestart", () => {
      // console.log("地图平移");
      // 抽屉点击的时候让infowindow隐藏

      if (this.leftListClick) {
        console.log("moveStart");
        this.closeInfoWindow();
      }
    });
    // 地图开始缩放删除infowindow
    this.myMap.on("zoomstart", () => {
      this.closeInfoWindow();
      this.polyLinesColorClear();
    });
    this.myMap.on("moveend", () => {
      if (this.handleInfoWindowOpenFunc) {
        this.handleInfoWindowOpenFunc();
        this.handleInfoWindowOpenFunc = null;
        // 移动结束之后，leftListClick变成false
        this.leftListClick = false;
      }
      // console.log("缩放开始")
      if (!this.onceFlag) {
        this.onceFlag = true;
        if (this.view) {
          this.view.backFlag = false;
          // 让抽屉不在隐身
          this.view.drawerOpacity = true;
        }
      }
      // 每次地图移动结束，就让地图可以缩放
      let options = this.myMap.getStatus();
      options.scrollWheel = true;
      this.myMap.setStatus(options);
      console.log("飞行结束");
    });

    this.districtBoundaries(latlng);
  }
  panTo(lnglat) {
    this.myMap.panTo(lnglat);
  }

  changeMap(bool) {
    // 卫星图
    if (!bool) {
      if (this.satellite) return;
      this.satellite = new AMap.TileLayer.Satellite();
      this.myMap.addLayer(this.satellite);
    } else {
      if (this.satellite) {
        this.myMap.removeLayer(this.satellite);
        this.satellite = null;
      }
    }
  }
  /**
   * 获取map
   * @returns {AMap.Map}
   */
  get getMap() {
    return this.map;
  }

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

  resetMapCenter(value) {
    map.setCenter(value);
  }

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

  districtBoundaries(latlng) {
    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);
        if (latlng) {
          map.setCenter(latlng);
        } else {
          map.setCenter(defaultCenter);
        }

        console.log("defaultCenter", 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, func) {
    let that = this;
    that.markerType = markerType;
    console.log(markerType);
    let infoWindow = new AMap.InfoWindow({
      isCustom: true,
      offset: new AMap.Pixel(24, -38),
      anchor: "left-top"
    });
    infoWindow.on("mouseover", function() {
      let options = map.getStatus();
      options.scrollWheel = false;
      map.setStatus(options);
    });
    infoWindow.on("mouseout", function() {
      let options = map.getStatus();
      options.scrollWheel = true;
      map.setStatus(options);
    });
    let marker = new AMap.Marker({
      position: [data.longitude, data.latitude],
      map: map,
      offset: new AMap.Pixel(0, 5)
    });
    this.setMarkerIcon(marker);
    if (
      DEVICE_TYPE.WORKORDER != markerType &&
      DEVICE_TYPE.INSPECTOR != markerType
    ) {
      marker.content = this.getMarketContent(data);
      marker.on("mouseover", this.infoOpen);
      marker.on("click", this.infoOpen);
      marker.on("mouseout", infoClose);
      marker.infoWindow = infoWindow;
      marker.setExtData(data);
      that.deviceType = markerType;
      let editWindow = that.createInfowindow("编辑");
      editWindow.fileArr =
        data.iconUrl != "" && data.iconUrl != undefined
          ? [{ url: data.iconUrl }]
          : [];
      editWindow.obj = marker;
      editWindow.gaoMap = that;
      editWindow.map = map;
      marker.on("click", function(e) {
        if ("edit" == that.mapOperateType) {
          editWindow.form = e.target.getExtData();
          editWindow.show();
        } else if ("delete" == that.mapOperateType) {
          let diviceType = {
            "2": "调压箱",
            "3": "阀门井",
            "4": "流量计",
            "7": "压力表"
          };
          vue
            .$confirm(
              '是否删除名称为"' +
                e.target.getExtData().deviceName +
                '"的' +
                diviceType[markerType] +
                " ?",
              "提示",
              {
                type: "warning"
                // center: true
              }
            )
            .then(() => {
              // that.deleteMarker(markerType, data.deviceId);
              that.deleteMarker(markerType, data).then(res => {
                if (res.code == 200) {
                  map.remove(marker);
                  // 数组里也删了
                  const ind = that.markers.indexOf(marker);
                  if (ind >= 0) {
                    that.markers.splice(ind, 1);
                    console.log(that.markers);
                  }
                  const arr = that.markers.map(item => {
                    return item.getExtData();
                  });
                  that.view.deviceClassify(arr);
                  that.view.pipeList();
                }
              });
            })
            .catch(() => {
              vue.$message({
                type: "info",
                // center:true,
                offset: 100,
                message: "已取消删除"
              });
            });
        } /*else {
          //map.setZoomAndCenter(13, e.target.getPosition());
          let infoWindow = new AMap.InfoWindow({
            isCustom: true,
            offset: new AMap.Pixel(24, -38),
            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;
      });
    } else {
      marker.on("mouseover", function() {
        marker.setLabel({
          offset: new AMap.Pixel(0, -10), //设置文本标注偏移量
          content: "<div class='info'>" + data.deviceName + "</div>", //设置文本标注内容
          direction: "top" //设置文本标注方位
        });
      });
      marker.on("mouseout", function() {
        marker.setLabel({
          content: null
        });
      });
    }

    if (this.changePolineListNum === null) {
      // this.polyLines.push(polyline);
      this.markers.push(marker);
    } else {
      this.markers.splice(this.changePolineListNum, 0, marker);
      this.changePolineListNum = null;
    }
    map.setZoom("11");
    //map.setFitView();

    function infoClose(e) {
      let options = map.getStatus();
      options.scrollWheel = true;
      map.setStatus(options);
      //infoWindow.close(map, e.target.getPosition());
    }
    if (func) {
      func();
    }
  }
  // 其他设备
  infoOpen = e => {
    // 如果是无状态并且鼠标mouseover
    if (this.view.targetNum == 0 && e.type == "mouseover") {
      return;
    }
    // 如果是新建状态 不出弹框
    if (this.view.targetNum == 1) return;
    console.log(e.target);
    let options = map.getStatus();
    options.scrollWheel = false;
    map.setStatus(options);
    e.target.infoWindow.setContent(e.target.content);
    e.target.infoWindow.open(map, e.target.getPosition());
    this.markerInfoWindow = e.target.infoWindow;
  };
  /**
   * 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;
      }
      case DEVICE_TYPE.PRESSUREGAGE: {
        const dom = createPop(markerInfoWindow, {
          title: "压力表",
          data: data,
          map: map
        });
        const html = dom.$el;
        dom.remove();
        return html;
      }
    }
  }

  /**
   * 删除marker
   * @param delType
   * @param deviceId
   */
  deleteMarker(delType, deviceData) {
    if (
      DEVICE_TYPE.REGEULATORBOX == delType ||
      DEVICE_TYPE.VALUEWELL == delType ||
      DEVICE_TYPE.FLOWMETER == delType ||
      DEVICE_TYPE.PRESSUREGAGE == delType
    ) {
      // delDeviceInfo(deviceId);
      const upDataObj = { ...deviceData };
      upDataObj.isDel = 1;
      return updateDeviceInfo(upDataObj);
    }
  }

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

  /**
   * 添加折线
   * @param path
   */
  addPolyline(arr, func) {
    // this` polyLines = [];
    console.log("包装的数组", arr);
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      let { coordinates, pipePressure } = item;
      // console.log("coordinates",coordinates)
      // let path = coordinates ? getArray(coordinates) :[];
      // 字符串转二维数组

      let path = coordinates ? eval(coordinates) : [];
      let polyline = new AMap.Polyline({
        path,
        strokeColor: lineColor[pipePressure],
        strokeWeight: 4,
        strokeOpacity: 0.9,
        zIndex: 50,
        cursor: "pointer",
        bubble: false,
        geodesic: true,
        extData: {
          type: "line",
          //当前line状态 0:正常状态 1:正在编辑状态
          isState: 0,
          lineData: item
        }
      });
      // 如果是修改后包装，有记录的index 就在原位置插入，如果没有，就直接在最后插入
      if (this.changePolineListNum === null) {
        this.polyLines.push(polyline);
      } else {
        this.polyLines.splice(this.changePolineListNum, 0, polyline);
        this.changePolineListNum = null;
      }
      // 信息窗体
      const dom = createPop(lineInfoWindow, {
        obj: { a: 123, editorPage: true, ...item, polyline }
      });

      console.log("dom", dom.$el);
      dom.$el.addEventListener("mouseover", () => {
        let options = this.myMap.getStatus();
        options.scrollWheel = false;
        this.myMap.setStatus(options);
      });
      dom.$el.addEventListener("mouseout", () => {
        let options = this.myMap.getStatus();
        options.scrollWheel = true;
        this.myMap.setStatus(options);
      });
      let infoWindow = new AMap.InfoWindow({
        isCustom: true,
        autoMove: true,
        content: dom.$el,
        //信息船体偏移量
        offset: new AMap.Pixel(0, 0),
        anchor: "left-top"
      });

      this.newLineAddEvent(polyline);
      polyline.infoWindow = infoWindow;
      //添加事件
      polyline.on("mouseover", this.polylineMouseOver);
      polyline.on("click", this.polylineMouseOver);
      polyline.on("mousedown", e => {
        this.polyLinesColorClear(polyline);
      });
      polyline.on("mouseout", e => {
        // polyline.setOptions({ strokeColor: "#2EE7E7" });
        polyline.setOptions({ strokeColor: lineColor[pipePressure] });

        // infoWindow.close();
      });
      // 计算info的位置
      // function infoPosition() {}
    }
    map.add(this.polyLines);
    if (func) {
      func();
    }
    // 缩放地图到合适的视野级别
    // map.setFitView();
  }
  // 鼠标移入管道
  polylineMouseOver = e => {
    console.log(e.type);
    let polyline = e.target;
    // 如果是无状态或者是新建并且是鼠标移入
    if (this.view.targetNum == 0 && e.type == "mouseover") {
      polyline.setOptions({ strokeColor: "#F7FE38" });
      return;
    }

    // 当选择的是新建的时候，线是点不了的
    if (this.lineType == 1 || this.view.targetNum == 1) return;
    if (
      (this.view.targetNum == 2 || this.view.targetNum == 3) &&
      e.type == "mouseover"
    ) {
      this.polyLinesColorClear(polyline);
    }
    // 上方导航的高
    let X = 20,
      Y = -20;
    if (e.originEvent) {
      const topBar = 81;
      // 坐标导航的宽
      const leftBar = 100;
      // 屏幕可视区的宽高
      const {
        clientWidth: windowClientWidth,
        clientHeight: windowClientHeight
      } = document.body;
      // 弹出的信息窗口的宽高

      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;

      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;
      }
      X = 23;
      Y = -20;
      // polyline.setOptions({ strokeColor: "#FF5A67" });
      // 浮动的时候为新建时，不变色
      if (this.view.targetNum != 1) {
        polyline.setOptions({ strokeColor: "#F7FE38" });
      }
    }

    polyline.infoWindow.setOffset(new AMap.Pixel(X, Y));

    // 如果是戍边浮动出现infowindow 就让窗口在固定的位置出现，这样就不显得乱了
    if (e.type == "mouseover") {
      const coordinates = polyline.getPath().map(item => {
        return [item.lng, item.lat];
      });
      // const { coordinates } = polyline.getExtData().lineData;
      // 计算出前两个点的中点
      const arr1 = coordinates[0];
      const arr2 = coordinates[1];
      const a = this.centerNum(arr1[0], arr2[0]);
      const b = this.centerNum(arr1[1], arr2[1]);
      const a2 = this.centerNum(a, arr1[0]);
      const b2 = this.centerNum(b, arr1[1]);
      // polyline.infoWindow.open(map, [a2, b2]);
      polyline.infoWindow.open(map, e.lnglat);
    } else {
      console.log("windowOpen");
      // 变成异步，最后执行
      polyline.infoWindow.open(map, e.lnglat);

      // setTimeout(() => {
      //   console.log(polyline.infoWindow.getIsOpen())
      //   polyline.infoWindow.open(map, e.lnglat);
      // }, 0);
      // console.log(polyline.infoWindow.)
    }
    // polyline.infoWindow=infoWindow;
    this.showInfoWindow = polyline.infoWindow;

    // const
  };

  polyLinesColorClear(polylines) {
    this.polyLines.forEach(item => {
      if (item != polylines) {
        const { pipePressure } = item.getExtData().lineData;
        // item.setOptions({ strokeColor: "#2EE7E7" });
        item.setOptions({ strokeColor: lineColor[pipePressure] });
      }
    });
  }
  centerNum(num1, num2) {
    return (Number(num1) + Number(num2)) / 2;
  }
  // 创建一条新的线
  createNewLine() {
    map.remove(this.markerOverlays);
    console.log("创造一条线了啊");
    this.mouseTool.polyline({
      // bubbles:false,
      strokeWeight: 4,
      strokeColor: "#80d8ff",
      extData: {
        type: "newLine",
        //当前line状态 0:正常状态 1:正在编辑状态
        isState: 0
      }
      //同Polyline的Option设置
    });
    // 让它不再等于null
    // this.newLineObj={a:123}
  }
  // 创建出来的新线归位，重置，当点击编辑跟删除的时候
  newLineReset() {
    this.lineFlag = false;
    if (this.mouserTool) {
      this.mouseTool.close();
    }
    if (this.newLineObj) {
      this.newLineObj.polyEditor.close();
      map.remove(this.newLineObj);
      this.newLineObj = null;
    }
  }
  // 新建line增加编辑以及右键菜单
  closeInfoWindow() {
    this.showInfoWindow && this.showInfoWindow.close();
    this.markerInfoWindow && this.markerInfoWindow.close();
  }
  // 新line与老line添加点击事件
  newLineAddEvent(obj) {
    obj.polyEditor = new AMap.PolyEditor(map, obj);
    // obj.polyEditor.on('adjust',(e)=>{
    //   console.log("addnode")
    // })

    obj.on("mousedown", e => {
      console.log(e.originEvent);
      console.log("lineType", this.lineType);
      this.lineFlag = true;
      // 每次点击关闭然后再次激活
      // 如果是新线就关闭
      if (obj.getExtData().type == "newLine") {
        this.mouseTool.close();
      }
      // 删除
      if (this.lineType == 3) {
        this.lineDelete(obj);
        return;
      }
      // 获取当前状态 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;
        // const lineData =  obj.getExtData().lineData;
        console.log("lineData===================>传入组件的数据", lineData);
        this.infoWindowPipelineView({
          target: obj,
          lineType: type,
          lnglatsArr,
          pipeLength,
          lineData
        });
      }
    });
  }
  // 隐藏所有管道
  lineShow(bool) {
    bool
      ? this.polyLines.forEach(item => item.show())
      : this.polyLines.forEach(item => item.hide());
    if (this.newLineObj) {
      bool ? this.newLineObj.show() : this.newLineObj.hide();
    }
  }
  markerShow(type, bool) {
    this.markers.forEach(item => {
      const { deviceType } = item.getExtData();
      if (deviceType == type) {
        bool ? item.show() : item.hide();
      }
      // console.log("deviceType",deviceType);
    });
  }
  // 其实是修改了状态，不是真的删除
  lineDelete(obj) {
    const {
      lineData: { pipeName, deviceInfoList }
    } = obj.getExtData();
    let devices = " ";
    let content;
    if (deviceInfoList) {
      for (var i = 0; i < deviceInfoList.length; i++) {
        var item = deviceInfoList[i];
        devices = devices + item.deviceName + " ";
      }
      content = `请确认是否删除管道名称为 + ${pipeName} +的数据项，该管道下包含的设备（ ${devices}  ）将一并删除`;
    } else {
      content = `请确认是否删除管道名称为 ${pipeName} 的数据项，该管道下不包含任何设备`;
    }
    vue
      .$confirm(content, "提示", {
        // confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning"
        // center: true
      })
      .then(() => {
        const { lineData } = obj.getExtData();
        // updatePipe
        // delPipe(pipeId).then(res => {
        let upDataObj = { ...lineData };
        upDataObj.isDel = 1;
        updatePipe(upDataObj).then(res => {
          if (res.code == 200) {
            const index = this.polyLines.indexOf(obj);
            // 如果是老线，就要线删除原来的，然后重新包装一遍
            if (index >= 0) {
              this.polyLines.splice(index, 1);
              // 删除管道的时候，与管道管理额的设备也要删除,
              // 如果管道存在下级设备,也一并删除
              if (deviceInfoList) {
                for (var i = 0; i < deviceInfoList.length; i++) {
                  const item = deviceInfoList[i];
                  for (let j = 0; j < this.markers.length; j++) {
                    const item2 = this.markers[j];
                    if (item.deviceId == item2.getExtData().deviceId) {
                      map.remove(item2);
                      const ind = this.markers.indexOf(item2);
                      if (ind >= 0) {
                        this.markers.splice(ind, 1);
                      }
                      break;
                    }
                  }
                }
              }
              map.remove(obj);
              // 列表变化
              const pipeArr = this.polyLines.map(item => {
                return item.getExtData().lineData;
              });
              const markerArr = this.markers.map(item => {
                return item.getExtData();
              });
              this.view.pipeClassify(pipeArr);
              this.view.deviceClassify(markerArr);
              this.view.pipeList();
            }
            vue.$message({
              type: "success",
              offset: 100,
              // center:true,
              message: "删除成功!"
            });
            // 关闭当前线条的infowindow
            // this.closeLineInfoWindow();
            console.log("改变线条");
          }
        });
      })
      .catch(err => {
        console.log(err);
        vue.$message({
          type: "info",
          // center:true,
          offset: 100,
          message: "已取消删除"
        });
      });
  }
  // 关闭所有已经上传的线的编辑状态
  linePolyEditorAllClose() {
    this.polyLines.forEach(item => {
      item.polyEditor.close();
      let opstions = item.getExtData();
      const { pipePressure } = opstions.lineData;

      opstions.isState = 0;
      item.setExtData(opstions);

      let attr = item.getOptions();
      // attr.strokeColor = "#F7FE38";
      attr.strokeColor = lineColor[pipePressure];
      item.setOptions(attr);
    });
  }

  // 传进组件的会调 点确认的时候调
  lineOkCallBack(target, data, func) {
    target.polyEditor.close();
    const index = this.polyLines.indexOf(target);
    // 如果是老线，就要线删除原来的，然后重新包装一遍
    if (index >= 0) {
      // 记录当前位置的元素
      this.changePolineListNum = index;
      this.polyLines.splice(index, 1);
    }
    console.log("data999-=================>传回来的data", data);
    this.addPolyline([data], func);
    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.markerOverlays = [];
    this.mouseTool.on("draw", function(e) {
      if (e.obj.getExtData().type != "newLine") {
        map.remove(that.markerOverlays);
        const device = that.createInfowindow("新增");
        device.map = map;
        device.obj = e.obj;
        device.gaoMap = that;
        e.obj.on("click", function(aa) {
          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();
        });
        e.obj.on("mouseover", function() {
          that.mouseTool.close();
        });

        e.obj.on("mouseout", function() {
          that.draw(that.deviceType);
        });

        that.markerOverlays.push(e.obj);
      }

      if (e.obj && e.obj.getExtData().type == "newLine") {
        console.log("挂上事件");
        that.newLineAddEvent(e.obj);
        e.obj.on("mouseover", () => {
          e.obj.setOptions({ strokeColor: "#F7FE38" });
        });
        e.obj.on("mouseout", () => {
          e.obj.setOptions({ strokeColor: "#80d8ff" });
        });
        // 记录这条线
        // console.log(e.obj.getPath().length)
        // 如果只有一个点，并没有连成线的时候就不close 大于一个点的时候才执行clse
        console.log(that.lineType);
        if (e.obj.getPath().length > 1) {
          that.newLineObj = e.obj;
          that.mouseTool.close();
        } else {
          // that.newLineObj = null;
        }
        // 关闭
        // 创建一条新线，然后在点地图的时候删除原来的旧线
        // that.createNewLine();

        // 右键菜单
        // that.addEditorAndMenu(e.obj)
      }

      // if(e.obj.getExtData().type=="line"){
      //   return;
      // }
      //that.mouseTool.close();
      that.overlays.push(e.obj);
    });
  }

  /**
   * 创建弹框事件
   */
  createInfowindow(val) {
    switch (this.deviceType) {
      case DEVICE_TYPE.PIPEPLINE: {
        break;
      }
      case DEVICE_TYPE.REGEULATORBOX: {
        return createPop(regulatorBox, {
          title: val + "调压箱"
        });
      }
      case DEVICE_TYPE.VALUEWELL: {
        return createPop(valveWell, {
          title: val + "阀门井"
        });
      }
      case DEVICE_TYPE.FLOWMETER: {
        return createPop(flowMeter, {
          title: val + "流量计"
        });
      }
      case DEVICE_TYPE.PRESSUREGAGE: {
        return createPop(pressureGage, {
          title: val + "压力表"
        });
      }
    }
  }

  /**
   * 鼠标画图事件
   * @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.PRESSUREGAGE == 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
      // };
      // let auto = new AMap.AutoComplete(autoOptions);
      that.placeSearch = new AMap.PlaceSearch({
        map: map
      });
      //构造地点查询类
      // auto.on("select", function(e) {
      //   that.searchSelectAdcode = e.poi.adcode;
      //   that.searchSelectName = e.poi.name;
      // });
    });
  }

  closeAddMarker() {
    this.mouseTool.close();
    map.remove(this.markerOverlays);
  }
  // 只上图没功能
  onlyLine(obj) {
    const { coordinates, pipeName } = obj;
    let polyline = new AMap.Polyline({
      path: eval(coordinates),
      strokeColor: "#80d8ff",
      strokeWeight: 4,
      strokeOpacity: 0.9,
      zIndex: 50,
      bubble: true,
      geodesic: true,
      extData: {
        type: "line",
        //当前line状态 0:正常状态 1:正在编辑状态
        isState: 0,
        lineData: obj
      }
    });
    let infoWindow = new AMap.InfoWindow({
      isCustom: true,
      content: `<div style='max-width:150px;border:1px solid #80d8ff;background:#fff'>${pipeName}</div>`,
      anchor: "left-top",
      offset: new AMap.Pixel(20, -20)
    });
    polyline.on("mouseover", e => {
      const options = polyline.getOptions();
      options.strokeColor = "#FF5A67";
      polyline.setOptions(options);
      infoWindow.open(map, e.lnglat);
    });
    polyline.on("mouseout", e => {
      const options = polyline.getOptions();
      options.strokeColor = "#80d8ff";
      polyline.setOptions(options);
      infoWindow.close();
    });
    map.add(polyline);
    const path1 = eval(coordinates)[0];
    const path2 = eval(coordinates)[1];
    // map.setFitView();
    const path3 = [
      (Number(path1[0]) + Number(path2[0])) / 2,
      (Number(path1[1]) + Number(path2[1])) / 2
    ];
    map.setCenter(path3, false);

    // const lntlat = eval(coordinates)[0];
    // map.panTo(lntlat)

    // 信息窗体
  }
}
export default gaodeMap;
