<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="onEditorChange">{{ buttonName }}</a-button>
                <a-button type="primary" @click="onEditorClear">清除</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="BECBZ-EJIEQ-LUU5N-B5ISQ-3TLMZ-BXFLG"
                    :center="center"
                    zoom="16"
                    :control="control"
                    :options="options"
                    @map_inited="onMapInited"
                >
                    <tlbs-geometry-editor
                        ref="editorRef"
                        action-mode="draw"
                        :polygon-styles="styles.polygon"
                        polygon-drawing-style-id="drawing"
                        polygon-selected-style-id="selected"
                        :circle-styles="styles.circle"
                        circle-drawing-style-id="drawing"
                        circle-selected-style-id="selected"
                        selectable
                        @draw_complete="onDrowComplet"
                        @adjust_complete="onAdjustComplete"
                        @draw_error="onDrawError"
                    />
                </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'
    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;
        if (props.onCallBack) {
            props.onCallBack("");
        }
    };
    defineExpose({ showModal });

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

    let timer = null;
    let shapeId = null;
    const loadMap = (dataRegion) => {
        if (editorRef.value) {
            clearTimeout(timer);
            if (dataRegion) {
                const { regionId } = dataRegion;
                callOperate("/ebikeRegion/getRegionInfo/" + regionId, {}, "get").then((res) => {
                    if (res.code != 200) {
                        message.error(res.message)
                        return
                    }
                    const { points, shapeType, radius } = res.data;
                    formData.value = {
                        "points": points,
                        "shapeType": shapeType, // 1:圆形 2:多边形
                        "regionId": regionId,
                        "radius": radius, // 圆形半径	
                    }
                    let 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: 'fill', // 样式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, // 设置地图边界的内边距
                            });
                        }
                        console.log('editorRef', editorRef.value)
                        buttonName.value = '重新选择区域';
                        editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);
                        editorRef.value.editor.select([shapeId]);
                    }
                });	
            }
        }
        else
        {
            timer = setTimeout(() => {
                loadMap(dataRegion);
            }, 1000)
        }
    };

    const mapRef = ref(null);
    const center = ref({ lat: 30.633158, lng: 103.974997 });
    const control = ref({ scale: {}, zoom: { position: 'topRight',},});
    const options = ref({ renderOptions: { renderOptions: true, }});
    const editorRef = ref(null);
    const styles =ref({
        polygon: {
            drawing:{
                color: 'rgba(233,233,233,0.8)', // 面填充色
                showBorder: false, // 是否显示拔起面的边线
                borderColor: 'rgba(233,233,233,1)', // 边线颜色
            },
            selected: {
                color: 'rgba(41,91,255,0.16)', // 选中时的填充色
                showBorder: true, // 是否显示拔起面的边线
                borderColor: 'rgba(41,91,255,1)', // 边线颜色
            }
        },
        circle: {
            drawing: {
            color: 'rgba(233,233,233,0.8)', // 面填充色
            showBorder: false, // 是否显示拔起面的边线
            borderColor: 'rgba(233,233,233,1)', // 边线颜色
            borderWidth: 2,
          },
          selected: {
            color: 'rgba(41,91,255,0.16)', // 选中时的填充色
            showBorder: true, // 是否显示拔起面的边线
            borderColor: 'rgba(41,91,255,1)', // 边线颜色
            borderWidth: 2,
          }
        },
    });
    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);
    };
    const onAdjustComplete = (geomeytry) => {
      console.log("onAdjustComplete",geomeytry);
    };
    const onDrawError = (e) => {
      console.log("onDrawError",e);
    };

    const onEditorChange = () => {
        if(!isNullOrEmpty(shapeId)){
            editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.DRAW);
            editorRef.value.editor.remove([shapeId]);
            shapeId = null;
        }
        else
        {
            editorRef.value.editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.DRAW);
        }
    }
    const onEditorClear = () => {
        console.log("onEditorClear",editorRef.value.editor.getOverlayList());
    }

    const onEditorComplete = () => {
    	console.log("onEditorOver",editorRef.value.editor.getOverlayList());
    }
</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: 180px;
    background-color: rgb(255, 255, 255, 0.8);
    padding: 15px;
  }
  .button-panel button{
    width: 100%;
    border-radius: 0px !important;
    margin-bottom: 10px;
  }
</style>