
<template>
  <div>

    <a-modal
      v-model:open="open"
      :title="openTitle"
      width="100%"
      wrap-class-name="full-modal"
      :footer="null"
      :afterClose="handleClose"
    >
      <div class="button-panel">
        <a-button
          type="primary"
          @click="onEditorClear"
        >{{ buttonName }}</a-button>
        <a-button
          type="primary"
          @click="onEditorComplete"
        >完成</a-button>
      </div>
      <div
        class="map-container"
        style="width: auto; height: auto;"
      >
        <tlbs-map
          ref="mapRef"
          :api-key="config.map.apiKey"
          :center="center"
          zoom="16"
          :control="control"
          :options="options"
          @map_inited="onMapInited"
        >
          <tlbs-geometry-editor
            ref="editorRef"
            action-mode="draw"
            selectable
            @draw_complete="onDrowComplet"
            @draw_error="onDrawError"
            @adjust_complete="onAdjustComplete"
            @adjust_error="onAdjustError"
            @delete_complete="onDeleteComplete"
          />
        </tlbs-map>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps } from 'vue'
import { callOperate } from '@/apis/call.js'
import { message } from 'ant-design-vue'
import { isNullOrEmpty } from '@/utils/tools.js'
import config from '@/utils/config.js'
const props = defineProps({
  onCallBack: {
    type: Function,
    required: true
  },
  openTitle: {
    type: String,
    default: '' // Default value in case no openTitle is provided
  }
});
const open = ref(false);
const showModal = (data) => {
  if (data) {
    loadMap(data);
  }
  open.value = true;
};
const handleClose = () => {
  open.value = false;
  ClearEditor();
  if (props.onCallBack) {
    props.onCallBack(formData.value);
  }
};
defineExpose({ showModal });

const formData = ref({
  "regionId": "",
  "regionName": "",
  "simpleName": "",
  "zoneId": "",
  "points": [],
  "shapeType": 2, // 1:圆形 2:多边形
  "radius": 0, // 圆形半径
});

let timer = null;
const loadMap = (dataRegion) => {
  if (editorRef.value) {
    clearTimeout(timer);
    if (dataRegion) {
      const { operationRegionId } = dataRegion;
      callOperate("/ebikeRegion/getOperationById?regionId=" + operationRegionId, {}, "get").then((res) => {
        if (res.code != 200) {
          message.error(res.message)
          return
        }
        const { operationRegionName, simpleName, zoneId, points, shapeType, radius } = res.data;
        formData.value = {
          "operationRegionId": operationRegionId,
          "operationRegionName": operationRegionName,
          "simpleName": simpleName,
          "zoneId": zoneId,
          "points": points,
          "shapeType": shapeType, // 1:圆形 2:多边形
          "radius": radius, // 圆形半径	
        }
        loadGeometry();
      });
    }
  }
  else {
    timer = setTimeout(() => {
      loadMap(dataRegion);
    }, 1000)
  }
};

let shapeId = null;
const loadGeometry = () => {
  const { points, shapeType, regionId, radius } = formData.value;
  shapeId = 'polygon' + regionId;
  if (shapeType == 1) {
    shapeId = 'circle' + regionId;
  }
  if (points) {
    if (shapeType == 1) {
      const circleGeometries = [];//editorRef.value.circle.getGeometries();
      if (circleGeometries.length > 0) {
        circleGeometries.forEach((geometry) => {
          editorRef.value.circle.remove(geometry); // 删除之前的图形数据
        });
      }
      circleGeometries.push({
        id: shapeId, // 圆形图形数据的标志信息
        styleId: 'circle', // 样式id
        radius: radius, // 圆形的半径
        center: new TMap.LatLng(points[0].latitude, points[0].longitude),
        properties: {
          // 圆形的属性数据
          title: 'circle',
        },
      });
      editorRef.value.circle.setGeometries(circleGeometries);
      //设置视野范围
      const mycircle = editorRef.value.circle.getGeometryById(shapeId);
      const boundary = TMap.geometry.computeBoundingRectangle(mycircle.paths);
      mapRef.value.map.fitBounds(boundary, {
        padding: 100, // 设置地图边界的内边距
      });
    }
    else if (shapeType == 2) {
      const paths = [];
      points.forEach((point) => {
        paths.push(new TMap.LatLng(point.latitude, point.longitude));
      });
      const polygonGeometries = [];//editorRef.value.polygon.getGeometries();
      polygonGeometries.push({
        id: shapeId, // 多边形图形数据的标志信息
        styleId: 'polygon', // 样式id
        paths, // 多边形的位置信息
        properties: {
          // 多边形的属性数据
          title: 'polygon',
        },
      });
      editorRef.value.polygon.setGeometries(polygonGeometries);
      // var position = TMap.geometry.computeCentroid(paths);
      // mapRef.value.map.setCenter(position);
      //设置视野范围
      const mypolygon = editorRef.value.polygon.getGeometryById(shapeId);
      const boundary = TMap.geometry.computeBoundingRectangle(mypolygon.paths);
      mapRef.value.map.fitBounds(boundary, {
        padding: 100, // 设置地图边界的内边距
      });
    }
    buttonName.value = '重置';
    editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);
    editorRef.value.editor.select([shapeId]);
  }
}

const mapRef = ref(null);
const center = ref(config.map.center);
const control = ref({ scale: {}, zoom: { position: 'topRight', }, });
const options = ref({ renderOptions: { renderOptions: true, } });
const editorRef = ref(null);
const onMapInited = () => {
  if (mapRef.value) {
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const calculatedWidth = windowWidth - 60;
    const calculatedHeight = windowHeight - 100;
    // 调用地图实例的 resize 方法
    const map = mapRef.value.map;
    if (map) {
      map.resize(calculatedWidth, calculatedHeight);
    }
  }
};

const buttonName = ref('清除');
const onDrowComplet = (geomeytry) => {
  //console.log("onDrowComplet",geomeytry);
  if (geomeytry.id) {
    editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);
    editorRef.value.editor.select([geomeytry.id]);
  }
};
const onDrawError = (e) => {
  ClearEditor();
  editorRef.value.editor.stop();
};

const onAdjustComplete = (geomeytry) => {
  //console.log("onAdjustComplete",geomeytry);
};
const onAdjustError = (e) => {
  ClearEditor();
  loadGeometry();
};

const onEditorClear = () => {
  if (!isNullOrEmpty(shapeId)) {
    loadGeometry();
  }
  else {
    ClearEditor();
  }
}

const ClearEditor = () => {
  editorRef.value.editor.select([]);
  editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.DRAW);
  editorRef.value.circle.setGeometries([]);
  editorRef.value.polygon.setGeometries([]);
}

const onEditorComplete = () => {
  if (editorRef.value.editor.getSelectedList().length > 0) {
    const selectedList = editorRef.value.editor.getSelectedList();
    const geometry = selectedList[0];
    console.log("onEditorComplete", geometry);
    if (geometry.id) {
      if (geometry.radius && geometry.center) {
        formData.value.radius = geometry.radius;
        formData.value.points = [
          {
            "latitude": geometry.center.lat,
            "longitude": geometry.center.lng,
          }
        ];
        formData.value.shapeType = 1;
      }
      else if (geometry.paths) {
        formData.value.radius = 0;
        formData.value.points = geometry.paths.map((point) => {
          return {
            "latitude": point.lat,
            "longitude": point.lng,
          };
        });
        formData.value.points.push({
          "latitude": geometry.paths[0].lat,
          "longitude": geometry.paths[0].lng,
        });
        formData.value.shapeType = 2;
      }
      if (!isNullOrEmpty(formData.value.operationRegionId)) {
        callOperate("/ebikeRegion/updateOperation", formData.value, "post").then((res) => {
          if (res.code == 200) {
            message.success(res.message, 3, handleClose);
          } else {
            message.error(res.message, 10);
          }
        });
      }
      else {
        handleClose();
      }
    }
  }
  else {
    message.error("请先绘制区域！")
  }
}

const onDeleteComplete = (geomeytry) => {
  if (editorRef.value.polygon.getGeometries().length > 0) {
    const shapeId = editorRef.value.polygon.getGeometries()[0].id;
    editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);
    editorRef.value.editor.select([shapeId]);
  }
  else if (editorRef.value.circle.getGeometries().length > 0) {
    const shapeId = editorRef.value.circle.getGeometries()[0].id;
    editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);
    editorRef.value.editor.select([shapeId]);
  }
  else {
    editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.DRAW);
    // editorRef.value.circle.setGeometries([]);
    // editorRef.value.polygon.setGeometries([]);
  }
};
</script>

<style>
.full-modal .ant-modal {
  max-width: 100%;
  top: 0;
  padding-bottom: 0;
  margin: 0;
}
.full-modal .ant-modal-content {
  display: flex;
  flex-direction: column;
  height: calc(100vh);
  border-radius: 0 !important;
}
.full-modal .ant-modal-body {
  flex: 1;
}

.button-panel {
  position: absolute;
  bottom: 55px;
  right: 35px;
  z-index: 2000;
  width: 300px;
  height: 105px;
  background-color: rgb(255, 255, 255, 0.8);
  padding: 15px;
}
.button-panel button {
  width: 100%;
  border-radius: 0px !important;
  margin-bottom: 10px;
}
</style>