var proId = localStorage.getItem("proId");
var selectLon = localStorage.getItem("selectLon");
var selectLat = localStorage.getItem("selectLat");
var cityName = localStorage.getItem("cityName");
var map;
let layer = '';
var tree;
var form;
var level = "";
var startDataNums = 2;
var loadIndex;
$(function () {
	layui.use(['layer','tree','form'], function () {
		layer = layui.layer; //只有执行了这一步，部分表单元素才会自动修饰成功
		tree = layui.tree;
		form = layui.form;
		init();
		madeBoundary(); //加载区域图

		getTowerBasicNum();
		getTreeData();
		tree.setChecked('treeId', ["P-"+proId]); // 勾选对应 id 值的节点
		$("#getCheckData").click(function () {
			map.clearOverlays();
			var checkedData = tree.getChecked('treeId'); // 获取选中节点的数据
			proId= "";
			if (checkedData.length == 0) {
				return;
			}
			for (let i = 0; i <checkedData[0].children.length; i++) {
				for (let j = 0; j < checkedData[0].children[i].children.length; j++) {
					proId += checkedData[0].children[i].children[j].id.replace("P-","")+",";
				}
			}
			proId = proId.substring(0,proId.length-1);
			selectLon =106.96;
			selectLat = 34.03;
			level = "6";
			loadIndex = layer.msg('加载中', {
				icon: 16,
				shade: 0.01
			});
			//获取省份名称
			// getCityName();
			init();
			getTowerBasicNum();
		})
	});
	setInterval(function (){
		changeData();
	},2000)
});

function changeData() {
	var checkedData = tree.getChecked('treeId'); // 获取选中节点的数据
	var dataNums = JSON.stringify(checkedData).length;
	if(startDataNums != dataNums){
		map.clearOverlays();
		var checkedData = tree.getChecked('treeId'); // 获取选中节点的数据
		if (checkedData.length == 0) {
			return;
		}
		proId= "";
		for (let i = 0; i <checkedData[0].children.length; i++) {
			for (let j = 0; j < checkedData[0].children[i].children.length; j++) {
				proId += checkedData[0].children[i].children[j].id.replace("P-","")+",";
			}
		}
		proId = proId.substring(0,proId.length-1);
		selectLon =106.96;
		selectLat = 34.03;
		level = "6";
		//获取省份名称
		// getCityName();
		// setTimeout(function(){
		init();
		getTowerBasicNum();
		// },500)

		startDataNums  = dataNums;
	}
}

function getCityName(){
	$.ajax({
		type: 'POST',
		async: false, // 默认异步true,false表示同步
		url: ctxPath + "/schedule/getCityName",// 请求地址
		dataType: 'json', // 服务器返回数据类型
		data: {proId:proId}, //获取提交的表单字段
		success: function (data){
			cityName = data;
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
		}
	});
}


function getTowerBasicNum(){
	$.ajax({
		type: 'POST',
		async: false, // 默认异步true,false表示同步
		url: ctxPath + "/schedule/getAllTowerBasicNum",// 请求地址
		dataType: 'json', // 服务器返回数据类型
		data: {proId:proId}, //获取提交的表单字段
		success: function (data){
			var obj = data.obj;
			$("#not_finish").text(parseInt(obj.team.basicNotFinishNum));
			$("#basic_num").text(parseInt(obj.team.basicFinishNum));
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
		}
	});
}

function init(){
	initMap();
	selectMap();
}

//设置区域图start
function madeBoundary() {
	datas = new Array(cityName !=''?cityName+"-":"湖南省");
//				datas = new Array("甘肃省-");
	var bdary = new BMap.Boundary();
	for(var i=0;i<datas.length;i++){
		getBoundary(datas[i],bdary);
	}
}

function getBoundary(data,bdary){
	data = data.split("-");
	bdary.get(data[0], function(rs){       //获取行政区域
		var count = rs.boundaries.length; //行政区域的点有多少个
		var pointArray = [];
		for (var i = 0; i < count; i++) {
			var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 3, strokeColor: "#0567FC",fillOpacity:0,fillColor: "rgba(191,227,243,0.5)"}); //建立多边形覆盖物
			map.addOverlay(ply);  //添加覆盖物
		}
	});
}

function initMap(){
	// 百度地图API功能
	map = new BMap.Map("allmap");    // 创建Map实例
	map.centerAndZoom(new BMap.Point(selectLon !=""?selectLon:112.98,selectLat !="" ?selectLat:28.19), level != "" ?  parseInt(level): 8)  // 初始化地图,设置中心点坐标和地图级别
	//添加地图类型控件
	map.addControl(new BMap.MapTypeControl({
		mapTypes:[
			BMAP_NORMAL_MAP,
			BMAP_HYBRID_MAP
		]}));
	map.setCurrentCity(cityName.replace("省",""));          // 设置地图显示的城市 此项是必须设置的
	map.enableScrollWheelZoom(true);
// 清除地图上的所有覆盖物
	map.clearOverlays();
	map.addEventListener('click', function (e) {
	});

}



function G(id) {
	return document.getElementById(id);
}
var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
	{"input" : "suggestId"
		,"location" : map
	})

ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
	var str = "";
	var _value = e.fromitem.value;
	var value = "";
	if (e.fromitem.index > -1) {
		value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
	}
	str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

	value = "";
	if (e.toitem.index > -1) {
		_value = e.toitem.value;
		value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
	}
	str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
	G("searchResultPanel").innerHTML = str;
});

var myValue;
ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
	var _value = e.item.value;
	myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
	G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
	setPlace();
});


function setPlace(){
	map.clearOverlays();    //清除地图上所有覆盖物
	function myFun(){
		var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
		console.log('经度：'+pp.lng, '纬度：'+pp.lat);
		map.centerAndZoom(pp, 18);
		map.addOverlay(new BMap.Marker(pp));    //添加标注
	}
	var local = new BMap.LocalSearch(map, { //智能搜索
		onSearchComplete: myFun
	});
	local.search(myValue);
}

function theLocation(){
	var city = document.getElementById("cityName").value;
	if(city != ""){
		map.centerAndZoom(city,11);      // 用城市名设置地图中心点
	}
}
//查询地图杆塔start
function selectMap(){
	loadIndex = layer.msg('加载中', {
		icon: 16,
		shade: 0.01
	});
	$.ajax({
		type: 'POST',
		async: true, // 默认异步true,false表示同步
		url: ctxPath + "/schedule/findAllTower",// 请求地址
		dataType: 'json', // 服务器返回数据类型
		data: {proId:proId}, //获取提交的表单字段
		success: function (data){
			var obj = data.obj;
			var result = obj;
			if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
				var points = [];  // 未施工
				var basicPoints = [];  // 未施工
				var towerPoints = [];  // 未施工
				for (var i = 0; i < result.didnTStartList.length; i++) {
					var p=createPoint(result.didnTStartList[i]);
					points.push(p);
				}
				for (var i = 0; i < result.basicFinishList.length; i++) {
					var p=createPoint(result.basicFinishList[i]);
					basicPoints.push(p);
				}
				for (var i = 0; i < result.towerFinishList.length; i++) {
					var p=createPoint(result.towerFinishList[i]);
					basicPoints.push(p);
				}
				for (let i = 0; i < result.beanList.length; i++) {
					// 添加自定义标注
					var point = new BMap.Point(result.beanList[i].lon, result.beanList[i].lat)
					var myIcon = new BMap.Icon("../../img/home/blue_frame.png", new BMap.Size(30, 30));
					var marker = new BMap.Marker(point, {icon: myIcon});
					map.addOverlay(marker);
					// 添加点击事件
					marker.addEventListener("click", function(e){
						var infoWindow = new BMap.InfoWindow("工程名称："+result.beanList[i].proName+"<br>所属分公司："+result.beanList[i].orgName);
						this.openInfoWindow(infoWindow, point);
						infoWindow.disableCloseOnClick()
					});
				}

				// // 创建标记点并添加到地图
				// for (var i = 0; i < points.length; i++) {
				// 	var pt = new BMap.Point(points[i].lng, points[i].lat);
				// 	// 创建自定义图标
				// 	var icon = new BMap.Icon("../../img/home/map_ash_1.png", new BMap.Size(30, 30));
				// 	var marker = new BMap.Marker(pt, {icon: icon});
				// 	marker.addEventListener("click", clickPoint);
				// 	map.addOverlay(marker);
				// }
				var pointCollection = createPointCollection(points,'#ff0000');
				var basicPointCollection = createPointCollection(basicPoints,'#76ea07');
				// var towerPointCollection = createPointCollection(towerPoints,'#df864c');
				pointCollection.addEventListener('click',clickPoint);
				basicPointCollection.addEventListener('click',clickPoint);
				// towerPointCollection.addEventListener('click',clickPoint);
				map.addOverlay(pointCollection);
				map.addOverlay(basicPointCollection);
				layer.close(loadIndex)
				// map.addOverlay(towerPointCollection);
			} else {
				alert('请在chrome、safari、IE8+以上浏览器查看本示例');
			}
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
		}
	});
}
//查询地图杆塔end
//创建点strat
function createPoint(respone){
	var p =new BMap.Point(respone.lon, respone.lat);
	p.towerName=respone.towerName;
	p.basicName=respone.basicName;
	p.groupTowersName=respone.groupTowersName;
	p.basicFinishTime=respone.basicFinishTime;
	p.groupTowersFinishTime=respone.groupTowersFinishTime;
	return p;
}
//创建点end


//设置杆塔样式start
function createPointCollection(points,color){
	var options = {
		size: BMAP_POINT_SIZE_BIG,// 定义点的尺寸为大，宽高为8px*8px。
		shape: BMAP_POINT_SHAPE_CIRCLE, //形状：正方形
		color: color //蓝色
	};
	var pointCollection = new BMap.PointCollection(points,options);
	return pointCollection;
}
//设置杆塔样式end

//杆塔点击事件start
function clickPoint(e){
	map.closeInfoWindow(); // 关闭之前的信息窗口
	let cent = "<span style='color:#ea9157'>" +e.point.towerName+"</span>";
	if (isEmpty(e.point.basicFinishTime)){
		cent +="<br/><span style='color:#151414'>" + e.point.basicName+"：</span><span style='color:red'>未完成</span>";
	}else {
		cent +="<br/><span style='color:#1c1b1b'>" + e.point.basicName+"："+e.point.basicFinishTime+"</span>";
	}
	// if (isEmpty(e.point.groupTowersFinishTime)){
	// 	cent +="<br/><span style='color:#212020'>" + e.point.groupTowersName+"：</span><span style='color:red'>未完成</span>";
	// }else {
	// 	cent +="<br/><span style='color:#212020'>" + e.point.groupTowersName+"："+e.point.groupTowersFinishTime+"</span>";
	// }
	console.log('clickPoint executed')
	console.log('cent：'+cent)

	let infoWindow = new BMap.InfoWindow(cent);
	console.log("11111111")
	// 监听点击事件
	let point = new BMap.Point(e.point.lng,e.point.lat);
	console.log("2222222")
	map.openInfoWindow(infoWindow,point); //开启信息窗口
	console.log("--------------------")
	infoWindow.disableCloseOnClick()

}
//杆塔点击事件end


//杆塔信息窗口start
var optsGt = {
	width : 100,     // 信息窗口宽度
	height: 80,     // 信息窗口高度
	borderRadius: 5
};

function getPack(type){
	if(type==1){
		document.getElementById("main").style.width='0%';
		document.getElementById("packUp").style.display='none';
		document.getElementById("unwind").style.display='block';
	}else if(type==2){
		document.getElementById("main").style.width='26%';
		document.getElementById("packUp").style.display='block';
		document.getElementById("unwind").style.display='none';
	}
}

/**
 * layui树结构
 */
function getTreeData() {
	$.ajax({
		type: 'post',
		url: ctxPath + '/schedule/tree',//数据接口
		dataType: 'json', // 服务器返回数据类型
		async: false,
		data: {
		},
		success: function (data) {
			var results = [];
			for (let i = 0; i < data.length; i++) {
				if (data[i].level == '0') {
					data[i].spread = true
					results.push(data[i])
				}
			}
			for (let i = 0; i < results.length; i++) {
				results[i].children = []
				for (let j = 0; j < data.length; j++) {
					if (results[i].id == data[j].parentId) {
						data[j].spread = true
						results[i].children.push(data[j])
					}
				}
			}
			for (let i = 0; i < results.length; i++) {
				//root
				for (let k = 0; k < results[i].children.length; k++) {
					//parent = 0
					results[i].children[k].children = []
					for (let j = 0; j < data.length; j++) {
						if (results[i].children[k].id == data[j].parentId) {
							data[j].spread = true

							results[i].children[k].children.push(data[j])
						}
					}
				}
			}
			renderTree(results);

		},
		error: function (err) {
			console.log("获取工程下拉列表出错：", err);
		}
	});
}

function renderTree(results){
	tree.render({
		elem: '#tree'
		, id: 'treeId'
		, data: results
		, spread: true
		, showLine: false  // 是否开启连接线
		,showCheckbox: true  // 是否显示复选框
		,onlyIconControl: true  // 是否仅允许节点左侧图标控制展开收缩
	});
}