<template>
    <div class="edit-map">
        <custom-header name="编辑农场" :isGoBack="true" @goback="backgToCreate"></custom-header>
        <div class="edit-map-content">
            <div class="edit-map-tip">操作提示：拖动圆点，即可调整地块边界</div>
            <div class="map-container" ref="mapContainer"></div>
            <div class="edit-map-footer">
                <div class="footer-back" @click="goBack">
                    <img class="back-icon" src="@/assets/img/home/go-back.png" alt="" />
                </div>
                <div class="footer-address-box">
                    <div class="footer-address">
                        <div class="address-title">{{ pointName }}</div>
                        <div class="address-detail">{{ pointAddress }}</div>
                    </div>
                    <div class="address-btn" @click="goBack">修改地址</div>
                </div>
                <div class="edit-map-footer-btn">
                    <div class="btn-delete" @click="deletePolygon">删除地块</div>
                    <div class="btn-cancel" @click="goBack">取消</div>
                    <div class="btn-confirm" @click="confirm">确认</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import customHeader from "@/components/customHeader.vue";
import { ref, onMounted, onActivated, onDeactivated } from "vue";
import EditMap from "./map/editMap.js";
import { useRouter, useRoute } from "vue-router";
import { convertPointToArray } from "@/utils/index";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const route = useRoute();
const store = useStore();
const mapContainer = ref(null);
const editMap = new EditMap();
const mapData = {
    farmCode: "LBY",
    farmId: "766",
    id: 2,
    isGenerateReport: 1,
    name: "分区2",
    pointCount: 131,
    pointWkt: "POINT (113.6142086995688 23.585836479509055)",
    regionCode: "LBY-MR-2",
    wkt: "MULTIPOLYGON (((113.61348988377155 23.58617369800422, 113.61395837633405 23.58622555407246, 113.61414076654707 23.58622555407246, 113.61436964832843 23.5862774101407, 113.61478628474084 23.586468741036786, 113.61491681896747 23.58652417337007, 113.61512424307672 23.586449071517652, 113.61491503077356 23.585742756367924, 113.61479880177082 23.585596129050916, 113.61473800497858 23.585451289764112, 113.61438931780664 23.585286780835393, 113.61410858003889 23.585299297865365, 113.61385645239149 23.585249229909184, 113.61378135053907 23.585288569029306, 113.61357571446003 23.585283204611276, 113.61347200232355 23.585342213209604, 113.61338080721704 23.585506721974614, 113.61335934954492 23.585665866485304, 113.61342193444922 23.58616296916816, 113.61348988377155 23.58617369800422)))",
};

const pointAddress = ref(null)
const pointName = ref(null)
const type = ref(null)
onMounted(() => {
    pointAddress.value = route.query.pointAddress
    pointName.value = route.query.pointName
    type.value = route.query.type
    const point = route.query.mapCenter || "POINT (113.6142086995688 23.585836479509055)"
    editMap.initMap(point, mapContainer.value);
    
    // 设置绘制限制回调
    editMap.setDrawLimitCallback(() => {
        ElMessage.warning("请先删除当前地块再重新勾画");
    });
    // editMap.setAreaGeometry([{ featureWkt: mapData.wkt }]);
});

onActivated(() => {
    pointAddress.value = route.query.pointAddress
    pointName.value = route.query.pointName
    const point = route.query.mapCenter || "POINT (113.6142086995688 23.585836479509055)"
    
    // 先绘制地块
    const polygonData = store.state.home.polygonData;
    if (polygonData) {
        editMap.setAreaGeometry(polygonData?.geometryArr);
    }
    
    // 再设置地图中心位置，确保视图在 mapCenter
    editMap.setMapPosition(convertPointToArray(point))
})

onDeactivated(() => {
    editMap.clearLayer()
})
const goBack = () => {
    editMap.clearLayer()
    // 用户点击取消，不保存编辑结果
    // 保持 store 中的数据不变（保留跳转前的状态，isConfirmed 保持为 false）
    // 不需要做任何处理，直接返回即可
    
    if (type.value !== 'edit') {
        router.replace(`/create_farm?from=${route.query.from}&type=${route.query.type}`)
    }else{
        router.back()
    }
};

function backgToCreate() {
    editMap.clearLayer()
    // 用户点击返回，不保存编辑结果
    // 保持 store 中的数据不变
    
    if (type.value !== 'edit') {
        router.replace(`/create_farm?from=${route.query.from}&type=${route.query.type}`)
    }else{
        router.back()
    }
}
const deletePolygon = () => {
    ElMessageBox.confirm(
        '确认要删除当前地块吗？删除后可以重新勾画。',
        '删除确认',
        {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        editMap.deleteCurrentPolygon();
        ElMessage.success("地块已删除");
    }).catch(() => {
        // 用户取消删除，不做任何操作
    });
};

const confirm = () => {
    // getAreaGeometry
    const polygonData = editMap.getAreaGeometry()
    
    // 标记为已确认，表示从编辑页面确认返回
    polygonData.isConfirmed = true;
    
    store.commit("home/SET_FARM_POLYGON", polygonData);
    
    if (type.value !== 'edit') {
        // 添加时间戳确保路由更新，触发 onActivated
        const timestamp = Date.now();
        router.replace(`/create_farm?from=${route.query.from}&type=${route.query.type}&_t=${timestamp}`)
    }else{
        router.back()
    }
};
</script>

<style lang="scss" scoped>
.edit-map {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    .edit-map-content {
        width: 100%;
        height: 100%;
        position: relative;
        .edit-map-tip {
            position: absolute;
            top: 23px;
            left: calc(50% - 256px / 2);
            z-index: 1;
            font-size: 12px;
            color: #fff;
            padding: 9px 20px;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 20px;
        }
        .map-container {
            width: 100%;
            height: 100%;
        }
        .edit-map-footer {
            position: absolute;
            bottom: 80px;
            left: 12px;
            width: calc(100% - 24px);
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            .footer-back {
                padding: 6px 7px 9px;
                background: #fff;
                border-radius: 8px;
                .back-icon {
                    width: 20px;
                    height: 18px;
                }
            }
            .footer-address-box {
                width: 100%;
                box-sizing: border-box;
                margin: 19px 0 14px 0;
                display: flex;
                justify-content: space-between;
                align-items: center;
                background: #fff;
                border-radius: 14px;
                padding: 14px 12px;
                .footer-address {
                    font-size: 12px;
                    color: rgba(0, 0, 0, 0.6);
                    .address-title {
                        font-weight: 500;
                        font-size: 16px;
                        color: #000;
                    }
                }
                .address-btn {
                    color: #2199f8;
                    border: 1px solid #2199f8;
                    border-radius: 25px;
                    padding: 6px 10px;
                    flex: none;
                }
            }
            .edit-map-footer-btn {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                gap: 8px;
                div {
                    flex: 1;
                    max-width: 100px;
                    text-align: center;
                    color: #666666;
                    font-size: 14px;
                    padding: 8px 0;
                    border-radius: 25px;
                    background: #fff;
                }
                .btn-delete {
                    background: #ff4d4f;
                    color: #fff;
                }
                .btn-confirm {
                    background: #000;
                    background-image: linear-gradient(180deg, #76c3ff 0%, #2199f8 100%);
                    color: #fff;
                }
            }
        }
    }
}
</style>
