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 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;
  markers: any;
  map: 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.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={};
  marker:any={};
  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;
    this.map.addOverlay(newPolyLine);
   // var newPoints = this.corToPoint(proj.coordinate);
   // this.m.animationLine(newPoints);

  }
  goToVideo(){
    this.router.navigate(['/video']);
  }
  ngOnInit(): void {
    this.map = new window.BMap.Map(("baidu-map"), { 
      enableMapClick: true
    });
    (window as any).map=this.map;
     this.map.setMapStyleV2({ styleJson: theme });
    this.map.enableScrollWheelZoom(true);
    //this.map.enableContinuousZoom()
    this.map.centerAndZoom("山西省",11);
    var _map =this.map;
    var maping = {8:11,9:15,10:20,11:22,12:25,13:26,14:28,15:29}
    this.map.addEventListener("zoomend", function() {
      var curZoom =_map.getZoom();
      var collections = document.getElementsByClassName("label-panel2");
      var marks = document.getElementsByClassName("mark");
      for (const key in collections) {
        if (collections.hasOwnProperty(key)) {
          const element = collections[key];
          const mark = marks[key];
          (element as any).style.fontSize=maping[curZoom]+"px";
          (mark as any).style.fontSize=maping[curZoom]+"px";
        }
      }
    });
    this.setBound();
    this.route.queryParamMap.subscribe(queryParams => {
      this.debug = Boolean(queryParams.get("debug"))
    })

    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 + `/camera/list`).subscribe(res => {
      this.markers = res.data;
      // this.loadLabels();
    });
    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 + "/mapLable/list").subscribe(res => {
      // this.maplabes = res.data;
      //加载labels
     // setTimeout(() => {
        this.loadLabels(res.data);
      //}, 5000);
    });
    this.http.get<any>(this.s.basePath + "/scetion/list").subscribe(res => {
      this.allsecs = res.data;
    });
 
  }
  proj2Change($event, type) {
    this.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);
    this.map.setViewport(points);
  }
  loadLabels(data){

    //var labels = [{lng:112.43176242674386,lat:37.78663390039693,text:"test1"}];
    // var labels = data.map(d=>({...(JSON.parse(data.coordinate)),text:d.name}));
    data.forEach(label => {
      this.addLabel2(label);
    });
  }
  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);
      });
    }else{
      this.map.centerAndZoom("山西省",8);
    }

  }
  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() {
    this.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 = this.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'){
       // this.map.setViewport(points,{
      //   enableAnimation:true,
      //   delay:5000
      // });
      var view = this.map.getViewport(points,{enableAnimation:true,delay:2000});
         
         this.map.panTo(view.center,{duration:1000});
        //  var orginZoom = this.map.getZoom();
        //  var dur =view.zoom - this.map.getZoom();
        //  timer(0, 200)
        //  .pipe(timeInterval(), pluck('interval'), take(dur)).subscribe((index:any)=>{

        
        //  // this.m.dispatchWheelEvent_Chrome(document.getElementById("baidu-map"),10);
        //   }
        //  );
         this.map.centerAndZoom(view.center,view.zoom);
        //  setTimeout(() => {
        //    this.m.dispatchWheelEvent_Chrome(document.getElementById("baidu-map"),50);
        //    this.map.centerAndZoom(view.center,view.zoom);
        //    //this.map.dispatchWheelEvent_Chrome
        //   }, 1000);
        
    }


    //设置摄像头数据
    // 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');
    })
  }
  addMarker(marker){

    this.http.post<Scetion>(this.s.basePath + "/mapLable/add", marker).subscribe(res => {
      this.modalService.close('marker');
    })
  //  localStorage.setItem("marker_"+marker.name,JSON.stringify(marker.coordinate));
  //  this.closeModal('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 {
  //   this.map = polyline.getMap();
  
  //   this.setBound();

  //   this.map.setMapStyleV2({ styleJson: theme });
  //   this.map.enableScrollWheelZoom(true);
  //   this.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.marker.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 = this.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 _this=this;
    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"}); //建立多边形覆盖物
            _this.map.addOverlay(ply1);//遮罩物是半透明的，如果需要纯色可以多添加几层
            //4. 给目标行政区划添加边框，其实就是给目标行政区划添加一个没有填充物的遮罩层
            var ply = new BMap.Polygon(rs.boundaries[0], {strokeWeight:0,strokeColor:"#16e8d6",fillColor:"",fillOpacity:"0"});
            _this.map.addOverlay(ply);
            _this.map.setViewport(ply.getPath());//调整视野
    });
  }
  /**
   * 
   * @param id id
   * @param type "s" = section ,"p"=project
   */
  getOverlayById(id: number, type: string = "p") {
    var overlays = this.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 
    });
    this.map.addOverlay(label);

  }

  addLabel2(label){
  
var label = new BMap.Label(`
<div style="background:${label.divStyle};font-size:11px;" class="label-panel2">
${label.name}
</div>
<div class='mark' style="font-size:11px;">${label.mark}</div>
`, {
  position: JSON.parse(label.coordinate),
  // offset:{width:5,height:-10}
});
this.map.addOverlay(label);

}
}


