<template>
    <custom-header name="农情互动" bgColor="#f2f4f5"></custom-header>
    <div class="interaction-list" ref="interactionListRef">
        <div class="list-item" v-for="(item, index) in listData" :key="item.id || index"
            :class="{ 'uploaded-item': item.questionStatus !== 3 }">
            <!-- 标题区域 -->
            <div class="item-header-wrapper" :class="{ 'has-status': item.questionStatus !== 3 }">
                <div class="item-header">
                    <div class="title">{{ item.interactionTypeName }}</div>
                    <div class="status" :class="['urgent-' + item.urgent]" v-if="item.questionStatus === 3">{{
                        urgentType[item.urgent] }}</div>
                </div>
                <div class="upload-status" v-show="item.questionStatus !== 3">
                    <el-icon class="status-icon">
                        <SuccessFilled />
                    </el-icon>
                    <span class="status-text">提交成功</span>
                </div>
            </div>

            <!-- 未上传状态内容 -->
            <div class="uploaded-content" v-show="item.questionStatus === 3 || item.expanded">
                <div class="content-wrapper">
                    <span>{{ item.remark }}</span>
                    <text-ellipsis class="item-desc" rows="0" :content="item.reason" expand-text="展开"
                        collapse-text="收起" />
                    <div class="tip-box">如果不确定是否发生，直接上传照片即可</div>
                    <div class="example-wrapper">
                        <div class="example-header">
                            <div>示例照片</div>
                            <div class="more" v-if="item.exampleImageWithAnnotations.length > 3"
                                @click="openMorePopup(item)">查看更多</div>
                        </div>
                        <div class="example-list" v-if="item.exampleImageWithAnnotations.length > 0">
                            <div class="image-item-wrapper"
                                v-for="(example, exIndex) in item.exampleImageWithAnnotations"
                                :key="example.exampleImageUrl" @click="showExample(item, exIndex)">
                                <img class="image-item" :src="example.exampleImageUrl" alt="" />
                            </div>
                        </div>
                    </div>
                    <text-ellipsis class="patrol-suggestion" rows="2" :content="'巡园建议：' + item.patrolSuggestion">
                        <template #action="{ expanded }"><span class="action-text">{{ expanded ? '收起' : '展开'
                                }}</span></template>
                    </text-ellipsis>
                </div>

                <!-- 展开状态内容 -->
                <div class="expanded-content" v-show="item.imagePaths.length > 0">
                    <!-- 原因说明 -->
                    <div class="reason-text">上传照片（{{ item.imagePaths.length }}张）</div>
                    <!-- 图片展示 -->
                    <div class="uploaded-images">
                        <div class="uploaded-img-wrap" v-for="(image, imgIndex) in item.imagePaths" :key="image"
                            @click="showExample(item, imgIndex, { hideLabel: true })">
                            <img class="uploaded-img" :src="base_img_url2 + image" alt="" />
                            <span v-show="item.questionStatus === 3" class="uploaded-img-remove"
                                @click.stop="removeUploadedImage(item, imgIndex)">×</span>
                        </div>
                    </div>
                    <uploader v-show="item.questionStatus === 3" class="upload-wrap continue-upload-btn"
                        @click="handleUploadClick(item)" multiple :max-count="10" :after-read="afterReadUpload">
                        <div class="upload-btn">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <span>继续上传照片</span>
                        </div>
                    </uploader>
                </div>

                <!-- 上传按钮 -->
                <uploader v-if="item.imagePaths.length === 0 && item.questionStatus === 3"
                    @click="handleUploadClick(item)" class="upload-wrap" multiple :max-count="10"
                    :after-read="afterReadUpload">
                    <div class="upload-btn">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>点击上传照片</span>
                    </div>
                </uploader>

                <div class="question-wrapper" v-if="item.imagePaths.length">
                    <div class="question-cont">
                        <div class="question-text"
                            v-for="(q, qIdx) in (item.questionList || [item.question].filter(Boolean))" :key="qIdx">
                            <span class="text-title">{{ q }}</span>
                            <el-input v-model="item.answerValues[qIdx]" :disabled="item.questionStatus !== 3"
                                type="number" style="width: 70px">
                                <template #suffix>
                                    <span class="text-unit">{{ item.indicators[qIdx]?.unit ?? item.indicators[0]?.unit
                                        ?? '%' }}</span>
                                </template>
                            </el-input>
                        </div>
                    </div>
                    <div class="draw-region-btn" v-if="item.interactionTypeId != 1 && item.questionStatus === 3"
                        @click="handleDrawRegion(item)">
                        编辑发生区域</div>
                    <div class="draw-region-btn" v-if="item.rangeWkt && item.questionStatus !== 3"
                        @click="handleViewRegion(item)">
                        查看发生区域</div>
                </div>

                <!-- 输入框 -->
                <div class="input-wrapper">
                    <el-input v-model="item.replyText" :disabled="item.questionStatus !== 3" placeholder="请输入您咨询的问题"
                        clearable />
                </div>

                <!-- 按钮区域 -->
                <div class="button-group" v-show="item.questionStatus === 3">
                    <div class="btn-not-reached" @click="handleConfirm(item, false)">{{ item.cancelButtonName }}</div>
                    <div class="btn-default" :class="{ 'btn-confirm': item.imagePaths.length > 0 }"
                        @click="handleConfirm(item, true)">
                        确认提交
                    </div>
                </div>
            </div>

            <!-- 比例信息（已上传状态显示） -->
            <div class="proportion-info" v-show="item.questionStatus !== 3"
                :style="{ justifyContent: item.expanded ? 'center' : 'space-between' }">
                <template v-if="!item.expanded">
                    <span class="proportion-text">{{(item.questionList && item.questionList.length
                        ? item.questionList.map((q, i) => q + '：' + (item.answerValues[i] ?? '') +
                            (item.indicators[i]?.unit
                                ?? item.indicators[0]?.unit ?? '%')).join('')
                        : item.question + '：' + (item.answerValues[0] ?? '') + (item.indicators[0]?.unit ?? '%'))
                        }}</span>
                </template>
                <div class="toggle-btn" @click="toggleExpand(item)">
                    <span>{{ item.expanded ? "收起" : "展开" }}</span>
                    <el-icon :class="{ rotate: !item.expanded }">
                        <CaretTop />
                    </el-icon>
                </div>
            </div>
        </div>
        <div class="empty-data" v-if="!loading && listData.length === 0">暂无数据</div>
    </div>

    <!-- <div class="custom-bottom-fixed-btns" :class="{ 'center-btn': false }">
        <div class="bottom-btn secondary-btn" @click="handleShowDroneConsultPopup">获取自动飞行航线</div>
        <div class="bottom-btn secondary-btn">邀请农情互动</div>
        <div class="bottom-btn primary-btn" @click="handleSubmitAll">一键提交</div>
    </div> -->

    <!-- 农场信息完善弹窗 -->
    <farm-info-popup :oldUser="oldUser" :expertMiniUserId="query.expertMiniUserId" v-model:show="showFarmInfoPopup" />
    <!-- 无人机/飞行航线咨询弹窗 -->
    <drone-consult-popup v-model:show="showDroneConsultPopup" @copy="onCopyWechatId" />

    <!-- 示例照片轮播组件 -->
    <example-popup v-model:show="showExamplePopup" :images="exampleList" :tips="currentPhotData?.shootingMethod"
        :start-index="exampleStartIndex" :show-title-and-tips="exampleShowTitleAndTips" />
    <!-- 照片上传进度 -->

    <popup v-model:show="showUploadProgressPopup" round class="upload-progress-popup">
        <div class="upload-progress-title">
            <span>照片上传进度</span>
            <el-progress class="upload-progress" :percentage="uploadPercentage" :stroke-width="10" :format="format" />
        </div>
        <div class="upload-box">
            <!-- 把已经上传成功的图片传给 upload 组件做回显，同时保持原有上传事件不变 -->
            <upload :maxCount="10" :initImgArr="initImgArr" @handleUpload="handleUploadSuccess">
            </upload>
        </div>
        <div class="input-box">
            <div class="input-item"
                v-for="(q, qIdx) in (currentItem?.questionList?.length ? currentItem.questionList : (currentItem?.question ? [currentItem.question] : []))"
                :key="qIdx">
                <span class="label-text">{{ q }}</span>
                <el-input class="label-input" v-model="currentItem.answerValues[qIdx]" placeholder="请输入" type="number">
                    <template #suffix>
                        <span class="unit">{{ currentItem.indicators[qIdx]?.unit ?? currentItem.indicators[0]?.unit ??
                            '%' }}</span>
                    </template>
                </el-input>
            </div>
            <el-input class="input-item" v-model="currentItem.replyText" placeholder="请输入您咨询的问题" clearable />
        </div>
        <template v-if="currentItem.interactionTypeId != 1">
            <div class="region-tips">勾画新发生区域，精准匹配专属农事方案</div>
            <div class="region-map" ref="mapContainer" @click="handleDrawRegion(currentItem)">
                <div class="region-map-text">点击勾画新发生区域</div>
            </div>
        </template>
        <div class="confirm-btn" @click="handleConfirmUpload">确认上传</div>
    </popup>

    <!-- 查看更多弹窗 -->
    <more-popup ref="morePopupRef" />
</template>
<script setup>
import { ref, onActivated, computed, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { Uploader, Popup, TextEllipsis } from "vant";
import customHeader from "@/components/customHeader.vue";
import upload from "@/components/upload.vue";
import FarmInfoPopup from "@/components/popup/farmInfoPopup.vue";
import DroneConsultPopup from "@/components/popup/droneConsultPopup.vue";
import ExamplePopup from "./components/examplePopup.vue";
import { useRouter, useRoute } from "vue-router";
import { base_img_url2 } from "@/api/config";
import DrawRegionMap from "./map/drawRegionMap.js";
import UploadFile from "@/utils/upliadFile";
import { getFileExt } from "@/utils/util";
import MorePopup from "./components/morePopup.vue";

const interactionListRef = ref(null);
const SCROLL_KEY = 'interactionListScrollTop';

const showDroneConsultPopup = ref(false);
const handleShowDroneConsultPopup = () => {
    // showDroneConsultPopup.value = true;
    router.push(
        `/confirm_area`
    );
}

const showFarmInfoPopup = ref(false);
const loading = ref(false);
const router = useRouter();
const listData = ref([]);
const query = ref(useRoute().query);
const morePopupRef = ref(null);
//照片上传进度
const showUploadProgressPopup = ref(false);
// 上传进度统计
const totalUploadCount = ref(0); // 本次选择的总文件数（固定不随上传成功变化）
const uploadedSuccessCount = ref(0); // 已上传成功的文件数
const uploadPercentage = computed(() => {
    if (!totalUploadCount.value) return 0;
    return Math.round((uploadedSuccessCount.value / totalUploadCount.value) * 100);
});
const format = () => {
    if (!totalUploadCount.value) return '0/0';
    return `${uploadedSuccessCount.value}/${totalUploadCount.value}`;
};

const drawRegionMap = new DrawRegionMap();
const mapContainer = ref(null);

const renderRegionFromSession = () => {
    if (!drawRegionMap.kmap) return;

    // 先清空图层
    drawRegionMap.clearLayer && drawRegionMap.clearLayer();

    // 1）通过保存的互动项 ID，在 listData 中找到对应项，用接口 rangeWkt 回显只读区域
    const savedId = sessionStorage.getItem("drawRegionInteractionId");
    if (savedId && Array.isArray(listData.value) && listData.value.length > 0) {
        const targetItem = listData.value.find(
            (it) =>
                it &&
                it.id != null &&
                (String(it.id) === savedId || Number(it.id) === Number(savedId))
        );
        if (targetItem && targetItem.rangeWkt && targetItem.rangeWkt.length > 10) {
            // 使用 setStatusRegions 显示接口返回的区域
            renderRegionFromItemWkt(targetItem);
        }
    }

    // 2）再回显本地勾画的多边形到可编辑图层（两者可共存）
    const polygonStr = sessionStorage.getItem("drawRegionPolygonData");
    if (polygonStr) {
        try {
            const polygonData = JSON.parse(polygonStr);
            if (
                polygonData &&
                Array.isArray(polygonData.geometryArr) &&
                polygonData.geometryArr.length > 0 &&
                drawRegionMap.kmap &&
                drawRegionMap.kmap.polygonLayer
            ) {
                // 注意这里不再调用 clearLayer，避免清掉上一步 setStatusRegions 的只读区域
                // 此处也不单独做 fit，由下方统一调用 fitAllRegions 适配所有图层
                drawRegionMap.setAreaGeometry(polygonData.geometryArr, false, polygonData.mianji);
            }
        } catch (e) {
            console.error("解析 drawRegionPolygonData 失败：", e);
        }
    }

    // 3）统一根据只读图层 + 可编辑图层的范围自适应视图，保证所有区域都在视野内
    if (drawRegionMap.fitAllRegions) {
        drawRegionMap.fitAllRegions();
    }
};

// 用当前项的 rangeWkt（接口返回的已保存区域）回显到地图；使用 setStatusRegions 方法显示
const renderRegionFromItemWkt = (item) => {
    const raw = item?.rangeWkt;
    if (!raw || typeof raw !== 'string' || raw.length <= 10) return;
    if (!drawRegionMap.kmap || !drawRegionMap.staticRegionLayer) return;
    let geometryArr = [];
    const trimmed = raw.trim();
    if (trimmed.startsWith('{')) {
        try {
            const parsed = JSON.parse(raw);
            if (parsed && Array.isArray(parsed.geometryArr) && parsed.geometryArr.length > 0) {
                geometryArr = parsed.geometryArr;
            }
        } catch (e) {
            console.error("解析 rangeWkt JSON 失败：", e);
            return;
        }
    } else {
        geometryArr = [raw];
    }
    if (geometryArr.length > 0) {
        // 转换为 setStatusRegions 需要的格式：[{ geometry: wkt, status?: 'resolved' | 'unresolved' }]
        const regions = geometryArr
            .filter(wkt => wkt && typeof wkt === 'string' && wkt.trim().length > 10)
            .map(wkt => ({
                geometry: wkt.trim(),
                status: 'unresolved' // 接口返回的区域默认显示为未解决状态
            }));
        if (regions.length > 0) {
            drawRegionMap.setStatusRegions(regions);
        }
    }
};

//
const urgentType = {
    "0": "一般紧急",
    "1": "紧急",
    "2": "非常紧急",
}

const uploadFileObj = new UploadFile();
const initImgArr = ref([]);
const miniUserId = localStorage.getItem("MINI_USER_ID");
//弹窗问题
const afterReadUpload = async (data) => {
    // 继续上传：回显已有图片再追加新图；首次上传：直接清空，只显示本次新传
    initImgArr.value = (currentItem.value?.imagePaths?.length > 0)
        ? [...currentItem.value.imagePaths]
        : [];
    // 本次上传的总数 = 选择的文件数量（固定，用于做进度的“总数”）
    if (!Array.isArray(data)) {
        data = [data];
    }
    totalUploadCount.value = data.length;
    uploadedSuccessCount.value = 0;
    // 仅当「编辑发生区域」和本次上传是同一项时保留勾画数据并回显；否则清除，避免数据串
    const savedInteractionId = sessionStorage.getItem("drawRegionInteractionId");
    const isSameItem = savedInteractionId != null && String(currentItem.value?.id) === savedInteractionId;
    if (!isSameItem) {
        drawRegionMap.clearLayer && drawRegionMap.clearLayer();
        sessionStorage.removeItem("drawRegionPolygonData");
        sessionStorage.removeItem("drawRegionInteractionId");
    }

    for (let file of data) {
        // 将文件上传至服务器
        let fileVal = file.file;
        file.status = "uploading";
        file.message = "上传中...";
        let ext = getFileExt(fileVal.name);
        let key = `birdseye-look-mini/${miniUserId}/${new Date().getTime()}.${ext}`;
        let resFilename = await uploadFileObj.put(key, fileVal)
        if (resFilename) {
            file.status = "done";
            file.message = "";
            // 记录成功数量，用于进度条“当前成功数”
            uploadedSuccessCount.value += 1;
            // 记录已上传成功的图片路径，用于回显
            initImgArr.value.push(resFilename)
        } else {
            file.status = 'failed';
            file.message = '上传失败';
            ElMessage.error('图片上传失败，请稍后再试！')
        }
    }
    showUploadProgressPopup.value = true;

    // 所有文件上传结束后再打开进度弹窗，此时 imgArr 已包含全部图片
    if (initImgArr.value.length > 0 && currentItem.value.interactionTypeId != 1 && currentItem.value.questionStatus === 3) {
        setTimeout(() => {
            // 只在第一次时初始化地图，后续复用已有实例
            if (!drawRegionMap.kmap) {
                drawRegionMap.initMap(
                    "POINT (113.6142086995688 23.585836479509055)",
                    mapContainer.value,
                    false,
                    false,
                    false
                );
            }
            // 先清空所有图层，再按规则分别回显：接口 rangeWkt 用 setStatusRegions，本地 session 用 setAreaGeometry，可共存
            drawRegionMap.clearLayer && drawRegionMap.clearLayer();
            const savedId = sessionStorage.getItem("drawRegionInteractionId");
            const currentId = currentItem.value?.id;
            const isSameItem =
                savedId != null &&
                currentId != null &&
                (String(currentId) === savedId || Number(currentId) === Number(savedId));
            const hasSessionPolygon = !!sessionStorage.getItem("drawRegionPolygonData");

            // 1）接口返回的 rangeWkt：始终用 setStatusRegions 渲染到只读图层
            if (currentItem.value?.rangeWkt?.length > 10) {
                renderRegionFromItemWkt(currentItem.value);
            }

            // 2）本地刚编辑的多边形（同一项且有 session 数据）：用 setAreaGeometry 渲染到可编辑图层
            if (isSameItem && hasSessionPolygon) {
                const polygonStr = sessionStorage.getItem("drawRegionPolygonData");
                if (polygonStr) {
                    try {
                        const polygonData = JSON.parse(polygonStr);
                        if (
                            polygonData &&
                            Array.isArray(polygonData.geometryArr) &&
                            polygonData.geometryArr.length > 0 &&
                            drawRegionMap.kmap &&
                            drawRegionMap.kmap.polygonLayer
                        ) {
                            // 此处不再调用 clearLayer，避免清掉上一步 setStatusRegions 的只读区域
                            drawRegionMap.setAreaGeometry(
                                polygonData.geometryArr,
                                true,
                                polygonData.mianji
                            );
                        }
                    } catch (e) {
                        console.error("解析 drawRegionPolygonData 失败：", e);
                    }
                }
            }
            if (drawRegionMap.fitAllRegions) {
                drawRegionMap.fitAllRegions();
            }
            // 3）其它情况：保持清空后的空地图
        }, 100);
    }
};

const currentItem = ref(null);
const handleUploadClick = (item) => {
    currentItem.value = item;
};

// 示例照片轮播
const showExamplePopup = ref(false);
const exampleList = ref([]);
const exampleStartIndex = ref(0);
const exampleShowTitleAndTips = ref(true);
const currentPhotData = ref({})
const showExample = (item, index, options = {}) => {
    currentPhotData.value = item;
    exampleList.value = options?.hideLabel ? item.imagePaths.map(p => ({exampleImageUrl: base_img_url2 + p})) : item.exampleImageWithAnnotations || [];
    exampleStartIndex.value = index || 0;
    exampleShowTitleAndTips.value = options.hideLabel !== true;
    showExamplePopup.value = true;
};

// 加载数据
/*  */
const loadData = async () => {
    loading.value = true;
    try {
        const { data } = await VE_API.home.listTriggeredByFarm({ farmId: localStorage.getItem("selectedFarmId") })
        listData.value = data.map(item => {
            // question 按 || 切割成数组，用于循环渲染
            const questionStr = item.question != null ? String(item.question) : '';
            item.questionList = questionStr
                ? questionStr.split('||').map(s => s.trim()).filter(Boolean)
                : [];
            if (!item.questionList.length && questionStr !== '') {
                item.questionList = [questionStr];
            }
            // 保证 answerValues 与 questionList 长度一致，便于每项对应一个输入框
            if (!Array.isArray(item.answerValues)) {
                item.answerValues = [];
            }
            while (item.answerValues.length < item.questionList.length) {
                item.answerValues.push('');
            }
            return {
                ...item
            };
        });
    } catch (error) {
        // 加载数据失败时静默处理或在需要时提示
    } finally {
        loading.value = false;
    }
};

// 刷新列表数据
const refreshList = async () => {
    listData.value = [];
    await loadData();
};

// 删除已上传的图片
const removeUploadedImage = (item, imgIndex) => {
    item.imagePaths.splice(imgIndex, 1);
};

// 确认上传 / 暂未到达进程
const handleConfirm = async (item, isConfirm) => {
    if (isConfirm) {
        const list = item.questionList || [];
        // const needFill = list.length || 1;
        // const hasEmpty = Array.from({ length: needFill }, (_, i) => i).some(
        //     (i) => item.answerValues[i] === '' || item.answerValues[i] === null || item.answerValues[i] === undefined
        // );
        // if (hasEmpty) {
        //     ElMessage.warning("请填写当前果园比例");
        //     return;
        // }
        if (item.imagePaths.length === 0 && uploadData.value.length === 0) {
            ElMessage.warning("请上传图片");
            return;
        }
    }
    const parmas = {
        farmId: localStorage.getItem("selectedFarmId"),
        imagePaths: item.imagePaths.concat(uploadData.value),
        isUploadPhoto: item.imagePaths.concat(uploadData.value).length > 0 ? true : false,
        rangeWkt: sessionStorage.getItem("drawRegionPolygonData") || '',
        interactionId: item.id,
        replyText: item.replyText,
        answerValues: item.answerValues
    }
    await VE_API.home.uploadAnswerData(parmas);
    const { code, msg } = await VE_API.home.uploadAnswer(parmas);
    if (code === 0) {
        ElMessage.success("上传成功");
        // 清空上传数据
        uploadData.value = [];
        // 刷新列表
        await refreshList();
        sessionStorage.removeItem("drawRegionPolygonData");
        sessionStorage.removeItem("drawRegionInteractionId");
    } else {
        ElMessage.error(msg || '上传失败');
    }
};

const handleConfirmUpload = async () => {
    // 校验是否有上传图片
    if (!uploadData.value || uploadData.value.length === 0) {
        ElMessage.warning("请先上传照片");
        return;
    }
    const item = currentItem.value;
    const len = item?.questionList?.length || 1;
    // const hasEmpty = Array.from({ length: len }, (_, i) => i).some(
    //     (i) => item.answerValues[i] === '' || item.answerValues[i] === null || item.answerValues[i] === undefined
    // );
    // if (hasEmpty) {
    //     ElMessage.warning("请填写占比数值");
    //     return;
    // }
    const answerVals = (item.answerValues || []).slice(0, len);
    const parmas = {
        interactionId: item.id,
        farmId: localStorage.getItem("selectedFarmId"),
        imagePaths: uploadData.value,
        rangeWkt: sessionStorage.getItem("drawRegionPolygonData") || '',
        replyText: item.replyText,
        answerValues: answerVals,
    }
    const { code, msg } = await VE_API.home.uploadAnswerData(parmas);
    if (code === 0) {
        ElMessage.success("确认成功");
        // 清空上传数据及勾画关联
        uploadData.value = [];
        sessionStorage.removeItem("drawRegionPolygonData");
        sessionStorage.removeItem("drawRegionInteractionId");
        showUploadProgressPopup.value = false;
        // 刷新列表
        await refreshList();
    } else {
        ElMessage.error(msg || '确认失败');
    }
};

// 切换展开/收起
const toggleExpand = (item) => {
    item.expanded = !item.expanded;
};

const handleViewRegion = (item) => {
    router.push(`/draw_region?viewOnly=1&rangeWkt=${encodeURIComponent(item.rangeWkt)}&updatedTime=${item.updatedTime.slice(0, 10)}`);
}

const handleDrawRegion = (item) => {
    if (sessionStorage.getItem("drawRegionInteractionId") != item.id) {
        sessionStorage.removeItem("drawRegionPolygonData");
        sessionStorage.removeItem("drawRegionInteractionId");
    }
    // 记录本次勾画对应的互动项 id，上传时若是同一项则保留回显，否则清除避免数据串
    sessionStorage.setItem("drawRegionInteractionId", String(item.id));
    const polygonData = sessionStorage.getItem("drawRegionPolygonData");
    // 记录当前滚动位置
    const container = interactionListRef.value;
    if (container && typeof container.scrollTop === 'number') {
        sessionStorage.setItem(SCROLL_KEY, String(container.scrollTop));
    }

    if (item.rangeWkt && item.rangeWkt.length > 10) {
        router.push(`/draw_region?polygonData=${polygonData}&rangeWkt=${item.rangeWkt}&updatedTime=${item.updatedTime.slice(0, 10)}`);
    } else {
        if (polygonData) {
            router.push(`/draw_region?polygonData=${polygonData}`);
        } else {
            router.push(`/draw_region`);
        }
    }
};

onUnmounted(() => {
    sessionStorage.removeItem("drawRegionPolygonData");
    sessionStorage.removeItem("drawRegionInteractionId");
});

const uploadData = ref([]);
const handleUploadSuccess = (data) => {
    uploadData.value = data.imgArr;
    // 同步进度条：删除/增加图片时，总数和已上传数跟随当前列表变化
    const len = (data.imgArr && data.imgArr.length) || 0;
    totalUploadCount.value = len;
    uploadedSuccessCount.value = len;
};

const openMorePopup = (item) => {
    const data = item.exampleImageWithAnnotations.map(exampleItem => {
        return {
            ...exampleItem,
            shootingMethod: item.shootingMethod,
        }
    });
    morePopupRef.value.setItems(data);
    morePopupRef.value.openPopup();
}

const onCopyWechatId = () => {
    ElMessage.success("微信号已复制");
};

const oldUser = ref(false);
// 页面从勾画页返回时，如果组件被 keep-alive 缓存，则会触发 onActivated，在此再做一次回显
onActivated(() => {
    // 初始化加载
    getFarmList();
    // 加载数据
    loadData();
    renderRegionFromSession();
    // 恢复滚动位置
    const container = interactionListRef.value;
    const savedTop = sessionStorage.getItem(SCROLL_KEY);
    if (container && savedTop != null) {
        const top = Number(savedTop);
        if (!Number.isNaN(top)) {
            // 延迟一点，等 DOM 渲染完成后再滚动
            setTimeout(() => {
                container.scrollTop = top;
            }, 0);
        }
    }
    oldUser.value = query.value.oldUser && Boolean(query.value.oldUser);
    if (oldUser.value) {
        showFarmInfoPopup.value = true;
    }
});

const getFarmList = async () => {
    const { data } = await VE_API.farm.userFarmSelectOption();
    if (data && data.length === 0) {
        showFarmInfoPopup.value = true;
    }
}

const handleSubmitAll = () => {
    console.log("一键提交");
};

</script>
<style scoped lang="scss">
.interaction-list {
    width: 100%;
    height: calc(100vh - 40px);
    background: #f2f4f5;
    padding: 12px;
    box-sizing: border-box;
    overflow-y: auto;

    .list-item {
        background: #ffffff;
        border-radius: 6px;
        padding: 10px;
        border: 1px solid #ffffff;

        &.uploaded-item {
            border: 1px solid #2199f8;
        }

        .item-header-wrapper {
            .item-header {
                display: flex;
                align-items: center;
                justify-content: space-between;

                div {
                    font-size: 16px;
                    color: #6f6f6f;
                    font-family: "PangMenZhengDao";
                    width: fit-content;
                    background: rgba(143, 143, 143, 0.1);
                    padding: 5px 10px;
                    border-radius: 2px;
                }

                .status {
                    color: #999999;
                    background: #F1F1F1;

                    &.urgent-0 {
                        color: #2199f8;
                        background: rgba(33, 153, 248, 0.1);
                    }

                    &.urgent-1 {
                        color: #FF953D;
                        background: rgba(255, 149, 61, 0.1);
                    }

                    &.urgent-2 {
                        color: #EE4646;
                        background: rgba(238, 70, 70, 0.1);
                    }
                }
            }

            .upload-status {
                display: flex;
                align-items: center;
                gap: 4px;
                margin-left: 10px;

                .status-icon {
                    color: #2199f8;
                    font-size: 17px;
                }

                .status-text {
                    font-size: 14px;
                    color: #2199f8;
                }
            }

            &.has-status {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .item-header {
                    div {
                        color: #2199f8;
                        background: rgba(33, 153, 248, 0.1);
                    }
                }
            }
        }

        .expanded-content {
            background: rgba(33, 153, 248, 0.1);
            border-radius: 5px;
            padding: 10px;
            border: 0.5px solid #2199F8;
            margin-top: 12px;

            .uploaded-images {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                margin-top: 8px;

                .uploaded-img-wrap {
                    position: relative;
                    width: calc((100vw - 68px) / 4);
                    height: calc((100vw - 68px) / 4);
                }

                .uploaded-img {
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                    object-fit: cover;
                }

                .uploaded-img-remove {
                    position: absolute;
                    top: 0;
                    right: 0;
                    width: 18px;
                    height: 18px;
                    display: flex;
                    justify-content: center;
                    background: rgba(0, 0, 0, 0.6);
                    color: #fff;
                    font-size: 14px;
                    line-height: 16px;
                    border-radius: 50%;
                }
            }

            .continue-upload-btn {
                border: 0.5px solid rgba(33, 153, 248, 0.5);
                border-radius: 4px;
                background: #FFFFFF;
                cursor: pointer;
            }
        }

        .uploaded-content {
            .content-wrapper {
                border: 0.5px solid rgba(0, 0, 0, 0.1);
                border-radius: 4px;
                padding: 10px;
                margin-top: 12px;

                .item-desc {
                    color: #3C3C3C;
                    margin-bottom: 10px;
                    display: inline-block;
                }

                .tip-box {
                    font-size: 12px;
                    color: #2199F8;
                    padding: 3px 5px;
                    border-radius: 4px;
                    margin-bottom: 10px;
                    background: linear-gradient(90deg, rgba(33, 153, 248, 0.2) 0%, rgba(221, 221, 221, 0) 100%);
                }

                .example-wrapper {
                    .example-header {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        margin-bottom: 8px;
                        color: #BEB9B9;

                        .more {
                            font-size: 12px;
                        }
                    }

                    .example-list {
                        display: flex;
                        align-items: center;
                        overflow: hidden;

                        .image-item-wrapper {
                            position: relative;
                            margin-right: 6px;

                            &::after {
                                content: '示例';
                                position: absolute;
                                top: 0;
                                left: 0;
                                background: rgba(0, 0, 0, 0.7);
                                color: #F2F4F5;
                                padding: 2px 6px;
                                border-radius: 8px 0 2px 0;
                                font-size: 10px;
                                z-index: 1;
                            }
                        }

                        .image-item {
                            width: calc((100vw - 68px) / 4);
                            height: calc((100vw - 68px) / 4);
                            border-radius: 8px;
                            object-fit: cover;
                        }
                    }
                }

                .patrol-suggestion {
                    color: rgba(60, 60, 60, 0.4);
                    margin-top: 10px;

                    .action-text {
                        color: #727272;
                    }
                }
            }

            .upload-wrap {
                width: 100%;
                margin-top: 12px;

                ::v-deep {
                    .van-uploader__input-wrapper {
                        width: 100%;
                    }
                }

                .upload-btn {
                    width: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 4px;
                    color: #0B84E4;
                    padding: 6px;
                    border: 0.5px solid rgba(33, 153, 248, 0.5);
                    border-radius: 4px;
                    box-sizing: border-box;
                }
            }
        }

        .input-wrapper {
            margin: 12px 0;
        }

        .button-group {
            display: flex;
            gap: 12px;

            .btn-not-reached,
            .btn-default {
                flex: 1;
                text-align: center;
                border-radius: 4px;
                padding: 6px;
            }

            .btn-not-reached {
                max-width: fit-content;
                background: #fff;
                color: #585858;
                border: 1px solid rgba(88, 88, 88, 0.2);
            }

            .btn-default {
                background: #F1F1F1;
                color: #999999;
                border: 1px solid #F1F1F1;
            }

            .btn-confirm {
                background: #2199f8;
                color: #ffffff;
                border: 1px solid #2199f8;
            }
        }

        .proportion-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 12px;

            .proportion-text {
                color: #969696;
                font-size: 14px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                flex: 1;
                margin-right: 10px;
            }

            .toggle-btn {
                display: flex;
                align-items: center;
                gap: 2px;
                color: #8D8D8D;
                padding: 2px 10px;
                border: 1px solid rgba(0, 0, 0, 0.2);
                font-size: 12px;
                border-radius: 25px;
                background: #FFFFFF;

                .rotate {
                    transform: rotate(180deg);
                }
            }
        }
    }

    .list-item+.list-item {
        margin-top: 12px;
    }

    .empty-data {
        text-align: center;
        padding: 40px 0;
        color: #999999;
        font-size: 14px;
    }

    .question-wrapper {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 10px;
        margin: 12px 0 6px;
        box-sizing: border-box;
        width: 100%;

        .question-text {
            background: #ffffff;
            color: #6f6f6f;
            display: flex;
            align-items: center;

            .text-title {
                margin-right: 5px;
            }

            .text-unit {
                margin-left: 4px;
            }
        }

        .question-text+.question-text {
            margin-top: 6px;
        }

        .draw-region-btn {
            background: rgba(33, 153, 248, 0.1);
            border-radius: 4px;
            padding: 6px 10px;
            color: #2199f8;
        }
    }
}

.center-btn {
    justify-content: center;

    .primary-btn {
        padding: 10px 32px;
        background: #2199F8;
    }
}

.upload-progress-popup {
    width: 100%;
    padding: 20px 16px;

    .upload-progress-title {
        font-size: 16px;
        color: #121212;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .upload-progress {
            width: 55%;

            ::v-deep {
                .el-progress__text {
                    min-width: fit-content;
                }
            }
        }
    }

    .upload-box {
        margin-bottom: 12px;
    }

    .input-box {
        .input-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 6px;

            .label-input {
                width: 130px;
            }
        }

        .input-item+.input-item {
            margin-top: 6px;
        }
    }

    .region-tips {
        color: #2199F8;
        padding: 5px;
        background: rgba(33, 153, 248, 0.1);
        border-radius: 5px;
        margin: 16px 0 12px 0;
        text-align: center;
    }

    .region-map {
        width: 100%;
        height: 168px;
        clip-path: inset(0px round 5px);
        position: relative;

        .region-map-text {
            position: absolute;
            bottom: 0;
            right: 0;
            color: #FFFFFF;
            padding: 5px 20px;
            border-radius: 5px;
            background: rgba(0, 0, 0, 0.6);
            z-index: 1;
        }
    }

    .confirm-btn {
        background: #2199f8;
        color: #ffffff;
        border-radius: 4px;
        padding: 8px;
        text-align: center;
        font-size: 16px;
        margin-top: 16px;
    }
}
</style>
