<template>
	<div class="app-container" style="margin: 0; position: relative;">
		<div id="container">

		</div>
		<div id="search-box">
			<el-input v-model="keyWord" placeholder="请输入电站编码、用户姓名进行搜索" clearable></el-input>
			<el-button icon="el-icon-search" @click="search()"></el-button>
		</div>
		<div class="top-data">
			<h3>运行电站：{{ total }}</h3>
			<p style="color: red;font-weight: bolder;">故障：{{ totalError }}</p>
		</div>
		<!-- <div style="padding-bottom: 10px;">
			<div class="marker-content">
				<div class="txt">XM1002039-009<span>王贤</span></div>
				<ul>
					<li>
						<div>装机功率(KW)</div>
						<big>39</big>
					</li>
					<li>
						<div>日发电量(度)</div>
						<big>39</big>
					</li>
					<li>
						<div>实时功率(KW)</div>
						<big>39</big>
					</li>
					<li>
						<div>累计电量(万度)</div>
						<big>39</big>
					</li>
				</ul>
			</div>
		</div> -->
	</div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'; //引入
import func from '@/utils/func';
import { getMapDistribute, queryList, mapSearch} from "@/api/nh/powerStation";
export default {
	name: "MapSpread",
	data() {
		return {
			baseUrl:import.meta.env.VITE_APP_BASE,
			map: null,//初始化 map 对象
			keyWord: '',
			markers: [],//marker点
			txts:[],
			total: 0,
			totalError: 0,
			province: "",
			colors: {},
			infoWindow: null,
			data: [],
			disProvince: null
		};
	},
	created() {
		//DOM初始化完成进行地图初始化
		this.initMap();
	},
	methods: {
		initMap() {

			this.total = 0, this.totalError = 0;
			let centerPoint = [116.397428, 39.90923];

			AMapLoader.load({
				key: "727b25e7366ab5015225754e8ee00fef", //此处填入我们注册账号后获取的Key
				version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
				plugins: [''], //需要使用的的插件列表，如比例尺'AMap.Scale'等
			}).then((AMap) => {
				this.map = new AMap.Map("container", {
					zoom: 5,
					center: centerPoint
				});
				this.initMapDistribution();
			}).catch(e => {
			})
		},
		toProviceMap() {
			let that = this;
			// let centerPoint = [116.397428, 39.90923];
			// that.map.remove(that.txts);
			if(that.disProvince)
			that.map.remove(that.disProvince);
			if (that.markers.length) {
				that.map.clearInfoWindow();
				that.map.remove(that.markers);
				
				// that.map.removeAll();
			}

			let adcode = 130000;
			let centerPoint = [];

			if (this.province != "") {
				let position = func.getProvicePosition(this.province);
				adcode = func.getAdCode(this.province);
				centerPoint = [position.longitude, position.latitude];
				this.queryPowerStation();
			}

			// 创建行政区图层
			this.disProvince = new AMap.DistrictLayer.Province({
				zIndex: 12,
				adcode: [adcode],
				depth: 1,
				styles: {
					'fill': function (properties) {
						var adcode = properties.adcode;
						return that.getColorByAdcode(adcode);
					},
					'province-stroke': 'cornflowerblue',
					'city-stroke': 'white', // 中国地级市边界
					'county-stroke': 'rgba(255,255,255,0.5)' // 中国区县边界
				}
			});

			this.disProvince.setMap(this.map);
			this.map.setCenter(centerPoint);
			this.map.setZoom(7);

		},
		getColorByAdcode(adcode) {
			if (!this.colors[adcode]) {
				var gb = Math.random() * 155 + 50;
				this.colors[adcode] = 'rgb(' + gb + ',' + gb + ',255)';
			}

			return this.colors[adcode];
		},
		//获取地标数据
		initMapDistribution() {
			const that = this;
			getMapDistribute().then(res => {
				res.data.data.forEach(item => {
					this.addTxtMarker(item);
					this.total += item.total;
					this.totalError += item.error;
				});
			})
		},
		//获取地标数据
		addCircle(item) {
			let that = this;
			let img = this.baseUrl+"/img/blue_circle.png";
			if (item.status != 1) {
				img = this.baseUrl+"/img/red_circle.png";
			}

			var icon = new AMap.Icon({
				image: img,
				imageSize: new AMap.Size(18, 18),
				size: new AMap.Size(36, 36), // 设置为图标实际尺寸
				anchor: "bottom-center" // 根据图标实际锚点调整
			});

			// 构造点标记
			var marker = new AMap.Marker({
				icon: icon,
				position: [item.longitude, item.latitude]
			});

			var info = [];
			info.push("<b>电站编码：" + item.stationCode + "</b>");
			info.push("业主：" + item.ownerName + "/" + item.ownerPhone);
			info.push("地址：" + item.province + item.city + item.district + item.address + "")
			info.push("<a href='#' id='to-station-detail' data-id='"+item.id+"'>查看详情</a>")
			marker.content = info.join("<br/>");
			marker.title = item.id;

			// marker.on('click', function(){
			// 	localStorage.setItem('power_station_detail_id',JSON.stringify(item.id));
			// 	that.$router.push('/nh/powerStationDetail');
			// });
			// 添加点击事件
			marker.on('click', function(event) {
				localStorage.setItem('power_station_detail_id',JSON.stringify(item.id));
				that.$router.push('/nh/powerStationDetail');
			});

			marker.on('mouseover', that.openInfo);

			


			this.markers.push(marker);

			this.map.add(marker);

			if(that.disProvince==null){

				this.map.setFitView();
			}
		},
		search(){
			let that = this;
			if(that.disProvince){

				that.map.remove(that.disProvince);
			}
			that.map.remove(that.txts);
			that.map.clearInfoWindow();
			that.map.remove(that.markers);

			that.disProvince=null;

			if(this.keyWord){
				mapSearch(this.keyWord).then(res=>{
					let data = res.data.data;
					data.forEach(item => {
						this.addCircle(item);
					})
				})
			}else{
				this.initMapDistribution();
			}
			


		},
		queryPowerStation() {
			let values = {
				province: this.province,
				stationCode: this.keyWord,
				current: 1,
				size: 1000
			};

			queryList(values).then(res => {
				const data = res.data.data;
				this.data = data.records;
				this.data.forEach(item => {
					this.addCircle(item);
				})
			});
		},
		toStationDetail(id){
			alert(id)
		},
		openInfo(e) {
			let that = this;
			if (this.infoWindow == null) {
				this.infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(10, -10) });
			}

			this.infoWindow.setContent(e.target.content);
			this.infoWindow.open(this.map, e.target.getPosition());

			var infoContent = document.getElementById('to-station-detail');

			let detail_id = infoContent.getAttribute("data-id");
			// localStorage.setItem('power_station_detail_id',JSON.stringify(detail_id));
			// that.$router.push('/nh/powerStationDetail');

			infoContent.addEventListener('click', function() {
				localStorage.setItem('power_station_detail_id',JSON.stringify(detail_id));
				that.$router.push('/nh/powerStationDetail');
			});

		},
		addTxtMarker(item) {
			let that = this;
			let pos = func.getProvicePosition(item.province);
			let point = new AMap.LngLat(pos.longitude, pos.latitude)
			console.log("point:" + point)
			var text = new AMap.Text({
				title: item.province,
				text: '<b>' + item.province + '：' + item.total + '<b/><p style="color:red;">故障：' + item.error + '<p/>',
				anchor: 'center', // 设置文本标记锚点
				// draggable:true,
				cursor: 'pointer',
				// angle:10,
				style: {
					'padding': '10px 0 0 10px',
					'border-radius': '5px',
					// 'background-color': 'white',
					'width': '100px',
					'border-width': 1,
					'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
					'text-align': 'left',
					'font-size': '12px',
					'color': 'blue'
				},
				position: point
			});
			text.on('click', markerClick);
			function markerClick(e) {
				that.province = e.target._originOpts.title;
				// localStorage.setItem('map_province_name',province);
				// that.$router.push('/nh/mapProvice');
				// that.initMap();
				that.toProviceMap();
			}
			text.setMap(this.map);

			this.txts.push(text)
		}
	}
};
</script>

<style rel="stylesheet/scss" lang="scss">
#container {
	width: 100%;
	height: calc(100vh - 84px);
}

.top-data {
	position: absolute;
	right: 30px;
	top: 30px;
}


#search-box {
	position: absolute;
	left: 30px;
	top: 30px;
	width: 530px;
	height: 50px;
	padding: 0 0 0 10px;
	background-color: #ffffff;
	box-shadow: 4px 4px 20px 0px rgba(0, 0, 0, 0.2);
	display: flex;
	align-items: center;

	.el-input__inner {
		border: 0;
		font-size: 14px;
	}

	.el-button {
		width: 70px;
		height: 50px;
		background-color: #117fbc;
		margin-left: 10px;
		border-radius: 0;
		border: 0;
		font-size: 24px;
		color: #fff;
	}
}

.marker-content {
	width: 390px;

	.txt {
		font-size: 16px;
		padding: 5px 10px 5px;
		font-weight: 600;

		span {
			margin-left: 16px;
		}
	}

	ul {
		display: flex;
		flex-wrap: wrap;

		li {
			width: calc(50% - 10px);
			text-align: center;
			background-color: #f5f6fa;
			border-radius: 3px;
			margin: 5px;
			padding: 5px 5px;
			font-size: 14px;
			color: #555;
			list-style: none;


			big {
				font-size: 18px;
				margin-top: 10px;
				display: inline-block;
				color: #222;
			}
		}
	}
}
</style>
