<template>
    <custom-header name="农场信息" bgColor="#f2f3f5"></custom-header>
    <div class="farm-details-page">
        <div class="map-wrap info-card">
            <div class="map-area" ref="mapContainer"></div>
            <div class="map-text" @click="handleEditMap">点击编辑地块</div>
        </div>
        <div class="info-box info-card">
            <div class="section-header">
                <div class="line-title">基本信息</div>
                <div class="edit-btn-box">
                    <div class="edit-btn" @click="handleAddVariety">新增品种</div>
                    <div class="edit-btn" @click="handleEditFarmInfo">编辑信息</div>
                </div>
            </div>
            <div class="info-list">
                <div class="info-row">
                    <span class="info-label">农场名称：</span>
                    <span class="info-value">{{ farmInfo.subjectName }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">联系人：</span>
                    <span class="info-value">{{ farmInfo.contactName }}</span>
                </div>
                <div class="info-row center-row">
                    <span class="info-label">联系电话：</span>
                    <span class="info-value">{{ farmInfo.contactPhone }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">种植面积：</span>
                    <span class="info-value">{{ farmInfo.farmArea }}亩</span>
                </div>
                <div class="info-row">
                    <span class="info-label">农场位置：</span>
                    <span class="info-value">{{ farmInfo.farmAddress }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">种植品种：</span>
                    <div class="info-value crop-tags">
                        <span v-for="crop in farmInfo.regionList" :key="crop.regionId" class="crop-tag">
                            {{ crop.regionName }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="info-box info-card">
            <div class="section-header">
                <div class="line-title">农场设施</div>
                <div class="edit-btn" @click="handleEditFarmFacility">编辑信息</div>
            </div>
            <div class="info-list">
                <div class="info-row">
                    <span class="info-label">灌溉方式：</span>
                    <div class="info-value crop-tags">
                        <span v-for="method in basicFarmInfo.irrigation" :key="method.code" class="crop-tag">
                            {{ method.name }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <FarmInfoPopup ref="farmInfoPopupRef" :farmId="route.query.subjectId" @success="fetchFarmSubjectDetail" />
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import customHeader from "@/components/customHeader.vue";
import { useRouter, useRoute } from "vue-router";
import DrawRegionMap from "@/views/old_mini/interactionList/map/drawRegionMap.js";
import * as util from "@/common/ol_common.js";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import FarmInfoPopup from "@/views/old_mini/home/components/farmInfoPopup.vue";

const router = useRouter();
const route = useRoute();
const store = useStore();
const farmInfo = ref({});
const mapContainer = ref(null);
const drawRegionMap = new DrawRegionMap();

const initMap = () => {
    if (!mapContainer.value) return;
    if (drawRegionMap.kmap) return;

    const info = farmInfo.value || {};

    drawRegionMap.initMap(info.farmLocation, mapContainer.value, false, true, false);

    // 回显农场区域，多边形 WKT 数组（有就画，没有就不画）
    let geometryArr = [];

    // 优先使用 regionList 里的 geom：有值才渲染
    if (Array.isArray(info.regionList) && info.regionList.length > 0) {
        info.regionList.forEach((item) => {
            if (item?.geom) {
                geometryArr.push(item?.geom)
            }
        });
    }

    if (geometryArr.length) {
        // 农场信息页：地块用绿色展示；第三参留空表示面积仍按地块自动计算
        drawRegionMap.setAreaGeometry(Array.from(geometryArr), true, undefined, {
            fill: "rgba(0, 57, 44, 0.5)",
            stroke: "#18AA8B",
        });
    }

    // 在区域中心落一个点位（使用与勾画页相同的图标）
    try {
        const geom = util.wktCastGeom(info.farmLocation);
        if (geom && typeof geom.getFirstCoordinate === "function") {
            const coord = geom.getFirstCoordinate();
            drawRegionMap.setMapPoint(coord);
        }
    } catch (e) {
        // 解析失败则忽略点位
    }
};

const destroyMap = () => {
    if (drawRegionMap && drawRegionMap.kmap && drawRegionMap.destroyMap) {
        drawRegionMap.destroyMap();
    }
};

onMounted(() => {
    fetchFarmSubjectDetail();
    fetchBasicFarmFormData();
});

function fetchFarmSubjectDetail() {
    VE_API.basic_farm.fetchFarmSubjectDetail({ subjectId: route.query.subjectId }).then(({ data }) => {
        farmInfo.value = data || {};
        nextTick(() => {
            destroyMap();
            initMap();
        });
    });
}

const basicFarmInfo = ref({});
function fetchBasicFarmFormData() {
    VE_API.basic_farm.fetchBasicFarmFormData({ subjectId: route.query.subjectId }).then(({ data, code }) => {
        if (code === 0) {
            basicFarmInfo.value = {
                ...data,
                irrigation: data.irrigationMethods.filter(item => item.selected),
            }
        }
    });
}

const farmInfoPopupRef = ref(null);
const handleEditFarmInfo = () => {
    // // 回显地块：存到 polygonData，创建页会优先使用这里的数据
    // if (data.geomWkt) {
    //     const polygonData = {
    //         geometryArr: [data.geomWkt],
    //         mianji: data.mianji,
    //         isConfirmed: true,
    //     };
    //     store.commit("home/SET_FARM_POLYGON", polygonData);
    // } else {
    //     store.commit("home/SET_FARM_POLYGON", null);
    // }

    // const params = {
    //     ...farmInfo.value,
    //     name: farmInfo.value.subjectName,
    //     fzr: farmInfo.value.contactName,
    //     tel: farmInfo.value.contactPhone,
    //     mianji: farmInfo.value.farmArea,
    //     address: farmInfo.value.farmAddress,
    // };

    // // 回显其他表单字段
    // store.commit("home/SET_EDIT_FARM_DATA", params);

    // // 带上 from=details，创建页提交/取消后能正确返回
    // router.push(`/create_farm?type=edit&farmId=${route.query.subjectId}&from=details`);

    farmInfoPopupRef.value.handleShow();
};

const handleEditFarmFacility = () => {
    router.push(`/prescription?subjectId=${route.query.subjectId}`);
};

// 点击编辑地块
const handleEditMap = () => {
    const mapCenter = farmInfo.value.farmLocation || undefined;
    if (farmInfo.value.regionList.length) {
        // type=view 进入查看态；rangeWkt 用于回显多个地块
        router.push({
            path: "/draw_area",
            query: {
                type: "viewOnly",
                subjectId: route.query.subjectId
            },
        });
    } else {
        ElMessage.warning("暂无种植作物，无法编辑地块");
    }
};

const handleAddVariety = () => {
    router.push(`/interaction?addVariety=true&subjectId=${route.query.subjectId}`);
};
</script>

<style lang="scss" scoped>
.farm-details-page {
    background: #f2f3f5;
    height: calc(100vh - 40px);
    padding: 0 12px;
    overflow: auto;

    .line-title {
        position: relative;
        padding-left: 14px;
        font-size: 16px;

        &::before {
            content: "";
            position: absolute;
            left: 5px;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 15px;
            background: #2199f8;
            border-radius: 20px;
        }
    }

    .info-card{
        margin-top: 12px;
        background: #fff;
        border-radius: 6px;
        padding: 10px;
    }

    .map-wrap {
        position: relative;

        .map-area {
            width: 100%;
            height: 142px;
            clip-path: inset(0px round 5px);
        }

        .map-text {
            position: absolute;
            right: 13px;
            bottom: 16px;
            font-size: 12px;
            color: #ffffff;
            background: rgba(0, 0, 0, 0.5);
            padding: 8px 12px;
            border-radius: 25px;
            border: 1px solid rgba(255, 255, 255, 0.5);
        }
    }

    .info-box {
        margin-top: 12px;

        .section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .edit-btn-box {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .edit-btn {
            padding: 4px 12px;
            font-size: 12px;
            color: #86909c;
            border-radius: 999px;
            border: 0.5px solid #d0d3d8;
            background-color: #ffffff;
        }

        .info-list {
            margin-top: 10px;
            margin-left: 5px;

            .info-row {
                display: flex;
                align-items: flex-start;
                margin-bottom: 6px;

                &.center-row {
                    align-items: center;
                }

                .info-label {
                    min-width: 80px;
                    color: #4E5969;
                }

                .crop-tags {
                    display: flex;
                    align-items: center;
                    flex-wrap: wrap;
                    gap: 6px;

                    .crop-tag {
                        padding: 2px 8px;
                        background: #E8F3FF;
                        color: #2199f8;
                        border-radius: 2px;
                        font-size: 12px;
                    }
                }

                .problem-tags {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 6px;

                    .problem-tag {
                        padding: 2px 8px;
                        background: rgba(58, 173, 148, 0.1);
                        color: #3AAD94;
                        border-radius: 2px;
                        font-size: 13px;
                    }
                }

                .device-value {
                    width: 100%;
                }

                .device-box {
                    padding: 6px;
                    border-radius: 4px;
                    border: 0.5px solid rgba(33, 153, 248, 0.2);
                    display: grid;
                    grid-template-columns: repeat(2, minmax(0, 1fr));
                    column-gap: 12px;
                    row-gap: 4px;

                    .device-item {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        padding: 4px 0;
                        min-width: 0;
                        gap: 8px;
                        font-size: 13px;
                        color: #1D2129;

                        .device-count {
                            padding: 2px 8px;
                            background: #E8F3FF;
                            color: #2199f8;
                            border-radius: 2px;
                        }
                    }
                }
            }

            .info-row-column {
                display: flex;
                flex-direction: column;
                gap: 4px;
            }
        }
    }
}
</style>
