<template>
    <div class="task-page" :style="{ height: `calc(100vh - ${tabBarHeight}px - 50px)` }">
        <div class="task-top">
            <div class="map-container" ref="mapContainer"></div>
        </div>
        <div class="task-list">
            <!-- <div class="list-filter">
                <div class="filter-item" :class="{ active: activeIndex === 0 }" @click="handleActiveFilter(0)">
                    待确认({{ taskCounts[0] || 0 }})
                </div>
                <div class="filter-item" :class="{ active: activeIndex === 2 }" @click="handleActiveFilter(2)">
                    已确认({{ taskCounts[2] || 0 }})
                </div>
                <div class="filter-item" :class="{ active: activeIndex === 3 }" @click="handleActiveFilter(3)">
                    待提醒({{ taskCounts[3] || 0 }})
                </div>
            </div> -->
            <!-- <div class="select-group">
                <el-select
                    class="select-item"
                    v-model="selectParma.farmWorkTypeId"
                    placeholder="用户类型"
                    @change="getSimpleList"
                >
                    <el-option v-for="item in farmWorkTypeList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-select
                    class="select-item"
                    v-model="selectParma.districtCode"
                    placeholder="切换作物"
                    @change="getSimpleList"
                >
                    <el-option v-for="item in districtList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
            </div> -->
            <van-list
                v-model:loading="loadingMore"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
                :immediate-check="false"
            >
                <div class="task-content" v-loading="loading && taskList.length === 0">
                    <div class="task-item" v-for="(item, index) in taskList" :key="item.id || index">
                        <div class="img-text-wrap">
                            <div class="left-wrap">
                                <div class="left-img">
                                    <img src="@/assets/img/home/farm.png" alt="" />
                                </div>
                                <div class="right-text">
                                    <div class="farm-info">
                                        {{ item?.farmName }}
                                        <div class="info-tag-wrap">
                                            <div class="tag-item primary">
                                                {{ item?.typeName }}
                                            </div>
                                            <div class="tag-item second">托管客户</div>
                                        </div>
                                    </div>
                                    <div class="farm-addr">{{ item?.address }}</div>
                                </div>
                            </div>
                            <div class="right-wrap" @click.stop="handleRemindCustomer(item)">提醒客户</div>
                        </div>
                        <div class="item-bottom">
                            <div class="bottom-tag">
                                <div class="tag-card active">
                                    <div class="card-content">
                                        <div class="card-main-text">{{ item.sourceData?.currentPhenologyName || '--' }}</div>
                                        <div class="card-sub-text">
                                            当前物候期
                                            <span class="card-icon" @click="handleSelectCurrentPhenology(item)">
                                                <el-icon><Edit /></el-icon>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="tag-card">
                                    <div class="card-content">
                                        <div class="card-main-text">冲梢风险</div>
                                        <div class="card-sub-text">预计风险</div>
                                    </div>
                                </div>
                                <div class="tag-card">
                                    <div class="card-content">
                                        <div class="card-main-text">{{ item.sourceData?.daysUntilNext || '--' }}天</div>
                                        <div class="card-sub-text">预计下次物候</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 时间轴组件 -->
                            <AgriculturalInteractionCard :item="item" @updateList="resetAndLoad" />
                        </div>
                    </div>
                    <div class="empty-data" v-if="!loading && taskList.length === 0">暂无数据</div>
                </div>
            </van-list>
        </div>
    </div>
    <upload-execute ref="uploadExecuteRef" :onlyShare="onlyShare" @uploadSuccess="handleUploadSuccess" />
    <!-- 服务报价单 -->
    <price-sheet-popup :key="activeIndex" ref="priceSheetPopupRef"></price-sheet-popup>
    <!-- 新增：激活上传弹窗 -->
    <active-upload-popup ref="activeUploadPopupRef" @handleUploadSuccess="handleUploadSuccess"></active-upload-popup>
</template>

<script setup>
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import { List as VanList } from "vant";
import IndexMap from "../../farm_manage/map/index";
import { useRouter } from "vue-router";
import uploadExecute from "./uploadExecute.vue";
import priceSheetPopup from "@/components/popup/priceSheetPopup.vue";
import { ElMessage } from "element-plus";
import activeUploadPopup from "@/components/popup/activeUploadPopup.vue";
import AgriculturalInteractionCard from "@/components/pageComponents/AgriculturalInteractionCard.vue";

const store = useStore();
const router = useRouter();
const indexMap = new IndexMap();
const mapContainer = ref(null);
const tabBarHeight = computed(() => store.state.home.tabBarHeight);
const uploadExecuteRef = ref(null);

const selectParma = ref({
    farmWorkTypeId: null,
    districtCode: null,
});

// 任务列表数据（用于显示，可能被筛选）
const taskList = ref([]);
// 各状态任务数量
const taskCounts = ref([0, 0, 0]);
// 当前选中的筛选索引
const activeIndex = ref(2);
const noData = ref(false);
const loading = ref(false);
// 分页相关
const page = ref(0);
const limit = ref(10);
const loadingMore = ref(false);
const finished = ref(false);

// 查询未来农事预警
const getFutureFarmWorkWarning = async (item) => {
    const res = await VE_API.home.listFutureFarmWorkWarning({ farmId: item.farmId });
    item.timelineList = res.data || [];
};

const taskItemRefs = ref([]);
const handleUploadSuccess = async () => {
    // 刷新列表
    await resetAndLoad();

    // 等待 DOM 更新完成，refs 被重新收集
    await nextTick();

    // 更新所有task-item的triggerImg
    taskItemRefs.value.forEach((ref) => {
        if (ref && ref.updateTriggerImg) {
            ref.updateTriggerImg();
        }
    });
};

const cityCode = ref("");
//根据城市的坐标返回区县列表
const districtList = ref([]);
function getDistrictListByCity() {
    VE_API.z_farm_work_record.getDistrictListByCity({ point: mapPoint.value }).then(({ data }) => {
        districtList.value = data || [];
        // cityCode.value = data[0].code.slice(0, -2);
        cityCode.value = "";
        districtList.value.unshift({ code: cityCode.value, name: "全部" });
        selectParma.value.districtCode = cityCode.value;
        resetAndLoad();
    });
}

//农事类型列表
const farmWorkTypeList = ref([]);
function getFarmWorkTypeList() {
    VE_API.z_farm_work_record.getFarmWorkTypeList().then(({ data }) => {
        farmWorkTypeList.value = data;
        farmWorkTypeList.value.unshift({ id: 0, name: "全部" });
    });
}

const mapPoint = ref(null);

onMounted(() => {
    mapPoint.value = store.state.home.miniUserLocationPoint;
    // getDistrictListByCity();
    resetAndLoad();
    getFarmWorkTypeList();
    nextTick(() => {
        indexMap.initMap(mapPoint.value, mapContainer.value, true);
    });
});

// 监听 activeIndex 变化，重新加载数据
watch(activeIndex, () => {
    resetAndLoad();
});

// 加载列表数据（支持分页）
async function getSimpleList(isLoadMore = false) {
    if (!isLoadMore) {
        // 重置分页
        page.value = 0;
        finished.value = false;
        taskList.value = [];
        taskItemRefs.value = [];
        loading.value = true;
    } else {
        loadingMore.value = true;
    }

    const params = {
        ...selectParma.value,
        page: page.value,
        limit: limit.value,
        flowStatus: 5,
    };

    try {
        const { data } = await VE_API.home.listUnansweredFarms(params);
        
        if (!isLoadMore) {
            loading.value = false;
        } else {
            loadingMore.value = false;
        }

        if (data && data.length > 0) {
            // 为每个item初始化timelineList
            const newItems = data.map((item) => {
                let sourceData = item?.latestPhenologyProgressBroadcast?.sourceData;
                if (sourceData) {
                    try {
                        sourceData = JSON.parse(sourceData);
                    } catch (e) {
                        console.error("解析sourceData失败:", e);
                        sourceData = null;
                    }
                }
                return {
                    ...item,
                    sourceData,
                    timelineList: [],
                };
            });

            // 串行请求，为每个农场获取时间轴数据
            for (let i = 0; i < newItems.length; i++) {
                await getFutureFarmWorkWarning(newItems[i]);
            }

            // 追加数据
            taskList.value = [...taskList.value, ...newItems];
            
            // 更新分页
            page.value += 1;
            
            // 判断是否还有更多数据
            if (data.length < limit.value) {
                finished.value = true;
            }

            // 更新地图数据
            indexMap.initData(taskList.value);
        } else {
            finished.value = true;
            if (taskList.value.length === 0) {
                noData.value = true;
            }
        }
    } catch (error) {
        console.error("获取任务列表失败:", error);
        if (!isLoadMore) {
            loading.value = false;
        } else {
            loadingMore.value = false;
        }
        finished.value = true;
        if (taskList.value.length === 0) {
            noData.value = true;
        }
    }
}

// 滚动加载更多
const onLoad = () => {
    if (!finished.value && !loadingMore.value) {
        getSimpleList(true);
    }
};

// 重置并重新加载
const resetAndLoad = () => {
    getSimpleList(false);
};

function handleActiveFilter(i) {
    activeIndex.value = i;
    selectParma.value.districtCode = cityCode.value;
    selectParma.value.farmWorkTypeId = null;
}

const showUploadExecutePopup = (item) => {
    if (item?.executeEvidence.length) {
        onlyShare.value = true;
    } else {
        onlyShare.value = false;
    }
    setTimeout(() => {
        uploadExecuteRef.value.showPopup(item);
    }, 10);
};

function toDetail(item) {
    // if (activeIndex.value === 0) {
    //     router.push({
    //         path: "/modify_work",
    //         query: { id: item.id },
    //     });
    // } else {
    // }
    router.push({
        path: "/completed_work",
        query: { miniJson: JSON.stringify({ id: item.id }) },
    });
}

const onlyShare = ref(false);
const phenologyList = ref([
    {
        id: 1,
        name: "花芽分化",
    },
    {
        id: 2,
        name: "开花",
    },
    {
        id: 3,
        name: "成熟",
    },
]);

const activeUploadPopupRef = ref(null);
function handleSelectCurrentPhenology(item) {
    activeUploadPopupRef.value.showPopup({
        gardenIdVal: item.farmId,
        problemTitleVal: "进入 物候期 的时间",
        imgDescVal: "请上传凭证(转入农事任务凭证）",
        arrangeIdVal: item.farmWorkArrangeId,
        selectCurrentPhenologyVal: true,
        phenologyListVal: phenologyList.value,
    });
}

function handleRemindCustomer(item) {
    router.push({
        path: "/remind_customer",
        query: { farmId: item.farmId },
    });
}
</script>

<style lang="scss" scoped>
.task-page {
    width: 100%;
    height: calc(100vh - 50px - 50px);
    overflow: auto;
    box-sizing: border-box;
    background: #f5f7fb;
    .map-container {
        width: 100%;
        height: 162px;
        clip-path: inset(0px round 8px);
    }

    .select-group {
        display: flex;
        padding: 0px 12px 0 12px;
        .select-item {
            width: 100%;
            ::v-deep {
                .el-select__wrapper {
                    text-align: center;
                    gap: 2px;
                    box-shadow: none;
                    justify-content: center;
                    background: none;
                }
                .el-select__selection {
                    flex: none;
                    width: fit-content;
                }
                .el-select__placeholder {
                    position: static;
                    transform: none;
                    width: fit-content;
                    color: rgba(0, 0, 0, 0.2);
                }
                .el-select__caret {
                    color: rgba(0, 0, 0, 0.2);
                }
            }
        }
    }

    .task-top {
        padding: 10px 12px 0 12px;
    }

    .task-content-loading {
        height: 80px;
        border-radius: 8px;
        position: absolute;
        top: 60px;
        left: 0;
        width: 100%;
    }

    .task-content {
        min-height: 80px;
    }

    .empty-data {
        text-align: center;
        font-size: 14px;
        color: #6f7274;
        padding: 20px 0;
    }
    .task-list {
        position: relative;
        background: #fff;
        padding: 12px 12px 8px 12px;
    }
    .list-filter {
        display: flex;
        align-items: center;
        justify-content: space-around;
        .filter-item {
            padding: 0 12px;
            height: 28px;
            color: rgba(0, 0, 0, 0.5);
            font-size: 14px;
            line-height: 28px;
            border-radius: 20px;
            &.active {
                color: #2199f8;
                background: rgba(33, 153, 248, 0.2);
            }
        }
    }
    .task-item {
        border-radius: 12px;
        border: 0.3px solid rgba(0, 0, 0, 0.2);
        padding: 12px;
    }

    .task-item + .task-item {
        margin-top: 10px;
    }

    .img-text-wrap {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        padding-bottom: 10px;
        border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);
        .left-wrap {
            display: flex;
            align-items: center;
            .left-img {
                width: 40px;
                height: 40px;
                border-radius: 6px;
                img {
                    width: 100%;
                    height: 100%;
                    object-fit: contain;
                }
            }
            .right-text {
                padding-left: 8px;
                .farm-info {
                    font-size: 14px;
                    color: #1d2129;
                    display: flex;
                    align-items: center;
                    .info-tag-wrap {
                        margin-left: 10px;
                        display: flex;
                        align-items: center;
                        gap: 4px;
                        .tag-item {
                            height: 20px;
                            line-height: 20px;
                            padding: 0 8px;
                            border-radius: 2px;
                            font-size: 12px;
                            &.second {
                                color: #ff953d;
                                background: rgba(255, 149, 61, 0.1);
                            }
                            &.primary {
                                color: #2199f8;
                                background: #e8f3ff;
                            }
                        }
                    }
                }
                .farm-addr {
                    padding-top: 2px;
                    font-size: 12px;
                    color: #86909c;
                }
            }
        }
        .right-wrap {
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            color: #fff;
            background: #2199f8;
            font-size: 12px;
            flex: none;
            width: 44px;
            height: 44px;
            padding: 8px;
            border-radius: 5px;
            box-sizing: border-box;
            .click-item {
                display: flex;
                align-items: center;
                gap: 2px;
            }
            .follow-text {
                color: #d0d0d0;
            }
        }
    }

    .item-bottom {
        padding-top: 10px;
        .bottom-tag {
            display: flex;
            gap: 10px;
            .tag-card {
                flex: 1;
                border-radius: 2px;
                padding: 4px;
                box-sizing: border-box;
                border: 0.4px solid rgba(215, 215, 215, 0.5);
                .card-content {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    text-align: center;
                    .card-main-text {
                        font-size: 16px;
                        font-weight: 500;
                        color: #202020;
                        margin-bottom: 2px;
                    }
                    .card-sub-text {
                        font-size: 10px;
                        color: rgba(32, 32, 32, 0.4);
                        display: flex;
                        align-items: center;
                        gap: 4px;
                        .card-icon {
                            display: inline-flex;
                            align-items: center;
                            justify-content: center;
                            width: 12px;
                            height: 12px;
                            color: #2199f8;
                        }
                    }
                }
                &.active {
                    background: rgba(33, 153, 248, 0.1);
                    border: 0.5px solid #2199f8;
                    .card-content {
                        .card-main-text {
                            color: #2199f8;
                        }
                        .card-sub-text {
                            color: #2199f8;
                        }
                    }
                }
            }
        }
    }

    .item-footer {
        margin-top: 10px;
        padding-top: 11px;
        border-top: 1px solid rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        .footer-l {
            color: #8b8b8b;
            font-size: 12px;
            &.primary-btn {
                display: inline-flex;
                align-items: center;
                border: 1px solid #2199f8;
                background: rgba(33, 153, 248, 0.1);
                padding: 0 12px;
                height: 32px;
                box-sizing: border-box;
                display: flex;
                align-items: center;
                border-radius: 20px;
                color: #2199f8;
                .share-icon {
                    width: 12px;
                    padding-right: 4px;
                }
            }
            &.farm-name-text {
                font-size: 14px;
                color: #6f7274;
                .name-text {
                    padding-left: 4px;
                }
            }
        }
        .footer-r {
            display: flex;
            align-items: center;
            .btn {
                height: 32px;
                line-height: 32px;
                padding: 0 12px;
                border-radius: 20px;
                display: flex;
                align-items: center;
                box-sizing: border-box;
                &.second {
                    // border: 1px solid #8B8B8B;
                    // color: #8B8B8B;
                    color: #2199f8;
                    background: rgba(33, 153, 248, 0.1);
                }
                &.primary {
                    background: #2199f8;
                    color: #fff;
                }
                .btn-icon {
                    padding-right: 4px;
                }
                &.warning {
                    color: #ff953d;
                    background: #fff;
                    border: 1px solid #ff953d;
                }
                &.secondary-text {
                    color: #2199f8;
                    border: 1px solid #2199f8;
                }
            }
            .btn + .btn {
                margin-left: 8px;
            }
        }
    }
}
</style>
