let field_data;
let map;
let fieldViewModal;

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');


let wkt = null;

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

let cursorStyle = "";
let selected = null;

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

$(function () {
  // fieldViewModal = new bootstrap.Modal(document.getElementById('fieldViewModal'));
  fieldViewModal = document.getElementById('fieldViewModal');
  fieldViewModal.addEventListener('shown.bs.modal', function (event) {
    makePropPaging();
    drawingObj();
    makePropTable();
  })

})

$(document).on('click', '.fieldDataTr', function () {
  const dataid = $(this).attr("data-id");
  $.ajax({
    url: '/admin/fieldData/' + dataid,
    type: 'GET',
    dataType: "html",
    success: function (html) {
      $("#fieldViewModalBody").empty().append(html);
      $(fieldViewModal).modal('show')
    },
    error: function () {

    }
  });
})
$(document).on("click", ".statusTab", function () {
    const chkBox = $(this).find(".statusChkBox")[0]
    chkBox.checked = !chkBox.checked;
    $("[name='searchForm']").submit();
})

function fn_link_page(pageNo) {
    document.searchForm.pageIndex.value = pageNo;
    document.searchForm.action = "<c:url value='/admin/fieldData' />";
    document.searchForm.submit();
}

function getCheckoxValue() {
    const query = 'input[name="check1"]:checked';
    const selectedEls = document.querySelectorAll(query);
    let result = '';
    selectedEls.forEach((el) => {
        result += el.value + ' ';
    });

    // 출력
    document.getElementById('result').innerText
        = result;
}


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

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

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>" + numberFormatter(field_data[idx].prop[i], 2) + "</td></tr>";
    } else {
      tags += "<tr><th>" + i + "</th><td>" + numberFormatter(field_data[idx].prop[i],2) + "</td>";
      // 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 numberFormatter(num,pointer){
  if(isNaN(num)){
    return num;
  }else{
    const dotPoint = Math.pow(10,pointer)
    return Math.round(num*dotPoint)/dotPoint;
  }
}
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();

  let 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'
    })
  });


  let 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
  });

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

  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;
    });
  });


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

  map.addLayer(objVectorLayer);
  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);
}

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;
}
