<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">
                <customCalendar ref="calendarRef" @dateSelect="handleDateSelect"></customCalendar>
            </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>
            <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 === 0 ? 0 : 1"
                        :item-data="item"
                        @handleUploadSuccess="handleUploadSuccess"
                        :ref="(el) => setTaskItemRef(el, index)"
                    >
                        <template #footer>
                            <div class="item-footer" v-if="activeIndex === 2">
                                <div class="footer-l farm-name-text van-ellipsis">
                                    来自<span class="name-text">{{ item.farmName || "--" }}</span>
                                </div>
                                
                                <div class="footer-r" v-if="item.reviewImage && item.reviewImage.length">
                                    <div class="btn warning" @click="generateReport(item)">生成成果报告</div>
                                </div>
                                <div class="footer-r" v-else>
                                    <div class="btn primary" @click="handleAction(item)">上传复核照片</div>
                                </div>
                            </div>
                            <div v-else-if="activeIndex === 1" class="item-footer">
                                <div class="footer-l farm-name-text van-ellipsis">
                                    来自<span class="name-text">{{ item.farmName || "--" }}</span>
                                </div>
                                <div class="footer-r">
                                    <div class="btn warning" @click="generateReport(item)">生成成果报告</div>
                                </div>
                            </div>
                            <div v-else-if="activeIndex === 0" class="item-footer">
                                <div class="footer-l" @click="toDetail(item)">查看详情</div>
                                <div class="footer-r" v-if="item.expectedExecuteDate">
                                    <div class="btn primary" @click="showUploadExecutePopup(item)">上传照片</div>
                                </div>
                                <div class="footer-r" v-else>
                                    <div class="btn warning" @click="selectExecuteTime(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" />

    <!-- 服务报价单 -->
    <price-sheet-popup :key="activeIndex" ref="priceSheetPopupRef"></price-sheet-popup>
    <offer-popup ref="offerPopupRef" @uploadSuccess="handleUploadSuccess"></offer-popup>

    <!-- 确认执行时间 -->
    <calendar
        teleport="#app"
        v-model:show="showCalendar"
        @confirm="onConfirmExecuteTime"
        :min-date="minDate"
        :max-date="maxDate"
    />
</template>

<script setup>
import { computed, nextTick, onActivated, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import { Popup, Calendar } from "vant";
import IndexMap from "../../farm_manage/map/index";
import taskItem from "@/components/taskItem.vue";
import customCalendar 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";
import offerPopup from "@/components/popup/offerPopup.vue";
import { formatDate } from "@/common/commonFun";

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 showPopup = ref(false);
const executionData = 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);

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

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

                if (index === 0) {
                    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 () => {
    // 刷新列表
    await getSimpleList();
};

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(4, 0), // 待完成
        getTaskCount(5, 1), // 已完成
        getTaskCount(5, 2), // 待复核
    ]);
}
const mapPoint = ref(null);

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

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

onActivated(() => {
    getSimpleList();
});

// 标记是否正在通过日期选择切换筛选（避免 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 needReview = activeIndex.value === 2 ? 1 : null;
    const params = {
        ...selectParma.value,
        role: 2,
        location: mapPoint.value,
        flowStatus: startFlowStatus,
        farmWorkTypeId: selectParma.value.farmWorkTypeId || null,
        needReview: needReview,
        includePrescription: activeIndex.value === 0 ? false : true,
    };

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

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

            // 如果有日期筛选，在前端再次过滤（确保数据准确）
            if (filterDate.value && Array.isArray(filteredData)) {
                filteredData = filteredData.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 === 0) {
                    // 传递给日历的数据应该是完整的未筛选数据
                    const calendarData = filterDate.value ? fullTaskList.value : taskList.value;
                    console.log('calendarData', calendarData);
                    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 === 0) {
                // 即使筛选后没有数据，日历也应该显示完整数据
                const calendarData = filterDate.value ? fullTaskList.value : [];
                indexMap.initData(taskList.value);
                calendarRef.value && calendarRef.value.setSolarTerm(calendarData);
            }
            noData.value = true;
        });
}

// 处理日历日期选择
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 offerPopupRef = ref(null);
const showUploadExecutePopup = (item) => {
    offerPopupRef.value.openPopup(item);
};

const generateReport = (item) => {
    router.push({
        path: "/achievement_report",
        query: { miniJson: JSON.stringify({ id: item.id }) },
    });
};

function toDetail(item) {
    // router.push({
    //         path: "/modify",
    //         query: { id: item.id },
    //     });
    router.push({
        path: "/completed_work",
        query: { miniJson: JSON.stringify({ id: item.id }) },
    });
}

const showCalendar = ref(false);
const maxDate = ref();
const minDate = new Date(2010, 0, 1);
const executeItem = ref(null);
const selectExecuteTime = (item) => {
    executeItem.value = item;
    maxDate.value = new Date(item.executeDeadlineDate);
    showCalendar.value = true;
};

const onConfirmExecuteTime = (date) => {
    showCalendar.value = false;
    VE_API.z_farm_work_record
        .updateExpectedExecuteDate({ recordId: executeItem.value.id, expectedExecuteDate: formatDate(date) })
        .then((res) => {
            if (res.code === 0) {
                ElMessage.success("操作成功");
                getSimpleList();
            }
        });
};

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);
function handleAction(item) {
    setTimeout(() => {
        uploadExecuteRef.value.showPopup(item, "share-sheet");
    }, 10);
}

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: center;
        gap: 20px;
        .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;
            }
        }
    }
}
</style>

<style lang="scss">
.van-calendar__popup {
    z-index: 9999 !important;
}
</style>
