<template>
    <div class="carousel-container">
        <!-- 图片列表 -->
        <div class="carousel-wrapper" :style="carouselStyle">
            <!-- <photo-provider v-if="images" :photo-closable="true" @visibleChange="handleVisibleChange">
                
                <template  v-for="(photo, index) in images"
                   :key="photo.id">
                    <album-draw-box :isShowNum="0" :farmId="766" :photo="photo" :current="currentIndex" :index="index" :length="images.length"
                    ></album-draw-box>
                    </template>
            </photo-provider> -->
            <div class="carousel-img" v-for="(photo, index) in images" :key="index">
                <div class="label-text" v-if="labelText">{{ labelText }}</div>
                <img class="img-dom" :index="index" @click="clickPhoto(photo)" :src="getPhotoSrc(photo)" alt="" />

                <div class="carousel-img-mask app-mask" v-if="!isAchievementImgs && imgType === 'app'">
                    <div class="mask-content app-mask-content">
                        <div class="app-mask-top">
                            <div class="app-mask-top-left">
                                <div class="app-year">{{ formatYear(imgData?.createTime || imgData?.updateTime) }}</div>
                                <div class="app-date-wrapper">
                                    <div class="app-date-line"></div>
                                    <div class="app-date">
                                        {{ formatMonthDay(imgData?.createTime || imgData?.updateTime) }}
                                    </div>
                                </div>
                            </div>
                            <div>
                                <!-- <div class="app-mask-top-right">
                                    <div class="app-phenology">当前处于 {{ imgData?.phenologyName }}</div>
                                    <div class="app-uploader">上传人:{{ imgData?.sourceDataJson?.userName }}</div>
                                </div> -->
                                <!-- 底部中间/右侧：天气信息和位置 -->
                                <div class="app-mask-bottom">
                                    <div class="app-weather-info">
                                        <div class="app-weather-item">
                                            <img class="app-weather-icon" src="@/assets/watermark/temp.png" alt="" />
                                            <span
                                                >{{ imgData?.sourceDataJson?.suitability?.tempMin }}-{{
                                                    imgData?.sourceDataJson?.suitability?.tempMax
                                                }}℃ {{ imgData?.sourceDataJson?.suitability?.tempSuitability }}</span
                                            >
                                        </div>
                                        <div class="app-weather-item">
                                            <img class="app-weather-icon" src="@/assets/watermark/shidu.png" alt="" />
                                            <span>{{ imgData?.sourceDataJson?.suitability?.humiditySuitability }}</span>
                                        </div>
                                        <div class="app-weather-item">
                                            <img class="app-weather-icon" src="@/assets/watermark/fushe.png" alt="" />
                                            <span>{{ imgData?.sourceDataJson?.suitability?.vindexSuitability }}</span>
                                        </div>
                                        <!-- <span class="app-weather-separator" v-if="imgData?.sourceDataJson?.address">-</span>
                                        <span class="app-location">
                                            {{ imgData?.sourceDataJson?.address }}
                                        </span> -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="carousel-img-mask app-mask" v-else-if="!isAchievementImgs && imgType === 'dji'">
                    <div class="mask-content app-mask-content">
                        <div class="dji-mask-top">
                            <span>{{ imgData?.sourceDataJson?.resFilename?.[index]?.treeCode }}</span>
                            <span>蓬径:{{ imgData?.sourceDataJson?.resFilename?.[index]?.pengjing }}m</span>
                            <span>高度:{{ imgData?.sourceDataJson?.resFilename?.[index]?.height.toFixed(1) }}m</span>
                            <span>{{ imgData?.sourceDataJson?.resFilename?.[index]?.highYield === 1 ? '高产树' : '低产树' }}</span>
                            <span>{{ imgData?.sourceDataJson?.resFilename?.[index]?.pingzhong }}</span>
                        </div>
                        <div class="app-mask-bottom">
                            <div class="app-weather-info">
                                <div class="app-weather-item">
                                    <img class="app-weather-icon" src="@/assets/watermark/temp.png" alt="" />
                                    <span
                                        >{{ imgData?.sourceDataJson?.suitability?.tempMin }}-{{
                                            imgData?.sourceDataJson?.suitability?.tempMax
                                        }}℃ {{ imgData?.sourceDataJson?.suitability?.tempSuitability }}</span
                                    >
                                </div>
                                <div class="app-weather-item">
                                    <img class="app-weather-icon" src="@/assets/watermark/shidu.png" alt="" />
                                    <span>{{ imgData?.sourceDataJson?.suitability?.humiditySuitability }}</span>
                                </div>
                                <div class="app-weather-item">
                                    <img class="app-weather-icon" src="@/assets/watermark/fushe.png" alt="" />
                                    <span>{{ imgData?.sourceDataJson?.suitability?.vindexSuitability }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="garden-info">
                            <span class="drone-date">{{ imgData?.droneDate }}</span>
                            <span class="code van-ellipsis">{{ imgData?.sourceDataJson?.resFilename?.[index]?.longCode }}</span>
                        </div>
                        <div class="base-map-wrapper" v-if="imgData?.sourceDataJson?.resFilename?.[index]?.baseMap">
                            <img
                                class="base-map-img"
                                :src="imgData?.sourceDataJson?.resFilename?.[index]?.baseMap"
                                alt=""
                            />
                        </div>
                    </div>
                </div>

                <template v-else>
                    <div class="carousel-img-mask" v-if="!isAchievementImgs">
                        <div class="mask-content">
                            <div class="mask-line line-top">
                                <span class="date-text">{{ imgData?.executeDate }}</span>
                                <span class="line-separator">|</span>
                                <span class="executor-text">执行人：{{ imgData?.executeName }}</span>
                            </div>
                            <div class="mask-line line-middle">
                                <span class="work-name">{{ imgData?.farmWorkName }}</span>
                                <span class="line-separator">|</span>
                                <span class="location-text">
                                    <img src="@/assets/watermark/address.png" alt="location" class="location-icon" />
                                    {{ imgData?.farmName }}
                                </span>
                            </div>
                            <div class="mask-line line-bottom">
                                <span class="prescription-text">药物处方：{{ prescriptionText }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="carousel-img-mask" v-if="isAchievementImgs && imgData?.reCheckText">
                        <div class="mask-content">
                            <div class="review-effect-text">{{ $t('复核成效') }}</div>
                            <div class="review-effect-content">
                                <span class="review-effect-content-text">{{ imgData?.reCheckText }}</span>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- 左右箭头 -->
        <div @click.stop="prev" v-if="currentIndex !== 0" class="arrow left-arrow">
            <el-icon color="#F0D09C"><ArrowLeftBold /></el-icon>
        </div>
        <div @click.stop="next" v-if="images && currentIndex !== images.length - 1" class="arrow right-arrow">
            <el-icon color="#F0D09C"><ArrowRightBold /></el-icon>
        </div>

        <div class="curren-img" v-if="currentPhoto">
            <div ref="currentImgRef" class="carousel-img" :class="{ noFit: isAchievementImgs }">
                <img class="img-dom" :src="currentPhoto" alt="" />
                <img src="@/assets/img/home/qrcode.png" alt="" class="code-icon" />
                <div class="carousel-img-mask" v-if="!isAchievementImgs">
                    <div class="mask-content">
                        <div class="mask-line line-top">
                            <span class="date-text">{{ imgData?.executeDate }}</span>
                            <span class="line-separator">|</span>
                            <span class="executor-text">执行人：{{ imgData?.executeName }}</span>
                        </div>
                        <div class="mask-line line-middle">
                            <span class="work-name">{{ imgData?.farmWorkName }}</span>
                            <span class="line-separator">|</span>
                            <span class="location-text">
                                <img src="@/assets/watermark/address.png" alt="location" class="location-icon" />
                                {{ imgData?.farmName }}
                            </span>
                        </div>
                        <div class="mask-line line-bottom">
                            <span class="prescription-text">药物处方：{{ prescriptionText }}</span>
                        </div>
                    </div>
                </div>
                <div class="carousel-img-mask" v-if="isAchievementImgs && imgData?.reCheckText">
                    <div class="mask-content">
                        <div class="review-effect-text">{{ $t('复核成效') }}</div>
                        <div class="review-effect-content">
                            <span class="review-effect-content-text">{{ imgData?.reCheckText }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <popup class="cavans-popup" v-model:show="showPopup" teleport="body" z-index="9999">
            <div class="cavans-content">
                <img class="current-img" :src="previewCanvas" alt="" />
            </div>
            <!-- 底部操作按钮 -->
            <div class="bottom-actions" @click.stop="showPopup = false">
                <div class="action-buttons">
                    <div class="action-btn text-btn">{{ $t('&lt;&lt;长按图片保存或转发&gt;&gt;') }}</div>
                    <!-- <div class="action-btn green-btn" @click.stop="handleWechat">
                        <div class="icon-circle">
                            <img src="@/assets/img/home/wechat.png" alt="" />
                        </div>
                        <span class="btn-label">{{ $t('微信') }}</span>
                    </div>
                    <div class="action-btn orange-btn" @click.stop="handleSaveImage">
                        <div class="icon-circle">
                            <el-icon :size="24"><Download /></el-icon>
                        </div>
                        <span class="btn-label">{{ $t('保存图片') }}</span>
                    </div> -->
                </div>
                <div class="cancel-btn" @click="handleCancel">{{ $t('取消') }}</div>
            </div>
        </popup>
    </div>
</template>

<script setup>
import { Popup } from "vant";
import { toRefs, ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
import AlbumDrawBox from "./albumDrawBox.vue";
import html2canvas from "html2canvas";
import { base_img_url2 } from "@/api/config";
import "./cacheImg.js";
const props = defineProps({
    images: {
        type: Array,
        required: true,
    },
    labelText: {
        type: String,
        default: "",
    },
    isAchievementImgs: {
        type: Boolean,
        default: false,
    },
    imgData: {
        type: Object,
        default: () => {},
    },
    imgType: {
        type: String,
        default: "",
    },
    disableClick: {
        type: Boolean,
        default: false,
    },
});
const { images, labelText, isAchievementImgs, imgType, disableClick } = toRefs(props);
let timer = null;
const currentIndex = ref(0);

onMounted(() => {
    updateImagePosition();
    clearAndRestartTimer();
    prescriptionText.value = buildPrescriptionText(props.imgData.prescriptionList);
});
onUnmounted(() => {
    clearInterval(timer);
});

watch(
    () => props.imgData,
    (newVal) => {
        if (newVal && newVal.prescriptionList) {
            prescriptionText.value = buildPrescriptionText(newVal.prescriptionList);
        }
    }
);

const prescriptionText = ref("");
function buildPrescriptionText(list) {
    if (!list || !Array.isArray(list) || list.length === 0) {
        return "无处方";
    }
    try {
        // 兼容原有格式：嵌套结构 [{ pesticideFertilizerList: [...] }]
        if (list[0]?.pesticideFertilizerList) {
            const result = list
                .map((group) =>
                    (group.pesticideFertilizerList || [])
                        .map((p) => p.defaultName || p.pesticideFertilizerName || "")
                        .filter(Boolean)
                        .join("+")
                )
                .filter(Boolean)
                .join("+");
            return result || "无处方";
        }
        
        // 兼容新格式：直接是字符串数组 ["药物1", "药物2"]
        if (typeof list[0] === "string") {
            return list.filter(Boolean).join("+") || "无处方";
        }
        
        // 兼容新格式：对象数组 [{ defaultName: "xxx" }, { defaultName: "yyy" }]
        if (list[0]?.defaultName || list[0]?.pesticideFertilizerName) {
            return list
                .map((p) => p.defaultName || p.pesticideFertilizerName || "")
                .filter(Boolean)
                .join("+") || "无处方";
        }
        
        return "无处方";
    } catch {
        return "无处方";
    }
}

const updateImagePosition = () => {
    carouselStyle.value.transform = `translateX(-${currentIndex.value * 100}%)`;
};

const clickPhotoShow = () => {
    if (timer) {
        clearInterval(timer);
    }
};

// 图片显隐切换回调
const handleVisibleChange = ({ visible }) => {
    if (visible.value) {
        if (timer) {
            clearInterval(timer);
        }
    } else {
        clearAndRestartTimer();
    }
};

// 计算轮播图样式
const carouselStyle = computed(() => {
    return {
        transform: `translateX(-${currentIndex.value * 100}%)`,
    };
});

// 下一张图片
const next = () => {
    // 图片总数
    const totalImages = images.value.length;
    currentIndex.value = (currentIndex.value + 1) % totalImages;
    updateImagePosition();
    clearAndRestartTimer();
};

// 上一张图片
const prev = () => {
    // 图片总数
    const totalImages = images.value.length;
    currentIndex.value = (currentIndex.value - 1 + totalImages) % totalImages;
    updateImagePosition();
    clearAndRestartTimer();
};

const clearAndRestartTimer = () => {
    if (timer) {
        clearInterval(timer);
    }
    // timer = setInterval(next, 5000);
};

const showPopup = ref(false);
const currentPhoto = ref(null);
const previewCanvas = ref(null);

const currentImgRef = ref(null);
const clickPhoto = (photo) => {
    if (disableClick.value) {
        return;
    }
    currentPhoto.value = getPhotoSrc(photo);
    nextTick(async () => {
        const canvas = await html2canvas(currentImgRef.value, {
            backgroundColor: "#ffffff00",
            scrollY: -window.scrollY, // 处理滚动条位置
            allowTaint: true, // 允许跨域图片
            useCORS: true, // 使用CORS
            scale: 2, // 提高分辨率（2倍）
            height: currentImgRef.value.scrollHeight, // 设置完整高度
            width: currentImgRef.value.scrollWidth, // 设置完整宽度
            logging: true, // 开启日志（调试用）
        });

        // 转换为图片并下载
        const image = canvas.toDataURL("image/png");
        setTimeout(() => {
            previewCanvas.value = image;
            showPopup.value = true;
        }, 100);
    });
};

const handleSaveImage = () => {
    downloadImage(previewCanvas.value, "执行照片");
};

function downloadImage(dataUrl, filename) {
    const link = document.createElement("a");
    link.href = dataUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

const getPhotoSrc = (photo) => {
    // if (isAchievementImgs.value) {
    //     return photo;
    // }
    return base_img_url2 + (photo.cloudFilename ? photo.cloudFilename : photo);
};

// 格式化年份
const formatYear = (dateStr) => {
    if (!dateStr) return "";
    const date = new Date(dateStr);
    if (Number.isNaN(date.getTime())) return "";
    return date.getFullYear().toString();
};

// 格式化月/日
const formatMonthDay = (dateStr) => {
    if (!dateStr) return "";
    const date = new Date(dateStr);
    if (Number.isNaN(date.getTime())) return "";
    const m = date.getMonth() + 1;
    const d = date.getDate();
    return `${m}/${d}`;
};
</script>

<style lang="scss" scoped>
@import "src/styles/index";
.carousel-container {
    position: relative;
    width: 100%;
    overflow: hidden;
    margin: 0 auto;
    .curren-img {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        width: 80%;
        height: 100%;
        margin: 0 auto;
        z-index: -1;
        pointer-events: none;
        .carousel-img {
            width: 100%;
            position: relative;
            overflow: hidden;
        }
        .img-dom {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 8px;
        }
    }
    .carousel-wrapper {
        display: flex;
        transition: transform 0.5s ease;
        width: 100%;
        .carousel-img {
            width: calc(100vw - 48px);
            min-width: calc(100vw - 48px);
            // min-width: 312px;
            // height: 255px;
            max-height: 90vh;
            object-fit: cover;
            position: relative;
            overflow: hidden;
            &.noFit {
                height: auto;
                object-fit: contain;
            }
            .img-dom {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 8px;
            }
            &.noFit {
                .img-dom {
                    height: auto;
                    object-fit: contain;
                }
            }
        }
    }
    .code-icon {
        position: absolute;
        right: 12px;
        top: 12px;
        width: 40px;
    }
    .carousel-img-mask {
        position: absolute;
        bottom: -2px;
        left: -2px;
        width: calc(100% + 2px);
        height: 80%;
        background: linear-gradient(360deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.4) 25%, rgba(0, 0, 0, 0) 40%);
        z-index: 1;
        pointer-events: none;
        display: flex;
        align-items: flex-end;
        padding: 8px 12px;
        box-sizing: border-box;
        border-radius: 8px 8px 12px 12px;
        &.app-mask {
            padding: 0;
            height: 100%;
        }
        .mask-content {
            width: 100%;
            color: #ffffff;
            font-size: 10px;
            line-height: 15px;
            &.app-mask-content {
                padding: 10px 8px;
                font-size: 12px;
                background: rgba(0, 0, 0, 0.2);
                backdrop-filter: blur(4px);
                .dji-mask-top {
                    background: rgba(0, 0, 0, 0.4);
                    backdrop-filter: blur(4px);
                    border-radius: 5px 0 5px 0;
                    padding: 6px 11px;
                    position: absolute;
                    top: -203px;
                    left: 0;
                    display: flex;
                    gap: 9px;
                    font-size: 10px;
                }
                .garden-info {
                    display: flex;
                    align-items: center;
                    margin-top: 4px;
                    width: calc(100% - 125px);
                    .code {
                        font-size: 10px;
                        opacity: 0.5;
                        margin-left: 5px;
                        width: 100%;
                        display: inline-block;
                    }
                }
                .base-map-wrapper {
                    position: absolute;
                    bottom: 4px;
                    right: 0;
                    width: 125px;
                    height: 94px;
                    z-index: 1;
                    .base-map-img {
                        width: 100%;
                        height: 100%;
                        border-radius: 4px;
                        border: 1px solid #ffffff;
                        object-fit: cover;
                        box-sizing: border-box;
                    }
                }
                .app-mask-top {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    .app-mask-top-left {
                        display: flex;
                        flex-direction: column;
                        align-items: flex-start;
                        .app-year {
                            font-size: 12px;
                            color: #ffffff;
                            margin-bottom: 4px;
                        }
                        .app-date-wrapper {
                            position: relative;
                            .app-date-line {
                                position: absolute;
                                top: -2px;
                                left: 0;
                                right: 0;
                                height: 1px;
                                background: #ffffff;
                            }
                            .app-date {
                                font-size: 12px;
                                color: #ffffff;
                                position: relative;
                            }
                        }
                    }
                    .app-mask-top-right {
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        .app-phenology {
                            color: #f0d09c;
                            font-weight: 500;
                        }
                        .app-uploader {
                            font-size: 10px;
                            color: #ffffff;
                            opacity: 0.5;
                        }
                    }
                }
                .app-mask-bottom {
                    display: flex;
                    align-items: center;
                    .app-weather-info {
                        display: flex;
                        align-items: center;
                        flex-wrap: wrap;
                        gap: 5px;
                        .app-weather-item {
                            color: #ffffff;
                            display: flex;
                            align-items: center;
                            gap: 2px;
                            .app-weather-icon {
                                width: 15px;
                                height: 15px;
                            }
                        }
                        .app-weather-separator {
                            font-size: 10px;
                            color: #ffffff;
                            margin: 0 4px;
                        }
                        .app-location {
                            font-size: 10px;
                            color: #ffffff;
                            opacity: 0.5;
                        }
                    }
                }
            }
        }
        .review-effect-text {
            font-family: "PangMenZhengDao";
            font-size: 16px;
            margin-bottom: 4px;
        }
        .review-effect-content {
            font-size: 10px;
            line-height: 15px;
        }
        .mask-line {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
        }
        .prescription-text {
            display: flex;
            .prescription-text-label {
                flex: none;
            }
        }
        .line-middle {
            margin-top: 4px;
            .work-name {
                font-family: "PangMenZhengDao", system-ui, -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial,
                    sans-serif;
                font-size: 17px;
            }
        }
        .line-bottom {
            margin-top: 4px;
        }
        .date-text {
            font-family: "PangMenZhengDao";
            font-size: 12px;
        }
        .date-text,
        .executor-text,
        .location-text {
            white-space: nowrap;
        }
        .location-icon {
            width: 9px;
            height: 10px;
            margin-right: 2px;
        }
        .line-separator {
            margin: 0 6px;
        }
    }
    .label-text {
        position: absolute;
        top: 0;
        left: 0;
        padding: 4px 10px;
        background: rgba(54, 52, 52, 0.8);
        color: #fff;
        font-size: 12px;
        border-radius: 8px 0 8px 0;
        z-index: 1;
    }
    .blur-bg {
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        backdrop-filter: blur(1.4px);
        .blur-content {
            border-radius: 8px;
            background: rgba(0, 0, 0, 0.5);
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #fff;
            .blur-img {
                img {
                    width: 54px;
                    position: relative;
                    left: 4px;
                    top: 4px;
                }
            }
            .blur-text {
                padding: 8px 0;
                text-align: center;
                line-height: 1.5;
            }
            .blur-btn {
                padding: 0 40px;
                box-shadow: 0 -2px 2px #86c9ff;
                height: 28px;
                line-height: 28px;
                border-radius: 50px;
                background: rgba(33, 153, 248, 0.7);
                // background: linear-gradient(#86C9FF, rgba(255, 255, 255, 0));
            }
        }
    }

    .arrow {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        width: rpx(72);
        height: rpx(72);
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        pointer-events: all;
    }

    .left-arrow {
        left: rpx(32);
    }

    .right-arrow {
        right: rpx(32);
    }
}

.cavans-popup {
    width: 100%;
    max-width: 100%;
    max-height: 90vh;
    background: none;
    border-radius: 12px;
    overflow: auto;
    display: flex;
    flex-direction: column;
    backdrop-filter: 4px;
    .cavans-content {
        text-align: center;
        padding: 16px;
        .current-img {
            width: 100%;
        }
    }

    // 底部操作按钮
    .bottom-actions {
        flex-shrink: 0;

        .action-buttons {
            padding: 16px;
            display: flex;
            justify-content: space-around;

            .action-btn {
                display: flex;
                flex-direction: column;
                align-items: center;
                cursor: pointer;
                &.text-btn {
                    font-size: 12px;
                    color: rgba(255, 255, 255, 0.7);
                }

                .icon-circle {
                    width: 48px;
                    height: 48px;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #fff;
                    margin-bottom: 4px;

                    .el-icon {
                        color: #fff;
                    }
                    img {
                        width: 50px;
                    }
                }

                &.blue-btn .icon-circle {
                    background: #2199f8;
                }

                &.green-btn .icon-circle {
                    background: #07c160;
                }

                &.orange-btn .icon-circle {
                    background: #ff790b;
                }

                .btn-label {
                    font-size: 12px;
                    color: #fff;
                }
            }
        }

        .cancel-btn {
            text-align: center;
            font-size: 18px;
            color: #fff;
            cursor: pointer;
        }
    }
}
</style>
