<template>
	<up-popup :show="showPopup" mode="center" round="20" @close="handleClose">
		<view class="album-popup">
			<view class="album-title">
				<view class="name">
					果树相册
					<view class="sub-name">无人机实时监测生长情况</view>
				</view>
				<image class="icon" :src="`${config.BASIC_IMG}img/treePage/drone-icon-popup.png`"></image>
			</view>
            <view class="album-cont">
                <view class="time-line-scroll">
                    <scroll-view class="time-line-container" scroll-x :scroll-into-view="scrollIntoViewId" scroll-with-animation @scroll="handleScroll" @scrollend="handleScrollEnd">
                        <view class="time-line">
                            <!-- 月份标记 -->
                            <view class="month-markers">
                                <view class="month-item" v-for="(month, index) in monthList" :key="index">
                                    <text class="month-text">{{ month.label }}</text>
                                    <view class="month-dot" :class="{'active': month.isCurrent}"></view>
                                </view>
                            </view>
                            <!-- 日期刻度 -->
                            <view class="date-markers">
                                <view class="date-item" v-for="(date, index) in dateList" :key="index" :class="{'current-date': date.isCurrent}">
                                    <text class="date-text" :class="{'current': date.isCurrent}">{{ date.display }}</text>
                                    <view class="date-dot" :class="{'current': date.isCurrent}"></view>
                                </view>
                            </view>
                        </view>
                    </scroll-view>
                    <!-- 中间竖线标志 -->
                    <view class="center-line"></view>
                </view>
				<view class="swiper-wrap">
					<swiper class="swiper">
						<swiper-item v-for="(item,index) in photoList" :key="index">
							<image class="img" :src="getImageUrl(item.filename)"></image>
						</swiper-item>
					</swiper>
					<!-- <view class="arrow left">
						<up-icon name="arrow-left" bold color="#F0D09C" size="22"></up-icon>
					</view>
					<view class="arrow right">
						<up-icon name="arrow-right" bold color="#F0D09C" size="22"></up-icon>
					</view> -->
				</view>
			</view>
		</view>
	</up-popup>
</template>

<script setup>
    import config from "@/api/config.js"
    import TREE from '@/api/tree.js'
	import {
		ref,
		watch,
		nextTick
	} from "vue";
	const resize = "?x-oss-process=image/resize,w_1000";

	const props = defineProps({
		show: {
			type: Boolean,
			defalut: false,
		},
        farmBuyId: {
            type: [String, Number],
            default: ''
        },
        sampleId: {
            type: [String, Number],
            default: 110939
        }
	});
	
	const showPopup = ref(false);
	const handleClose = ()=>{
		showPopup.value = false
	}
    const monthList = ref([])
    const dateList = ref([])
    const scrollIntoViewId = ref('')
    const selectedDateStr = ref('')
    const centerDate = ref('')

    const formatToDisplay = (dateStr)=>{
        // dateStr: YYYY-MM-DD
        const [y,m,d] = dateStr.split('-')
        return `${m}月${d}日`
    }
    const getTodayStr = ()=>{
        const d = new Date()
        const mm = `${d.getMonth()+1}`.padStart(2,'0')
        const dd = `${d.getDate()}`.padStart(2,'0')
        return `${d.getFullYear()}-${mm}-${dd}`
    }
    
    const generateTimeLineData = () => {
        const today = new Date()
        const currentYear = today.getFullYear()
        const currentMonth = today.getMonth() + 1
        const currentDay = today.getDate()
        
        // 生成月份列表（往前一年）
        const months = []
        for(let i = 11; i >= 0; i--) {
            const date = new Date(currentYear, currentMonth - 1 - i, 1)
            const month = date.getMonth() + 1
            const year = date.getFullYear()
            const isCurrent = month === currentMonth && year === currentYear
            
            months.push({
                year,
                month,
                label: `${month}月`,
                isCurrent,
                dateStr: `${year}-${month.toString().padStart(2,'0')}-01`
            })
        }
        monthList.value = months
        
        // 生成当前月份的日期刻度（每两天一个）
        const dates = []
        const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
        
        for(let day = 1; day <= daysInMonth; day += 2) {
            const dateStr = `${currentYear}-${currentMonth.toString().padStart(2,'0')}-${day.toString().padStart(2,'0')}`
            const isCurrent = day === currentDay
            
            dates.push({
                dateStr,
                display: `${currentMonth}月${day}日`,
                isCurrent,
                day
            })
        }
        dateList.value = dates
        
        // 设置当前日期为选中状态
        selectedDateStr.value = getTodayStr()
        centerDate.value = getTodayStr()
    }
    
    const fetchTreeImages = async (dateStr)=>{
        try{
            const params = {
                page: 1,
                limit: 1,
                treeId: 110939,
                date: dateStr,
            }
            const {data} = await TREE.treeImageList(params)
			photoList.value = data || []
        }catch(err){
            console.log('treeImageList error:', err)
        }
    }
	const getImageUrl = (filename) => {
	    if (filename.startsWith("https")) {
	        return filename; // 直接使用完整 URL
	    } else {
	        return config.BASE_IMG_URL + filename + resize; // 拼接基础 URL
	    }
	};
	
    const handleScroll = (e) => {
        // 滚动中实时计算中间位置
        const scrollLeft = e.detail.scrollLeft
        const viewWidth = e.detail.scrollWidth - e.detail.scrollLeft
        
        // 计算中间位置对应的日期
        const centerPosition = scrollLeft + viewWidth / 2
        const itemWidth = 120 // 每个时间项的宽度
        const estimatedIndex = Math.floor(centerPosition / itemWidth)
        
        if(dateList.value[estimatedIndex]){
            centerDate.value = dateList.value[estimatedIndex].dateStr
        }
    }
    
    const handleScrollEnd = (e) => {
        // 滚动停止时获取中间位置的日期并调用接口
        const scrollLeft = e.detail.scrollLeft
        const viewWidth = e.detail.scrollWidth - e.detail.scrollLeft
        
        const centerPosition = scrollLeft + viewWidth / 2
        const itemWidth = 120
        const estimatedIndex = Math.floor(centerPosition / itemWidth)
        
        if(dateList.value[estimatedIndex]){
            const finalDate = dateList.value[estimatedIndex].dateStr
            centerDate.value = finalDate
            selectedDateStr.value = finalDate
            console.log('滑动停止，中间位置日期:', finalDate)
            fetchTreeImages(finalDate)
        }
    }
    
    const handleDateClick = (dateStr)=>{
        selectedDateStr.value = dateStr
        centerDate.value = dateStr
        fetchTreeImages(dateStr)
    }
	const photoList = ref([]);
	
    watch(
        () => props.show,
        async (val) => {
            showPopup.value = val;
            if(val){
                generateTimeLineData()
                const today = getTodayStr()
                fetchTreeImages(today)
            }
        }
    );
    watch(
        () => props.farmBuyId,
        (val) => {
            if(showPopup.value && val){
                generateTimeLineData()
            }
        }
    )
</script>

<style lang="scss" scoped>
	.album-popup {
		width: 92vw;

		.album-title {
			padding: 30rpx 0 46rpx 30rpx;
			position: relative;
			background-image: linear-gradient(120deg, #79C4FF 13%, #FFFFFF 66%);
			border-radius: 40rpx 40rpx 0 0;
			line-height: 44rpx;

			.name {
				color: #004275;
				font-size: 48rpx;
				font-family: 'PangMenZhengDao';

				.sub-name {
					font-size: 24rpx;
				}
			}

			.icon {
				position: absolute;
				top: -100rpx;
				right: -26rpx;
				width: 364rpx;
				height: 300rpx;
			}
		}

        .album-cont {
			position: relative;
			z-index: 2;
			margin-top: -34rpx;
			padding: 32rpx 0 20rpx;
			background: #fff;
			border-radius: 40rpx;
            .time-line-scroll{
                margin-bottom: 16rpx;
                width: 100%;
                position: relative;
            }
            .time-line-container{
                width: 100%;
                white-space: nowrap;
            }
            .time-line{
                display: flex;
                flex-direction: column;
                padding: 0 20rpx;
                position: relative;
            }
            .center-line{
                position: absolute;
                left: 50%;
                top: 0;
                bottom: 0;
                width: 2rpx;
                background: #2199F8;
                z-index: 10;
                transform: translateX(-50%);
                pointer-events: none;
            }
            
            .month-markers{
                display: flex;
                align-items: flex-end;
                margin-bottom: 20rpx;
                
                .month-item{
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    min-width: 120rpx;
                    padding: 0 12rpx;
                    
                    .month-text{
                        font-size: 28rpx;
                        color: #777777;
                        margin-bottom: 8rpx;
                    }
                    
                    .month-dot{
                        width: 16rpx;
                        height: 16rpx;
                        background: #777777;
                        border-radius: 50%;
                        
                        &.active{
                            background: #2199F8;
                        }
                    }
                }
            }
            
            .date-markers{
                display: flex;
                align-items: flex-end;
                
                .date-item{
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    min-width: 120rpx;
                    padding: 0 12rpx;
                    
                    .date-text{
                        font-size: 24rpx;
                        color: #777777;
                        margin-bottom: 8rpx;
                        
                        &.current{
                            color: #2199F8;
                        }
                    }
                    
                    .date-dot{
                        width: 8rpx;
                        height: 8rpx;
                        background: #ccc;
                        border-radius: 50%;
                        
                        &.current{
                            background: #2199F8;
                            width: 16rpx;
                            height: 16rpx;
                        }
                    }
                }
            }
            
			.swiper-wrap{
				position: relative;
				padding: 0 20rpx;
				.swiper {
					width: 100%;
					height: 496rpx;
					
					.img{
						width: 100%;
						height: 100%;
						border-radius: 16rpx;
					}
				}
				.arrow{
					position: absolute;
					top: calc(50% - 40rpx);
					width: 80rpx;
					height: 80rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 50%;
					background: rgba(0, 0, 0, .6);
				}
				.left{
					left: 32rpx;
				}
				.right{
					right: 32rpx;
				}
			}
		}
	}
</style>