<template>
    <div class="task-page" :style="{ height: `calc(100vh - ${tabBarHeight}px - 50px)` }">
        <div class="task-top">
            <div class="map-container" ref="mapContainer"></div>
            <div class="calendar-wrap">
                <calendar ref="calendarRef" @dateSelect="handleDateSelect"></calendar>
            </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 === 1 }" @click="handleActiveFilter(1)">
                    已确认({{ taskCounts[1] || 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>
            <!-- <div class="task-content-loading" v-if="loading && noData" v-loading="loading">
            </div> -->
            <div class="task-content" v-loading="loading">
                <div class="task-item" v-for="(item, index) in taskList" :key="item.id || item.workRecordId">
                    <task-item
                        :key="activeIndex + '-' + index"
                        :itemIndex="activeIndex"
                        :status="activeIndex === 3 ? 1 : 0"
                        :item-data="item"
                        @handleUploadSuccess="handleUploadSuccess"
                        :ref="(el) => setTaskItemRef(el, index)"
                    >
                        <template #footer>
                            <div class="item-footer" v-if="activeIndex === 0 || activeIndex === 2">
                                <div class="footer-l" @click="toDetail(item)">查看详情</div>
                                <div class="footer-r">
                                    <div v-if="activeIndex === 0" class="btn second" @click="handleAction(item)">
                                        忽略
                                    </div>
                                    <div class="btn primary" v-if="activeIndex === 0" @click="showPriceSheetPopup(item)">
                                        确认并报价
                                    </div>
                                    <div v-else class="btn primary" @click="showUploadExecutePopup(item)">
                                        请求确认
                                    </div>
                                </div>
                            </div>
                            <div v-else-if="activeIndex === 1" class="item-footer">
                                <div class="footer-l" @click="toDetail(item)">查看详情</div>
                                <div class="footer-r">
                                    <!-- <div class="btn second" @click="handleForward(item)">
                                        转发给客户
                                    </div> -->
                                    <div class="btn primary" @click="showPriceSheetPopup(item)">确认并报价</div>
                                </div>
                            </div>
                        </template>
                    </task-item>
                </div>
                <div class="empty-data" v-if="noData">暂无数据</div>
            </div>
        </div>
    </div>
    <upload-execute ref="uploadExecuteRef" :onlyShare="onlyShare" @uploadSuccess="handleUploadSuccess" />

    <popup v-model:show="showTaskPopup" round class="task-tips-popup">
        <template v-if="taskPopupType === 'warning'">
            <img class="create-farm-icon" src="@/assets/img/home/create-farm-icon.png" alt="" />
            <div class="create-farm-text">
                <div>
                    您确认忽略 <span class="main-text">{{ currentTask?.farmName }}</span> 的
                    <span class="main-text">{{ currentTask?.farmWorkName }}</span> 农事吗
                </div>
            </div>
        </template>
        <template v-else>
            <img class="farm-check-icon" src="@/assets/img/home/right.png" alt="" />
            <div class="create-farm-text success-text">农事已下发成功</div>
        </template>
        <div class="create-farm-btn" @click="handlePopupBtn">
            {{ taskPopupType === "warning" ? "确认忽略" : "我知道了" }}
        </div>
    </popup>
    <!-- 服务报价单 -->
    <price-sheet-popup ref="priceSheetPopupRef"></price-sheet-popup>
</template>

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

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 dateValue = ref("1");
const calendarRef = ref(null);

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

// 任务列表数据（用于显示，可能被筛选）
const taskList = ref([]);
// 完整的任务列表数据（用于日历显示，不被筛选影响）
const fullTaskList = ref([]);
// 各状态任务数量
const taskCounts = ref([0, 0, 0]);
// 当前选中的筛选索引
const activeIndex = ref(0);
// 筛选日期（用于按日期筛选）
const filterDate = ref(null);
const noData = ref(false);
const loading = ref(false);

const showTaskPopup = ref(false);
const taskPopupType = ref("warning");

// 根据 activeIndex 计算 startFlowStatus
const getStartFlowStatus = (index) => {
    const statusMap = {
        0: 0, // 待确认
        1: "1,2,3", // 待完成
        2: 4, // 待完成
        3: 5, // 已完成
    };
    return statusMap[index] ?? 0;
};

// 获取单个状态的任务数量
function getTaskCount(flowStatus, index) {
    const location = store.state.home.miniUserLocationPoint;
    return VE_API.z_farm_work_record
        .getSimpleList({ role: 2, location, flowStatus })
        .then(({ data }) => {
            if (Array.isArray(data)) {
                taskCounts.value[index] = data.length;
                calendarRef.value && calendarRef.value.setCounts(index, taskCounts.value[index]);

                if (index === 2) {
                    calendarRef.value && calendarRef.value.setSolarTerm(data);
                    indexMap.initData(data);
                }
            } else if (data?.total !== undefined) {
                taskCounts.value[index] = data.total;
            } else {
                taskCounts.value[index] = 0;
            }
        })
        .catch((error) => {
            console.error(`获取状态${index}任务数量失败:`, error);
            taskCounts.value[index] = 0;
        });
}

const taskItemRefs = ref([]);
const setTaskItemRef = (el, index) => {
    if (el) {
        taskItemRefs.value[index] = el;
    }
};

const handleUploadSuccess = async () => {
    // 先保存当前需要更新的 item id
    const currentItemIds = taskList.value.map((item) => item.id || item.workRecordId);

    // 刷新列表
    await getSimpleList();

    // 等待 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;
        getSimpleList();
    });
}

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

// 初始化时获取所有状态的任务数量
function initTaskCounts() {
    const location = store.state.home.miniUserLocationPoint;
    // 并行请求三个状态的数量
    Promise.all([
        getTaskCount(0, 0), // 待确认
        getTaskCount("1,2,3", 1), // 待确认
        getTaskCount(4, 2), // 待完成
        getTaskCount(5, 3), // 已完成
    ]);
}
const mapPoint = ref(null);

onMounted(() => {
    mapPoint.value = store.state.home.miniUserLocationPoint;

    // 初始化时获取所有状态的数量
    initTaskCounts();
    // 加载当前选中状态的数据列表
    getSimpleList();
    getDistrictListByCity();
    getFarmWorkTypeList();
    nextTick(() => {
        indexMap.initMap(mapPoint.value, mapContainer.value, true);
    });
});

// 标记是否正在通过日期选择切换筛选（避免 watch 清除日期筛选）
const isDateSelecting = ref(false);

// 监听 activeIndex 变化，重新加载数据
watch(activeIndex, () => {
    // 如果正在通过日期选择切换，不清除日期筛选
    if (isDateSelecting.value) {
        isDateSelecting.value = false;
        getSimpleList();
        return;
    }
    // 切换筛选时清除日期筛选
    filterDate.value = null;
    // 清除日历选中状态
    if (calendarRef.value) {
        calendarRef.value.clearSelection();
    }
    getSimpleList();
});

function getSimpleList() {
    loading.value = true;
    noData.value = false;
    // 清空refs数组，避免索引错乱
    taskItemRefs.value = [];
    const startFlowStatus = getStartFlowStatus(activeIndex.value);
    const params = {
        ...selectParma.value,
        role: 2,
        location: mapPoint.value,
        flowStatus: startFlowStatus,
        farmWorkTypeId: selectParma.value.farmWorkTypeId || null,
    };

    return VE_API.z_farm_work_record
        .getSimpleList(params)
        .then(({ data }) => {
            loading.value = false;
            // 假设返回的数据结构是 { list: [], total: 0 } 或者直接是数组
            let filteredData = data

            // 保存完整数据（用于日历显示）
            if (activeIndex.value === 2) {
                // 如果是"待完成"状态，保存完整数据用于日历
                fullTaskList.value = Array.isArray(data) ? data : [];
            }

            // 如果有日期筛选，在前端再次过滤（确保数据准确）
            if (filterDate.value && Array.isArray(data)) {
                filteredData = data.filter((item) => {
                    if (!item.executeDate) return false;
                    const itemDate = formatDate(new Date(item.executeDate));
                    return itemDate === filterDate.value;
                });
            }

            if (Array.isArray(filteredData) && filteredData.length > 0) {
                taskList.value = filteredData;
                // 更新当前状态的数量
                taskCounts.value[activeIndex.value] = filteredData.length;
                if (activeIndex.value === 2) {
                    // 传递给日历的数据应该是完整的未筛选数据
                    const calendarData = filterDate.value ? fullTaskList.value : taskList.value;
                    calendarRef.value && calendarRef.value.setSolarTerm(calendarData);
                    // 地图使用筛选后的数据
                    indexMap.initData(taskList.value);
                }
            }else{
                noData.value = true;
                taskList.value = [];
                taskCounts.value[activeIndex.value] = 0;
            }
        })
        .catch((error) => {
            console.error("获取任务列表失败:", error);
            loading.value = false;
            taskList.value = [];
            taskCounts.value[activeIndex.value] = 0;
            if (activeIndex.value === 2) {
                // 即使筛选后没有数据，日历也应该显示完整数据
                const calendarData = filterDate.value ? fullTaskList.value : [];
                indexMap.initData(taskList.value);
                calendarRef.value && calendarRef.value.setSolarTerm(calendarData);
            }
            noData.value = true;
        });
}

// 格式化日期函数（与 calendar 组件保持一致）
function formatDate(date) {
    if (typeof date === "string") {
        date = new Date(date);
    }
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(
        2,
        "0"
    )}`;
}

// 处理日历日期选择
const handleDateSelect = (date) => {
    if (date) {
        // 有日期选择，切换到"待完成"筛选并设置筛选日期
        filterDate.value = date;
        // 如果当前不是"待完成"状态，切换到"待完成"
        if (activeIndex.value !== 2) {
            isDateSelecting.value = true; // 标记正在通过日期选择切换
            activeIndex.value = 2;
            // watch 会处理 getSimpleList
        } else {
            // 如果已经是"待完成"状态，直接重新加载列表
            getSimpleList();
        }
    } else {
        // 取消日期筛选
        filterDate.value = null;
        // 重新加载列表
        getSimpleList();
    }
};

function handleActiveFilter(i) {
    activeIndex.value = i;
    // watch 会自动处理清除日期筛选和日历选中状态
    selectParma.value.districtCode = cityCode.value
    selectParma.value.farmWorkTypeId = null
}

function toPage(item) {
    // router.push("/servicZes_agri")
    // if (activeIndex.value === 2) {
    // } else {
    //     // 下发农事请求
    //     const data = {
    //         id: item.id,
    //     };
    //     VE_API.z_farm_work_record.issueFarmWorkRecord(data).then((res) => {
    //         if (res.code === 0) {
    //             taskPopupType.value = "success";
    //             showTaskPopup.value = true;
    //             getSimpleList();
    //         }
    //     });
    // }
}

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: { json: JSON.stringify({ id: item.id }) },
        });
    }
}

const priceSheetPopupRef = ref(null);
const showPriceSheetPopup = (item) => {
    VE_API.z_farm_work_record.getDetail({ id: item.id }).then(({ data }) => {
        const res = data[0];
        priceSheetPopupRef.value.handleShowPopup(res);
    });
};

const onlyShare = ref(false);
const currentTask = ref(null);
function handleAction(item) {
    if (activeIndex.value === 0) {
        taskPopupType.value = "warning";
        showTaskPopup.value = true;
        currentTask.value = item;
    } else {
        onlyShare.value = true;
        setTimeout(() => {
            uploadExecuteRef.value.showPopup(item, "share-sheet");
        }, 10);
    }
}

function handlePopupBtn() {
    showTaskPopup.value = false;
    if (taskPopupType.value === "warning") {
        // 确认忽略
    } else {
        // 待确认
        getTaskCount("1,2,3", 1);
    }
}

function handleForward(item) {
    if (item.quoteCount && item.quoteCount != 0) {
        onlyShare.value = true;
        setTimeout(() => {
            uploadExecuteRef.value.showPopup(
                { ...item, type: "quotation", farmWorkOrderId: item.orderId },
                "share-sheet"
            );
        }, 10);
    } else {
        ElMessage.warning("暂无报价数据,无法分享");
        return;
    }
}
</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: 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);
                }
            }
        }
    }

    .calendar-wrap {
        padding: 10px 0 4px 0;
    }

    .task-top {
        padding: 10px 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: 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 + .task-item {
        margin-top: 10px;
    }

    .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;
            }
        }
    }
}

.task-tips-popup {
    width: 75%;
    padding: 28px 28px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .create-farm-icon {
        width: 40px;
        height: 40px;
        margin-bottom: 12px;
    }
    .farm-check-icon {
        width: 68px;
        height: 68px;
        margin-bottom: 12px;
    }
    .create-farm-text {
        font-size: 20px;
        font-weight: 500;
        line-height: 40px;
        margin-bottom: 32px;
        text-align: center;
        &.success-text {
            font-size: 23px;
            font-weight: 400;
        }
    }
    .main-text {
        color: #2199f8;
    }
    .create-farm-btn {
        width: 100%;
        box-sizing: border-box;
        padding: 8px;
        border-radius: 25px;
        font-size: 16px;
        background: #2199f8;
        color: #fff;
        text-align: center;
    }
}
</style>
