<template>
    <div class="patrol-photo">
        <custom-header name="农场照片"></custom-header>
        <div class="patrol-content">
            <div class="photo-header">
                <el-date-picker style="width: 120px" v-model="value1" type="date" placeholder="全部日期" />
                <div class="select-wrap">
                    <div
                        :class="['select-item', { active: tabActive === index }]"
                        v-for="(item, index) in tabsList"
                        :key="index"
                        @click="handleTabAct(index)"
                    >
                        {{ item }}
                    </div>
                </div>
            </div>
            <div class="photo-wrap">
                <List
                    class="photo-list"
                    v-model:loading="loading"
                    :finished="finished"
                    :immediate-check="false"
                    finished-text="没有更多了"
                    @load="getPhotoList"
                >
                    <div class="photo-item" v-for="(dateItem, dateIndex) in photoListByDate" :key="dateIndex">
                        <div class="photo-item-top">
                            <span class="date-text">{{ dateItem.dateText }}</span>
                            <div class="weather-wrap">
                                <div class="weather-item">
                                    <i :class="'qi-'+ dateItem.weather.iconDay + '-fill'"></i>
                                    <span>{{ dateItem.weather.textDay }}</span>
                                </div>
                                <div class="weather-item">
                                    <img src="@/assets/img/home/temperature.png" alt="">
                                    <span>{{ dateItem.weather.tempMax }}℃</span>
                                </div>
                                <div class="weather-item">
                                    <img src="@/assets/img/home/humidity.png" alt="">
                                    <span>{{ dateItem.weather.humidity }}%</span>
                                </div>
                            </div>
                        </div>
                        <div class="photo-img-wrap">
                            <photo-provider :photo-closable="true">
                                <photo-consumer
                                    v-for="src in dateItem.images"
                                    intro="执行照片"
                                    :key="src"
                                    :src="src.path"
                                >
                                    <div class="photo-img">
                                        <img :src="src.path" />
                                    </div>
                                </photo-consumer>
                            </photo-provider>
                        </div>
                    </div>
                </List>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { List } from "vant";
import { base_img_url2, resize } from "@/api/config";
import customHeader from "@/components/customHeader.vue";

const router = useRouter();
const route = useRoute();
const tabActive = ref(0);
const tabsList = ["物候", "病虫", "生长"];
const handleTabAct = (index) => {
    tabActive.value = index;
};

const value1 = ref("");

// 按日期分组的图片列表
const photoListByDate = ref([]);
const loading = ref(false);
const finished = ref(false);
// 日期列表
const dateList = ref([]);
// 当前加载的日期索引
const currentDateIndex = ref(0);
// 是否正在加载日期列表
const isLoadingDates = ref(false);
// 是否正在请求图片数据（独立标志，避免与 List 组件的 loading 冲突）
const isRequestingImages = ref(false);
// 当前页码
const currentPageIndex = ref(0);
const farmId = ref(766);

// 格式化日期显示
const formatDate = (dateStr) => {
    if (!dateStr) return "";
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}年${month}月${day}日`;
};

// 获取有图片的日期列表
const findHasImagesDate = (isLoadMore = false) => {
    if (isLoadingDates.value) return Promise.resolve();

    isLoadingDates.value = true;
    const params = {
        farmId: farmId.value,
        pageIndex: currentPageIndex.value,
        limit: 10,
    };
    return VE_API.farm
        .findHasImagesDate(params)
        .then(({ data }) => {
            if (data && Array.isArray(data) && data.length > 0) {
                if (isLoadMore) {
                    // 如果是加载更多，追加到现有日期列表
                    dateList.value = [...dateList.value, ...data];
                } else {
                    // 首次加载，重置日期列表
                    dateList.value = data;
                    currentDateIndex.value = 0;
                    currentPageIndex.value = 1;
                }
                
                finished.value = false;
                loading.value = false;
                isLoadingDates.value = false;

                // 如果是首次加载，等待 List 组件触发加载
                if (!isLoadMore && data.length > 0) {
                    loading.value = false;
                    finished.value = false;
                    isRequestingImages.value = false;
                    // 使用 nextTick 确保 DOM 更新后，List 组件能检测到需要加载
                    nextTick(() => {
                        if (!finished.value && currentDateIndex.value < dateList.value.length) {
                            getPhotoList();
                        }
                    });
                }
            } else {
                // 没有更多日期了
                finished.value = true;
                isLoadingDates.value = false;
            }
        })
        .catch((error) => {
            console.error("findHasImagesDate 请求失败:", error);
            isLoadingDates.value = false;
            finished.value = true;
        });
};

// 加载下一个日期的图片
const loadNextDateImages = () => {
    // 如果已经加载完所有日期，尝试加载更多日期
    if (currentDateIndex.value >= dateList.value.length) {
        // 不是直接设置 finished，而是尝试获取更多日期
        loadMoreDates();
        return;
    }

    // 如果已经标记为完成，直接返回
    if (finished.value) {
        return;
    }

    // 如果正在请求，直接返回（避免重复请求）
    if (isRequestingImages.value) {
        return;
    }

    // 设置请求标志和 loading 状态
    isRequestingImages.value = true;
    loading.value = true;
    const currentDate = dateList.value[currentDateIndex.value];

    const params = {
        farmId: farmId.value,
        // farmId: route.query.farmId,
        date: currentDate,
    };

    VE_API.farm
        .getImageInfo(params)
        .then(({ data }) => {
            if (data.images.length > 0) {
                // 处理图片数据，添加图片路径
                const photoArr = data.images.map((item) => ({
                    ...item,
                    path: base_img_url2 + (item.resFilename || item.filename) + "?x-oss-process=image/resize,w_300",
                }));

                // 将当前日期的图片数据添加到列表中
                photoListByDate.value.push({
                    date: currentDate,
                    dateText: formatDate(currentDate),
                    images: photoArr,
                    weather: data.weather,
                });
            }
            
            // 移动到下一个日期
            currentDateIndex.value++;
        })
        .catch((error) => {
            console.error("获取图片失败:", error);
            // 请求失败时也移动到下一个日期，避免卡住
            currentDateIndex.value++;
        })
        .finally(() => {
            // 使用 finally 确保状态总是被重置
            isRequestingImages.value = false;
            loading.value = false;
            
            // 检查是否还有更多日期需要加载
            if (currentDateIndex.value >= dateList.value.length) {
                // 当前日期列表已加载完，尝试加载更多日期
                loadMoreDates();
            }
        });
};

// 加载更多日期
const loadMoreDates = () => {
    if (isLoadingDates.value || finished.value) {
        return;
    }
    
    // pageIndex + 1，获取下一页日期
    currentPageIndex.value++;
    loading.value = true;
    
    findHasImagesDate(true).then(() => {
        // 如果获取到新日期，继续加载图片
        if (currentDateIndex.value < dateList.value.length) {
            loadNextDateImages();
        }
    });
};

// 滚动加载触发
const getPhotoList = () => {
    // 如果已经完成，直接返回
    if (finished.value) {
        loading.value = false; // 确保 loading 状态被重置
        return;
    }

    // 调用加载函数（loadNextDateImages 内部会检查 loading 状态）
    loadNextDateImages();
};


onMounted(() => {
    farmId.value = route.query.farmId;
    findHasImagesDate();
});
</script>

<style lang="scss" scoped>
::v-deep {
    .van-list__finished-text {
        width: 100%;
    }
    .el-input__wrapper {
        box-shadow: none;
        border: 1px solid #2199f8;
        --el-input-placeholder-color: #2199f8;
    }
    .el-input__inner,
    .el-input__prefix {
        color: #2199f8;
    }
}
.patrol-photo {
    width: 100%;
    height: 100vh;
    background: #fff;
    .patrol-content {
        padding: 0 12px;
        width: 100%;
        height: calc(100vh - 50px);
        box-sizing: border-box;
        margin-top: 10px;
        .photo-header {
            display: flex;
            width: 100%;
            margin-bottom: 20px;
            .select-wrap {
                display: flex;
                width: calc(100% - 120px);
                .select-item {
                    margin-left: 12px;
                    flex: 1;
                    color: #666666;
                    padding: 6px 0;
                    text-align: center;
                    background: #f5f5f5;
                    border-radius: 5px;
                    &.active {
                        color: #2199f8;
                        background: #e0f1fe;
                    }
                }
            }
        }
        .photo-wrap {
            width: 100%;
            height: calc(100vh - 95px);
            overflow: auto;
            .photo-list {
                width: 100%;
                .photo-item {
                    width: 100%;
                    .photo-item-top {
                        display: flex;
                        align-items: center;
                        margin-bottom: 12px;
                        .date-text {
                            font-weight: 500;
                            font-size: 14px;
                            color: #333;
                            margin-right: 20px;
                        }
                        .weather-wrap {
                            display: flex;
                            align-items: center;
                            .weather-item {
                                display: flex;
                                gap: 4px;
                                align-items: center;
                                font-size: 12px;
                                margin-right: 10px;
                                img {
                                    width: 16px;
                                    height: 16px;
                                }
                            }
                        }
                    }
                    .photo-img-wrap {
                        display: flex;
                        flex-wrap: wrap;
                        gap: 10px;
                        // .region-text {
                        //     width: 68px;
                        //     text-align: center;
                        //     font-weight: 500;
                        //     font-size: 12px;
                        //     padding: 5px 0;
                        //     border-radius: 4px;
                        //     border: 1px solid #bbbbbb;
                        //     color: #666;
                        //     margin-bottom: 8px;
                        // }
                        .photo-img {
                            width: 110px;
                            height: 110px;
                            img {
                                width: 100%;
                                height: 100%;
                                border-radius: 8px;
                                object-fit: cover;
                            }
                        }
                    }
                }
                .photo-item + .photo-item {
                    margin-top: 20px;
                }
            }
        }
    }
}
</style>
