<template>
  <div  id="imgDiv" class="map" ref="mapRef">
    <div class="tools">
      <div class="text">您当前查看的是：</div>
      <el-select v-model="curOrganId" @change="changeOrgan" class="select" placeholder="Select" size="small">
        <el-option
            v-for="item in organList"
            :key="item.organId"
            :label="item.name"
            :value="item.organId"
        />
      </el-select>
      <el-select v-model="curAreaId" @change="changeArea" class="select" placeholder="Select" size="small">
        <el-option
            label="全部"
            value="-1"
        />
        <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </div>
  </div>
</template>

<script setup>


import * as util from "@/common/ol_common.js"
import * as KMap from '@/utils/ol-map/KMap';
import config from "@/api/config.js"
import {onMounted, ref} from "vue";
import {useStore} from "vuex";
import {newAreaFeature, newPoint ,redBoxStyle} from "../map.js"
import {miniStyle2} from "./Style";
import {WKT} from "ol/format";
import {ElMessage} from "element-plus";

let emits = defineEmits(["selectOrganIdAndAreaId","selectTree","initListener"])
let store = useStore()
const mapRef = ref("mapRef")
let map = null;
let vectorStyle = new KMap.VectorStyle()
let organList = ref([]);
let curOrganId = ref(null)
let areaList = ref([])
let curAreaId = ref(null)
let areaLayer = new KMap.VectorLayer("areaLayer",999,{style:(f)=>
      vectorStyle.getPolygonStyle("#ffffff10", "#ffffff",3)})
let treeLayer = new KMap.VectorLayer("treeLayer",999, {style:miniStyle2})

const initMap = () => {
  let location = store.getters.userinfo.location;
  curOrganId.value = store.getters.userinfo.curGardenId
  let coordinate = util.wktCastGeom(location).getFirstCoordinate()
  map = new KMap.Map(mapRef.value, 16.5, coordinate[0], coordinate[1]);
  let xyz = config.base_img_url + 'map/lby/{z}/{x}/{y}.png';
  map.addXYZLayer(xyz,{minZoom:15,maxZoom:20});

  let xyz2 = config.base_img_url3 + 'map/lby/{z}/{x}/{y}.png';
  map.addXYZLayer(xyz2,{minZoom:15,maxZoom:20});

  map.addLayer(areaLayer.layer)
  map.addLayer(treeLayer.layer)
}

const initOrgan = async ()=>{
  let {data,code} = await VE_API.organ.gardenData()
  organList.value = data;
  if(!curOrganId.value)
    curOrganId.value = data[0].organId
  await initArea(curOrganId.value)
  curAreaId.value = areaList.value[0].id
  await changeArea();
}

const initArea = async (organId) => {
  areaLayer.refresh()
  let {data,code} = await VE_API.area.list({organId})
  for(let item of data){
    areaLayer.addFeature(newAreaFeature(item))
  }
  areaList.value = data
}

const initTree = (organId, areaId) => {
  treeLayer.refresh()
  selectOrganIdAndAreaId(organId, areaId)
}

const initListener = ()=>{
  treeLayer.addSingleSelect(function (e){
    if(e.selected.length > 0){
      emits("selectTree", e.selected[0])
    }else{
      emits("selectTree", null)
    }
  },map.map)
  let area = areaList.value.find((item)=> item.id == curAreaId.value)
  emits("initListener",new WKT().readGeometry(area.pointWkt).getFirstCoordinate())
}

const changeOrgan = function(){
  initArea(curOrganId.value)
  initTree(curOrganId.value,-1)
}

const changeArea = function(){
  initTree(curOrganId.value, curAreaId.value)
  if(!curAreaId.value || curAreaId.value == -1){
    map.fit(areaLayer.source.getExtent())
  }else{
    map.fit(areaLayer.getFeatureById(curAreaId.value).getGeometry().getExtent())
  }
}

const selectOrganIdAndAreaId = function(organId, areaId){
  emits("selectOrganIdAndAreaId",organId, areaId)
  VE_API.tree.treeList({gardenId:organId,areaId}).then(({data,code})=>{
    for(let item of data){
      treeLayer.addFeature(newPoint(item))
    }
    emits("getTreeList", data)
  })
}


onMounted(async()=>{
  initMap()
  await initOrgan()
  initListener()
})
function setSelected(treeId){
  treeLayer.singleSelect.getFeatures().clear()
  if(!treeId)
    return;
  let f = treeLayer.getFeatureById(treeId);
  treeLayer.singleSelect.getFeatures().insertAt(0,f)
  map.view.setCenter(f.getGeometry().getFirstCoordinate())
}
function updateExtentFeature(feature){
  feature.setStyle(redBoxStyle())
  map.polygonLayer.refresh()
  map.polygonLayer.addFeature(feature)
}
function getOrganId(){
  return curOrganId.value
}
function getAreaId(){
  return curAreaId.value
}

defineExpose({
  setSelected, updateExtentFeature, getOrganId, getAreaId
});
</script>

<style lang="scss" scoped>
.map{
  position: relative;
}
.tools{
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: row;
  .select{
    width: 80px;
  }
  .text{
    line-height: 24px;
    color: #00FFF0;
    font-weight: bold;
  }
  z-index: 1000;
}
</style>
