import { Component, OnInit, AfterContentInit, AfterViewInit, ViewChild, Inject, ChangeDetectorRef } from '@angular/core';
import { MapOptions, Point, PolylineOptions, BPolyline, ControlAnchor, MapTypeEnum } from 'angular2-baidu-map';
import { DynamicScriptLoaderService } from '../dynamic-script.service';


import { theme } from './theme';
import { ModalService } from '../services';
import { DefaultService, Project, Course, Scetion, Camera } from '../api';
import { HttpClient, HttpParams } from '@angular/common/http';
import { timer } from 'rxjs';

import { timeInterval, pluck, take, tap } from 'rxjs/operators';
import { ActivatedRoute, Router } from '@angular/router';
import { IdService } from '../services/id.service';
import { SelfMapService } from '../services/map.service';

declare var map: any;
declare var BMap: any;
declare var BMapLib: any;
declare var drawingManager: any;
declare var BMAP_HYBRID_MAP:any;
declare var mapv;
const enum CordType {
  PROJ,
  COURSE,
  SECTION
}
const enum markType {
  HIGHWAY = 1,
  NORMAL
}
export interface DialogData {
  animal: string;
  name: string;
}
@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.less']
})
export class MainComponent implements OnInit {
  cameraSum: any={};
  allsecs: any=[];
  curive:boolean = false;
  curiveLength:number = 10;
  theme: any;

  constructor(private m:SelfMapService, private router:Router, private idService: IdService, private route: ActivatedRoute, private cd: ChangeDetectorRef, private http: HttpClient, private dynamicScriptLoader: DynamicScriptLoaderService, private modalService: ModalService, private s: DefaultService) {
    //定位山西省地图
    this.opts = {
      centerAndZoom: {
        lat: 37.78663390039693,
        lng: 112.43176242674386,
        zoom: 10,
      },
      mapType:MapTypeEnum.BMAP_HYBRID_MAP
    }
    //    this.opts = {
    //     currentCity:"山西省",
    //   mapType:MapTypeEnum.BMAP_HYBRID_MAP
    // }
    this.polylineOptions = {
      strokeColor: 'yellow',
      strokeWeight: 10
    }
  }
  drawingManager: any;
  currentProjId: number;
  preCord: any;
  courses = [];
  highShow = false;
  normalShow = false;
  public opts: MapOptions
  public points: Array<Point> = [];
  public polylineOptions: PolylineOptions;

  public projects = [
    { secs: [] }
  ]
  public projects1 = []
  public projects2 = []
  polys = [];
  proj: Project = { delFlag: 0 };
  course: Course = { delFlag: 0 };
  section: Scetion = { delFlag: 0 };
  type = 1;
  _this = this;
  currentCouseId: any;
  staticHighWay: any = {};
  staticNormal: any = {};
  normalProjects: any = [];
  currProj: Project = {};
  secs: Array<Scetion> = [];
  camera:Camera={};
  debug = false;

  typeChange(e) {
    //0:course, 1 :project,2:section.
    var dic = { 0: "red", 1: "yellow", 2: "green" }
    console.log(drawingManager.polylineOptions.strokeColor = dic[e]);

    //当属于标段类型添加检查是否点在线上机制。
    if (e == 2) {
      drawingManager.hook = (point: Point) => {
        return BMapLib.GeoUtils.isPointOnPolyline(point, this.getOverlayById(this.currentProjId));
      }
    } else {
      drawingManager.hook = null;
    }
  }
  addPoly(proj) {
    var points = JSON.parse(proj.coordinate);
    var toPoints = this.m.toPoints(points,this.curiveLength,this.curive);
    var newPolyLine = new window.BMap.Polyline(toPoints, { strokeColor: proj.lineStyle, strokeWeight: proj.lineWidth });
    (newPolyLine as any).id = (proj.course ? "p" : "s") + proj.id;
    map.addOverlay(newPolyLine);
   // var newPoints = this.corToPoint(proj.coordinate);
   // this.m.animationLine(newPoints);

  }
  goToVideo(){
    this.router.navigate(['/video']);
  }
  ngOnInit(): void {
    this.route.queryParamMap.subscribe(queryParams => {
      this.debug = Boolean(queryParams.get("debug"))
    })

    this.http.get<any>(this.s.basePath + `/project/list/${markType.HIGHWAY}`).subscribe(res => {
      this.projects1 = res.data;
    });
    this.http.get<any>(this.s.basePath + `/project/list/${markType.NORMAL}`).subscribe(res => {
      this.projects2 = res.data;
    });
    this.http.get<any>(this.s.basePath + `/project/total`).subscribe(res => {
      this.staticHighWay = res.data[0];
    });
    this.http.get<any>(this.s.basePath + `/project/total2`).subscribe(res => {
      this.staticNormal = res.data[0];
    });
    this.http.get<any>(this.s.basePath + `/camera/total`).subscribe(res => {
      this.cameraSum = res.data[0];
    });
    this.http.get<any>(this.s.basePath + "/course/list").subscribe(res => {
      this.courses = res.data;
      //加载全局线路
      setTimeout(() => {
        this.loadPolys(res,false);
      }, 5000);
    });
    this.http.get<any>(this.s.basePath + "/scetion/list").subscribe(res => {
      this.allsecs = res.data;
    });
  }
  proj2Change($event, type) {
    map.clearOverlays();
    var proj: any = {};
    if (type == 1) {
    } else {
      proj = this.projects2.find(f => f.id == $event);
    }
    proj = this.projects1.find(f => f.id == $event);
    this.addPoly(proj);
    var points = this.corToPoint(proj.coordinate);
    map.setViewport(points);
  }
  toHighWay() {

    this.highShow = !this.highShow;

    if (this.highShow) {
      ///map.clearOverlays();
      this.http.get<any>(this.s.basePath + `/project/list/${markType.HIGHWAY}`).subscribe(res => {
        this.projects = res.data;
        var points =  this.loadPolys(res,true);
      });
    }

  }
  private loadPolys(res: any,animation:boolean) {
    var allPoints = [];
    res.data.forEach(obj => {
      this.addPoly(obj);
      if(animation){

         var newPoints = this.corToPoint(obj.coordinate);
         this.m.animationLine(newPoints);
      }
      allPoints = allPoints.concat(JSON.parse(obj.coordinate));
    });
    return allPoints;
    //map.setViewport(allPoints.map(p => ({ lng: p[0], lat: p[1] })));
  }

  toNormal() {
    map.clearOverlays();
    this.normalShow = !this.normalShow;


    this.http.get<any>(this.s.basePath + `/project/list/${markType.NORMAL}`).subscribe(res => {
      this.normalProjects = res.data;

    });

  }
  openDialog(id: string) {
    this.modalService.open(id);
  }


  corToPoint(json: string): Array<Point> {
    return JSON.parse(json).map(r => ({ lng: r[0], lat: r[1] }));
  }
  highLight(i: number, obj, type) {
    this.currProj = Object.assign({}, obj);
    var overlays = map.getOverlays();
    var cur = overlays.find(o => o.id == type + obj.id);
    timer(0, 200)
      .pipe(timeInterval(), pluck('interval'), take(6)).subscribe(index => {
        if (cur.isVisible()) {
          cur.hide();
        } else {
          cur.show();
        }
      });

    var points = this.corToPoint(obj.coordinate);

    //标段不定位
    if(type!='s'){
      map.setViewport(points);
    }


    //设置摄像头数据
    // this.http.get<any>(this.s.basePath + `/camera/totalByProjId?projId=`+obj.id).subscribe(res => {
    //   this.cameraSum ={project:1,total:res.data} ;
    // });

    //设置标注信息
    this.addLabel(points,obj);

    //设置动画效果
    this.m.animationLine(points)
  }

  setPrj(prj: Project) {
    this.http.get<any>(this.s.basePath + "/scetion/findListById/" + prj.id).subscribe(res => {
      prj.secs = res.data;
      this.loadPolys(res,false);
    });
  }
  setCamera(sec: Scetion) {
    // this.http.get<any>(this.s.basePath + "/camera/findListById/" + sec.id).subscribe(res => {
    //   // sec.cameras = res.data;
    //   // this.loadMarker(res);
    // });
  }
  addCourse(course: Course) {

    this.http.post<Course>(this.s.basePath + "/course/add", course).subscribe(res => {
      this.modalService.close('custom-modal-2');
    })
  }
  addSection(section: Scetion) {

    this.http.post<Scetion>(this.s.basePath + "/scetion/add", section).subscribe(res => {
      this.modalService.close('custom-modal-3');
    })
  }
  addCamera(camera: Camera) {

    this.http.post<Scetion>(this.s.basePath + "/camera/add", camera).subscribe(res => {
      this.modalService.close('marker');
    })
  }
  addProj(proj: Project) {
    this.http.post(this.s.basePath + "/project/add", proj).subscribe(res => {
      console.log(res)
    });
  }

  setTheme(theme){
    (window as any).map.setMapStyleV2({ styleJson: theme });
  }
  public polylineLoaded(polyline: BPolyline): void {
    (window as any).map = polyline.getMap();
  
    this.setBound();

    (window as any).map.setMapStyleV2({ styleJson: theme });
    map.enableScrollWheelZoom(true);
    map.centerAndZoom("山西省",11);
 
    this.dynamicScriptLoader.load('geouti','mapv').then();
    if (this.debug) {

      this.dynamicScriptLoader.load('drawing').then(data => {

        // Script Loaded Successfully
        drawingManager.addEventListener('overlaycomplete', e => {
          var overlay = e.overlay;

          var coordinates = [];
          if(overlay.getPath){

            var path = overlay.getPath();
            for (var i = 0; i < path.length; i++) {

              coordinates.push([path[i].lng, path[i].lat]);
            }
          }else{
            coordinates.push(overlay.getPosition())
          }
          if (overlay.toString() == '[object Polyline]') {

            if (this.type == CordType.PROJ) {
              this.proj.course = this.currentCouseId;
              this.proj.coordinate = JSON.stringify(coordinates);
              this.modalService.open('custom-modal-1');
            }
            else if (this.type == CordType.COURSE) {
              this.course.coordinate = JSON.stringify(coordinates);
              this.modalService.open('custom-modal-2');
            }
            else if (this.type == CordType.SECTION) {
              this.section.project = this.currentProjId;
              this.section.coordinate = JSON.stringify(coordinates);
              this.modalService.open('custom-modal-3');
            }
          }
          else if (overlay.toString() == '[object Polygon]') {
            // geojsonStr = {
            //   "type": "Polygon",
            //   "coordinates": [coordinates]
            // };
          }else if(overlay.toString() == "[object Marker]"){
            this.camera.coordinate = JSON.stringify(coordinates[0]);
            this.modalService.open('marker');
          }

       
          //   document.getElementById('result').innerHTML = "<div><span>左下角,右上角(经纬度)：</span><button class='btn'>复制</button><p class='copyText'>" + sw.lng + "," + sw.lat + "," + ne.lng + "," + ne.lat + "</p></div>"
          //     + "<div><span>左下角,右上角(墨卡托坐标)：</span><button class='btn'>复制</button><p class='copyText'>" + swMc.x + "," + swMc.y + "," + neMc.x + "," + neMc.y + "</p></div>"
          //     + "<div><span>坐标集(经纬度)：</span><button class='btn'>复制</button><p class='copyText'>" + pathStr + "</p></div>"
          //     + "<div><span>坐标集(墨卡托坐标)：</span><button class='btn'>复制</button><p class='copyText'>" + pathmcStr + "</p></div>"
          //     + "<div><span>geojson：</span><button class='btn'>复制</button><p class='copyText' style='white-space:nowrap;'>" + JSON.stringify(geojsonStr) + "</p></div>";
        });

      }).catch(error => console.log(error));
    }
    console.log('polyline loaded', polyline)
  }



  public polylineClicked({ polyline }): void {
    console.log('polyline clicked', polyline)
  }

  closeModal(id: string) {
    this.modalService.close(id);
  }
  setBound() {

    
    var project = map.getMapType().getProjection();
    var getPathStr = function (overlay) {
      var pathStr = "";
      var path = overlay.getPath();
      for (var i = 0; i < path.length; i++) {
        pathStr += path[i].lng + "," + path[i].lat + ",";
      }
      pathStr = pathStr.substr(0, pathStr.length - 1);
      return pathStr;
    }
    var bdary = new BMap.Boundary();
     bdary.get('山西省', function (rs) {   
       
      map.clearOverlays();
      //清除地图覆盖物
            //思路：利用行政区划点的集合与外围自定义东南西北形成一个环形遮罩层
            //1.获取选中行政区划边框点的集合rs.boundaries[0]
            var strs = new Array();
            strs = rs.boundaries[0].split(";");
            var ENWS = "";
            for (var i=0;i<strs.length;i++) {
                ENWS += strs[i] + ";"
            }
            //2.自定义外围边框点的集合
            var E_JW = "170.672126, 39.623555;";        //东
            var EN_JW = "170.672126, 81.291804;";       //东北角
            var N_JW = "105.913641, 81.291804;";        //北
            var NW_JW = "-169.604276,  81.291804;";     //西北角
            var W_JW = "-169.604276, 38.244136;";       //西
            var WS_JW = "-169.604276, -68.045308;";     //西南角
            var S_JW = "114.15563, -68.045308;";        //南
            var SE_JW = "170.672126, -68.045308 ;";     //东南角
            //3.添加环形遮罩层
            var ply1 = new BMap.Polygon(ENWS + E_JW + SE_JW + S_JW + WS_JW + W_JW + NW_JW + N_JW + EN_JW + E_JW, {strokeColor:"none",strokeOpacity:0,fillColor:"#0002069c",fillOpacity:"0.5"}); //建立多边形覆盖物
            map.addOverlay(ply1);//遮罩物是半透明的，如果需要纯色可以多添加几层
            //4. 给目标行政区划添加边框，其实就是给目标行政区划添加一个没有填充物的遮罩层
            var ply = new BMap.Polygon(rs.boundaries[0], {strokeWeight:0,strokeColor:"#114bf3",fillColor:"",fillOpacity:"0"});
            map.addOverlay(ply);
            map.setViewport(ply.getPath());//调整视野

      //获取行政区域
     //  map.clearOverlays();        //清除地图覆盖物       
    //   var count = rs.boundaries.length; //行政区域的点有多少个
    //   if (count === 0) {
    //     alert('未能获取当前输入行政区域');
    //     return;
    //   }
    //   var pointArray = [];
    //   var pathArr = [];
    //   for (var i = 0; i < count; i++) {
    //     var ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 1, fillOpacity: 0.05, strokeColor: "#f0f" }); //建立多边形覆盖物

    //     (function (ply) {
    //       ply.addEventListener('click', function () {
    //         // showResult(ply);
    //       });
    //     })(ply);
    //     pathArr.push(getPathStr(ply));

    //     map.addOverlay(ply);  //添加覆盖物
    //     //showResult(ply);
    //     var path = ply.getPath();
    //     var result = [];
    //     for (var j = 0; j < path.length; j++) {
    //       var px = project.lngLatToPoint(path[j]);
    //       result.push(px.x + ',' + px.y);
    //     }
    //     pointArray = pointArray.concat(path);
    //   }

        



    //    map.setViewport(pointArray);    //调整视野  
    //   // map.setMinZoom(8);

    });
  }
  /**
   * 
   * @param id id
   * @param type "s" = section ,"p"=project
   */
  getOverlayById(id: number, type: string = "p") {
    var overlays = map.getOverlays();
    return overlays.find(o => o.id == type + id);
  }
  addLabel(points:Array<Point>,proj){
          var center = {lng:0,lat:0}
      points.forEach(p => {
        center.lng+=p.lng;
        center.lat+=p.lat;
      });
      center.lng=center.lng/points.length;
      center.lat=center.lat/points.length;
      var label = new BMap.Label(`
      <div class="label-panel">
      <p class="header" style="margin:0">${proj.name}</p>
      <p style="margin:0;color:#eaab4e;">里程：<i>${proj.mileage || ""}Km</i></p>
      <p style="margin:0;color:#eaab4e;">投资：<i>${proj.capital || ""}亿</i></p>
      </div>`, {
        position: center 
    });
    map.addOverlay(label);

  }
}


