<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<script src="<c:out value="/js/openlayers/ol.js" />"></script>
<script src="<c:out value="/js/openlayers/proj4.js" />"></script>
<link href="<c:out value="/css/normalize.css" />" rel="stylesheet">
<link href="<c:out value="/css/openlayers/ol.css" />" rel="stylesheet">
<script src="../../../js/admin/fieldView.js"></script>
<script>
	function fieldVerify(){
		alert('준비중');
	}

	function fieldReflect(){
		alert('준비중');
	}

	$(function() {
		drawingObj();
		makePropPaging();
		makePropTable();
	});

	var field_data = JSON.parse('${fieldDataVO.field_data}');
	var wkt = null;
	proj4.defs('EPSG:5186', '+proj=tmerc +lat_0=38 +lon_0=127 +k=1 +x_0=200000 +y_0=600000 +ellps=GRS80 +units=m +no_defs');
	var baseMap = new ol.layer.Tile({
		title : 'vworldMap',
		visible : true,
		type : 'base',
		source : new ol.source.XYZ({
			url : 'http://api.vworld.kr/req/wmts/1.0.0/5616CAD1-5D79-3EE3-87D5-878A4AD0F91F/Base/{z}/{y}/{x}.png'
		})
	});

	var view = new ol.View({
		center : ol.proj.transform([ 203766.984, 541132.2 ], 'EPSG:5186', 'EPSG:3857'),
		zoom : 18, // 초기화면 zoom level
		minZoom : 1, // 최소 zoom level
		maxZoom : 19, // 최대 zoom level
	});

	var map = new ol.Map({
		layers : [ baseMap ],
		logo : false, //우측하단 로고 제거
		target : 'map',
		loadTilesWhileAnimating : true,
		view : view
	});

	var format = new ol.format.WKT();
	var objVectorSource = new ol.source.Vector({});
	var objVectorLayer = new ol.layer.Vector({
		source : objVectorSource,
		style : objStyle
	});

	var cursorStyle = "";
	var selected = null;
	map.on("pointermove", function(e) {
		if (selected !== null) {
			selected.setStyle(undefined);
			selected = null;
		}
		var newStyle = this.hasFeatureAtPixel(e.pixel) ? "pointer" : "";
		newStyle !== cursorStyle && $(this.getTargetElement()).css("cursor", cursorStyle = newStyle);
		map.forEachFeatureAtPixel(e.pixel, function(f) {
			selected = f;
			f.setStyle(highlightStyle);
			return true;
		});
	});

	var highlightStyle = new ol.style.Style({
		stroke : new ol.style.Stroke({
			color : '#3399CC',
			width : 8,
		}),
	});

	// feature click evt
	map.on('click', function(event) {
		map.forEachFeatureAtPixel(event.pixel, function(feature, layer) {
			var idx = feature.get("idx");
			makePropTable(idx);
		})
	});

	function objStyle(feature, resolution) {
		var selected = feature.get('selected');
		var style = null;
		if (selected) {
			style = new ol.style.Style({
				stroke : new ol.style.Stroke({
					color : '#f00',
					width : 5
				})
			});
		} else {
			style = new ol.style.Style({
				stroke : new ol.style.Stroke({
					color : '#52b4e7',
					width : 5
				})
			});
		}
		return style;
	}

	function resetObjStyle() {
		var feature = getObjFeatureBySelected();
		if (feature) {
			feature.set("selected", false);
		}
	}

	function makePropTable(idx) {
		if (idx == null)
			idx = 0;
		$("#fieldDataBody > tr").remove();

		var num = 0;
		var tags = "";
		for(var i in field_data[idx].prop) {
			num++;
			if(num % 2 == 0){
				tags += "<th>" + i + "</th><td>" + field_data[idx].prop[i] + "</td></tr>";
			}else{
				tags += "<tr><th>" + i + "</th><td>" + field_data[idx].prop[i] + "</td>";
			}
		}
		$("#fieldDataBody").append(tags);

		nowPagingOn(idx);
		resetObjStyle();

		//중심좌표 구하기?
		//var aa = feature.getGeometry().v;
		//var oo = ol.extent.getCenter(aa);

		var center = field_data[idx].center;
		var feature = getObjFeatureByIdx(idx);

		moveCenter(center);
		if (feature) {
			feature.set("selected", true);
		}
	}

	function nowPagingOn(idx){
		$(".paging_li").removeClass("fieldPagingOn")
		$("#paging_li"+idx).attr("class", "fieldPagingOn paging_li");
	}

	function makePropPaging() {
		var pagingNumber = 0;
		for (var idx in field_data) {
			pagingNumber++;
			$("#fieldDataPaging").append('<li class="paging_li" id="paging_li'+idx+'" onclick="makePropTable(' + idx + ')">' + pagingNumber+ '</li>');
		}
	}

	function drawingObj() {
		objVectorSource.clear();
		var objFeatures = [];
		for (var idx in field_data) {
			var objFeature = format.readFeature(field_data[idx].WKT, {
				dataProjection : 'EPSG:5186',
				featureProjection : 'EPSG:3857'
			});
			objFeature.setProperties({
				"idx" : idx,
				"selected" : false
			});
			objFeatures.push(objFeature);
		}
		objVectorSource.addFeatures(objFeatures);
		map.addLayer(objVectorLayer);
	}

	function moveCenter(center) {
		var coordinates = ol.proj.transform(center, 'EPSG:5186', 'EPSG:3857');
		map.getView().setCenter(coordinates);
	}

	function getObjFeatureBySelected() {
		var features = objVectorSource.getFeatures();
		var feature = null;

		for (var i = 0, size = features.length; i < size; i++) {
			if (features[i].get('selected') == true) {
				feature = features[i];
				break;
			}
		}
		return feature;
	}

	function getObjFeatureByIdx(idx) {
		var features = objVectorSource.getFeatures();
		var feature = null;
		for (var i = 0, size = features.length; i < size; i++) {
			if (features[i].get('idx') == idx) {
				feature = features[i];
				break;
			}
		}
		return feature;
	}
</script>

	    <div class="section_title">
	      <!-- <p>현장 지원 시스템</p> -->
	    </div>

		<div class="section_content">
   
		    <table class="detail_table">
		        <thead>
		          <tr>
		            <th colspan="6">담당자</th>
		          </tr>
		        </thead>
		        <tbody>
		         	<tr>
		         		<th>소속</th>
						<td class="text-center"><c:out value='${userVO.company}' /></td>
						<th>담당자</th>
						<td class="text-center"><c:out value='${userVO.name}' /></td>
						<th>연락처</th>
						<td class="text-center"><c:out value='${userVO.phonenum}' /></td>
		         	</tr>
				</tbody>
			</table>
    
			<table class="detail_table">
		        <thead>
		          <tr>
		            <th colspan="4">지도정보</th>
		          </tr>
		        </thead>
		        <tbody>
		         	<tr>
		         		<th>레이어 ID</th>
		         		<td class="text-center"><c:out value="${fieldDataVO.layer_id}" /></td>
		         		<th>수집일</th>
		         		<td class="text-center"><c:out value="${fieldDataVO.save_date}" /></td>
		         	</tr>
		         	<tr>
		         		<th>지역</th>
		         		<td class="text-center"><c:out value="${fieldDataVO.region}" /></td>
		         		<th>상태</th>
		         		<td class="text-center">
		         			<c:choose>
								<c:when test="${fieldDataVO.status eq '0'}">
									<span class="label label-warning">수집</span> 
								</c:when>
								<c:when test="${fieldDataVO.status eq '1'}">
									<span class="label label-danger">검증실패</span> 
								</c:when>
								<c:when test="${fieldDataVO.status eq '2'}">
									<span class="label label-success">검증성공</span> 
								</c:when>
								<c:when test="${fieldDataVO.status eq '3'}">
									<span class="label label-danger">반영실패</span> 
								</c:when>
								<c:when test="${fieldDataVO.status eq '4'}">
									<span class="label label-success">반영</span> 
								</c:when>
							</c:choose>
		         		</td>
		         	</tr>
		         	<tr>
		         		<th>설명</th>
		         		<td></td>
		         		<th>오류내용</th>
		         		<td></td>
		         	</tr>
		        </tbody>
		      </table>

			<div class="field_data_content">

				<div class="mapWrap">
					<div class="map-title">측량데이터</div>

					<div class="map" id="map">	</div>
				</div>				
				
				
				<div class="fieldDataDiv">
					<table class="fieldDataTable" id="fieldDataTable">
						<thead>
				       		<tr>
				       			<th colspan="4">속성정보</th>
				       		</tr>
						</thead>
						<tbody id="fieldDataBody">
						
						</tbody>
					</table>
				</div>
				
				<ul id="fieldDataPaging" class="fieldDataPaging"></ul>


		    	
			</div>
		
		      
			<div class="section_btn">
				<p class="search_p1">
					<input class="btn btn-primary" type="button" value="목록" onclick="location.href='/admin/fieldData'" />
				</p>
				<p class="search_p2">
					<input class="btn btn-secondary" type="button" value="표준DB변환 및 검증" onclick="fieldVerify();" />
			        <input class="btn btn-success" type="button" value="반영" onclick="fieldReflect();" />
				</p>
			</div>
		</div>