<template>
    <div>
        <!-- 搜索框 -->
        <div class="search-container">
            <el-input v-model="keyword" placeholder="请输入地点名称" class="search-input" @keyup.enter.native="toSearch"
                @input="handleInput">
                <el-button slot="append" icon="el-icon-search" @click="toSearch"></el-button>
            </el-input>
            <!-- 落点地点输入框 -->
            <el-input v-model="pointForm.address" readonly class="search-input">
                <template slot="append">
                    <el-button icon="el-icon-refresh" @click="reverseGeocode" :loading="loadingAddress"></el-button>
                </template>
            </el-input>
            <!-- 搜索结果列表 -->
            <div class="search-results" v-if="searchBox && searchList.length > 0">
                <div class="search-item" v-for="(item, index) in searchList" :key="index" @click="centerMap(item)">
                    <div class="item-name">{{ item.name }}</div>
                    <div class="item-address">{{ item.address }}</div>
                </div>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="main-content">
            <!-- 地图容器 -->
            <div class="map-thumbnail">
                <div id="mars2dContainerLuotu" class="mars2d-container"></div>
            </div>
            <div style="margin-top: 1rem;">
                <el-button type="primary" @click="confirmPoint">确认选择</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import 'mars2d/mars2d.css';
import * as mars2d from 'mars2d';
import axios from 'axios';


export default {
    data() {
        const basePathUrl = window.basePathUrl || "";
        return {
            configUrl: basePathUrl + "config/config.json",
            mapOptions: {
                copyright: false,
                basemaps: [
                    {
                        id: 2021,
                        chinaCRS: "GCJ02",
                        pid: 10,
                        name: "高德电子",
                        icon: "img/basemaps/gaode_vec.png",
                        type: "gaode",
                        layer: "vec",
                        show: true
                    }
                ],
                center: { lat: 31.2304, lng: 120.6184 },
                zoom: 10,
                chinaCRS: 'GCJ02'
            },
            map: null,
            floatingPanelVisible: false,
            pointDialogTitle: '确认地点位置',
            pointForm: {
                name: '',
                lat: '',
                lng: '',
                address: ''
            },
            selectedPlaceName: '',
            selectedMarker: null,
            keyword: "",
            searchList: [],
            searchBox: false,
            searchDebounce: null,
            markerIcon: require('@/assets/images/detailsicon/icon-定位@2x.png'),
            loadingAddress: false,
            gaodeKey: 'bd665f6310bb41cdaea4494ec86fcbfa'
        };
    },
    methods: {
        initMap() {
            if (!this.map) {
                this.map = new mars2d.Map('mars2dContainerLuotu', this.mapOptions);
                this.map.on('click', this.onMapClick);
            }
        },

        onMapClick(event) {
            if (this.selectedMarker) {
                this.selectedMarker.setLatLng(event.latlng);
                this.updatePointForm(event.latlng);
                this.reverseGeocode(); // 自动触发逆地理编码
            }
        },

        updatePointForm(latlng) {
            this.pointForm.lat = latlng.lat;
            this.pointForm.lng = latlng.lng;
        },

        showFloatingPanel() {
            this.floatingPanelVisible = true;
            this.$nextTick(() => {
                this.$refs.pointNameInput.focus();
            });
        },

        hideFloatingPanel() {
            this.floatingPanelVisible = false;
        },

        confirmPoint() {
            if (!this.pointForm.address) {
                this.$message.warning('请先落点选择地址');
                return;
            }

            // 通知父组件关闭弹窗并传递地址信息
            this.$emit('confirm-selection', {
                address: this.pointForm.address,
                lng: this.pointForm.lng,
                lat: this.pointForm.lat
            });

            this.hideFloatingPanel();
            this.$message.success('地点选择成功');
        },
        // 逆地理编码 - 根据经纬度获取地址
        reverseGeocode() {
            if (!this.pointForm.lat || !this.pointForm.lng) return;

            this.loadingAddress = true;

            axios({
                method: "GET",
                url: "https://restapi.amap.com/v3/geocode/regeo",
                params: {
                    key: this.gaodeKey,
                    location: `${this.pointForm.lng},${this.pointForm.lat}`,
                    radius: 50,
                    extensions: 'base'
                }
            }).then(res => {
                if (res.data && res.data.status === '1' && res.data.regeocode) {
                    const address = res.data.regeocode.formatted_address ||
                        res.data.regeocode.addressComponent.neighborhood.name ||
                        res.data.regeocode.addressComponent.township;
                    this.pointForm.address = address;

                    // 地址作为默认名称
                    if (!this.pointForm.name) {
                        this.pointForm.name = address;
                    }
                } else {
                    this.$message.warning('未能获取详细地址信息');
                }
            }).catch(error => {
                this.$message.error('获取地址信息失败');
            }).finally(() => {
                this.loadingAddress = false;
            });
        },

        handleInput() {
            if (this.searchDebounce) {
                clearTimeout(this.searchDebounce);
            }
            this.searchDebounce = setTimeout(() => {
                this.toSearch();
            }, 300);
        },

        toSearch() {
            let params = {
                key: this.gaodeKey,
                keywords: this.keyword,
                city: "亳州市",
            };

            axios({
                method: "GET",
                url: "https://restapi.amap.com/v3/place/text",
                params,
            }).then((res) => {
                if (res.status == 200) {
                    if (res.data.pois && res.data.pois.length > 0) {
                        this.searchList = res.data.pois;
                        this.searchBox = true;
                    } else {
                        this.$message({
                            message: "未搜索到结果！",
                            type: "warning",
                        });
                    }
                }
            }).catch(error => {
                console.error('搜索失败:', error);
                this.$message.error('搜索失败，请稍后重试');
            });
        },

        centerMap(item) {
            const [lng, lat] = item.location.split(',').map(Number);

            this.keyword = item.name;
            this.map.flyTo([lat, lng], 17);

            if (this.selectedMarker) {
                this.map.graphicLayer.removeGraphic(this.selectedMarker);
            }

            // 可拖标记
            this.selectedMarker = new mars2d.graphic.Marker({
                latlng: [lat, lng],
                style: {
                    image: this.markerIcon,
                    width: 32,
                    height: 32,
                    draggable: true
                },
                attr: {
                    name: item.name,
                    address: item.address
                }
            });

            this.map.graphicLayer.addGraphic(this.selectedMarker);

            // 监听拖动事件
            this.selectedMarker.on('dragend', (event) => {
                const newLatLng = event.target.getLatLng();
                this.updatePointForm(newLatLng);
                this.reverseGeocode(); // 获取新地址
            });

            // 初始化表单数据
            this.pointForm = {
                name: item.name,
                lat: lat,
                lng: lng,
                address: item.address
            };

            // 显示悬浮面板
            this.showFloatingPanel();
            this.searchBox = false;
        }
    },
    mounted() {
        this.initMap();
    },
};
</script>

<style scoped>
.el-input-group__append .el-button {
    padding: 12px;
}

.el-icon-refresh {
    cursor: pointer;
    transition: transform 0.3s;
}

.el-icon-refresh:hover {
    transform: rotate(180deg);
}

.search-container {
    padding: 1rem;
    position: relative;
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.search-input {
    width: 100%;
    /* max-width: 500px; */
}

.selected-place-input {
    width: 100%;
    /* max-width: 500px; */
}

.search-results {
    position: absolute;
    top: 100%;
    left: 1rem;
    width: 100%;
    max-width: 500px;
    max-height: 300px;
    overflow-y: auto;
    background-color: white;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.search-item {
    padding: 10px 15px;
    cursor: pointer;
    border-bottom: 1px solid #ebeef5;
}

.search-item:hover {
    background-color: #f5f7fa;
}

.item-name {
    font-weight: bold;
    margin-bottom: 5px;
}

.item-address {
    color: #909399;
    font-size: 12px;
}

.main-content {
    display: flex;
    flex-direction: column;
    padding: 0 1rem 1rem 1rem;
}

.map-thumbnail {
    width: 100%;
    height: 500px;
    position: relative;
}

.mars2d-container {
    width: 100%;
    height: 100%;
}

/* 悬浮面板样式 */
.floating-panel {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 400px;
    background-color: #FFFFFF;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background-color: #F5F7FA;
    border-bottom: 1px solid #E4E7ED;
}

.panel-header span {
    font-size: 16px;
    font-weight: 500;
}

.close-button {
    font-size: 14px;
    color: #909399;
}

.panel-body {
    padding: 20px;
}

.panel-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px 15px;
    background-color: #F5F7FA;
    border-top: 1px solid #E4E7ED;
}

.panel-footer .el-button {
    margin-left: 10px;
}
</style>