<template>
    <div class="achievement-report-page">
        <custom-header :name="$t('生成成果报告')"></custom-header>
        <div class="report-content-wrap" v-loading="loading">
            <div class="report-content" ref="reportDom">
                <img src="@/assets/img/home/qrcode.png" alt="" class="code-icon" />
                <div class="report-header">
                    <img class="header-book" src="@/assets/img/home/book.png" alt="" />
                    <div class="time-tag">{{ workItem?.executeDate }}</div>
                    <div class="report-title">{{ t('成果报告') }}</div>
                    <div class="report-info">
                        <div class="info-item">
                            <img class="info-icon" :src="workItem?.executorIcon || 'https://birdseye-img.sysuimars.com/dinggou-mini/defalut-icon.png'" alt="" />
                            <span class="info-text">执行组织:{{ workItem?.executeMain }}</span>
                        </div>
                        <div class="info-item">
                            <img class="info-icon" src="@/assets/img/home/farm.png" alt="" />
                            <span class="info-text">服务农场:{{ workItem?.farmName }}</span>
                        </div>
                    </div>
                </div>

                <div class="report-box">
                    <div class="report-box-item">
                        <div class="item-content">{{ workItem?.farmWorkName || "--" }}</div>
                        <div class="item-title">{{ t('作业农事') }}</div>
                    </div>
                    <div class="report-box-item">
                        <div class="item-content">{{ formatArea(workItem?.area) || "--" }}</div>
                        <div class="item-title">{{ t('作业面积') }}</div>
                    </div>
                    <div class="report-box-item">
                        <div class="item-content">{{ reportData?.workCycle ? (reportData?.workCycle + '天') : "--" }}</div>
                        <div class="item-title">{{ t('作业周期') }}</div>
                    </div>
                    <div class="report-box-item">
                        <div class="item-content">{{ reportData?.deviceName || "--" }}</div>
                        <div class="item-title">{{ t('使用设备') }}</div>
                    </div>
                </div>

                <!-- <div class="report-box">
                    <div class="box-title">{{ t('精准施治，智慧护航') }}</div>
                    <div class="box-text">
                        {{ reportData?.resultInfo || "--" }}
                    </div>
                </div> -->

                <div class="report-excute" v-for="(item, index) in workItem?.executeEvidence" :key="index">
                    <div class="tag-label">{{ t('执行照片') }}</div>
                    <album-draw-box :key="paramsPage.id" :isShowNum="0" :imgData="workItem" :photo="item" :current="index" :index="index" :length="workItem?.executeEvidence?.length"></album-draw-box>
                </div>
                <div class="report-excute" v-for="(item, index) in workItem?.reviewImage" :key="index">
                    <div class="tag-label">{{ t('复核照片') }}</div>
                    <album-draw-box :key="paramsPage.id+'复核'" :isShowNum="0" :isAchievementImgs="true" :imgData="workItem" :photo="item" :current="index" :index="index" :length="workItem?.reviewImage?.length"></album-draw-box>
                </div>
                <!-- <div class="report-excute" v-for="(item, index) in workItem?.reviewImage" :key="index">
                    <div class="tag-label">{{ t('复核照片') }}</div>
                    <album-draw-box :isShowNum="0" :photo="item" :current="index" :index="'review'+index" :length="workItem?.reviewImage?.length"></album-draw-box>
                </div> -->
                <!-- <div class="report-excute">
                    <album-carousel
                        :key="93"
                        :isAchievementImgs="true"
                        :images="combinedReviewImages"
                    ></album-carousel>
                </div> -->
            </div>

            <div class="bottom-btn">
                <div class="btn-item second" @click="handleDownload">{{ t('保存图片') }}</div>
                <div class="btn-item primay" @click="handleDownload">{{ t('转发') }}</div>
            </div>
        </div>

        <!-- 组合照片（用于生成合成图片） -->
        <div class="review-hide-box">
            <div class="review-image" ref="reviewComboRef">
                <div class="review-mask">
                    <div class="review-text">{{ t('复核成效') }}</div>
                    <div class="review-content">
                        {{ workItem?.reCheckText }}
                    </div>
                </div>
                <div class="vs-wrap" v-if="workItem?.reviewImage && workItem?.reviewImage?.length">
                    <img src="@/assets/img/home/vs.png" alt="" />
                </div>
                <div class="review-image-item" v-if="workItem?.executeEvidence?.length">
                    <div class="review-image-item-title">{{ t('复核照片') }}</div>
                    <img
                        class="review-image-item-img left-img"
                        :src="leftCoverImg"
                        style="width: 100%; height: 255px; display: block; image-rendering: auto"
                    />
                </div>
                <div class="review-image-item" v-if="workItem?.reviewImage?.length">
                    <img
                        class="review-image-item-img right-img"
                        :src="rightCoverImg"
                        style="width: 100%; height: 255px; display: block; image-rendering: auto"
                    />
                </div>
            </div>
        </div>
    </div>

    <popup class="cavans-popup" v-model:show="showPopup">
        <div class="cavans-content">
            <img class="current-img" :src="pageImg" alt="" />
        </div>
        <!-- 底部操作按钮 -->
        <div class="bottom-actions" @click.stop="showPopup = false">
            <div class="action-buttons">
                
                <div class="action-btn text-btn">
                    &lt;&lt;长按图片保存或转发&gt;&gt;
                </div>
            </div>
            <div class="cancel-btn" @click="handleCancel">{{ t('取消') }}</div>
        </div>
    </popup>
</template>

<script setup>
import { useI18n } from "@/i18n";
const { t } = useI18n();
import CustomHeader from "@/components/customHeader.vue";
import AlbumCarousel from "@/components/album_compoents/albumCarousel";
import { ref, onActivated, onDeactivated, onUnmounted, nextTick, watch } from "vue";
import html2canvas from "html2canvas";
import { uploadBase64 } from "@/common/uploadImg";
import { detectRuntimeEnvironment } from "@/common/commonFun";
import { useRoute } from "vue-router";
import { Popup } from "vant";
import { base_img_url2 } from "@/api/config";
import wx from "weixin-js-sdk";
import AlbumDrawBox from "@/components/album_compoents/albumDrawBox.vue";

const route = useRoute();
const loading = ref(false);
const workItem = ref({});
const showPopup = ref(false);
function formatArea(val) {
    const num = typeof val === "number" ? val : parseFloat(val);
    if (Number.isNaN(num)) return val;
    return Number.isInteger(num) ? num : num.toFixed(2) + "亩";
}
const paramsPage = ref({});
onActivated(() => {
    window.scrollTo(0, 0);
    paramsPage.value = route.query.miniJson ? JSON.parse(route.query.miniJson) : {};
    getDetail();
    getResultReport();
});

const reportData = ref({});
const getResultReport = () => {
    VE_API.z_farm_work_record.resultReport({ recordId: paramsPage.value.id }).then((res) => {
        if (res.code === 0) {
            reportData.value = res.data;
        }
    });
};

const getDetail = () => {
    if (!paramsPage.value.id) return;
    loading.value = true;
    VE_API.z_farm_work_record
        .getDetail({ id: paramsPage.value.id })
        .then(({ data }) => {
            workItem.value = data[0];
        })
        .finally(() => {
            loading.value = false;
        });
};

const isDowload = ref(true);
const reportDom = ref(null);
const pageImg = ref(null);

async function handleDownload() {
    isDowload.value = false;
    setTimeout(async () => {
        // 获取要截图的DOM元素
        const element = reportDom.value;

        try {
            const canvas = await html2canvas(element, {
                scrollY: -window.scrollY, // 处理滚动条位置
                allowTaint: true, // 允许跨域图片
                useCORS: true, // 使用CORS
                scale: 2, // 提高分辨率（2倍）
                height: element.scrollHeight, // 设置完整高度
                width: element.scrollWidth, // 设置完整宽度
                logging: true, // 开启日志（调试用）
            });

            // 转换为图片并下载
            const image = canvas.toDataURL("image/png");
            pageImg.value = image;
            nextTick(() => {
                showPopup.value = true;
            })
        } catch (error) {
            isDowload.value = true;
        }
    });
}

const handleCancel = () => {
    showPopup.value = false;
};

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 reviewComboRef = ref(null);
const combinedReviewImages = ref([]);
// 生成组合照片，传给相册组件
const generateCombinedReviewImage = async () => {
    try {
        await prepareCoverImages();
        await nextTick();

        const canvas = await html2canvas(reviewComboRef.value, {
            backgroundColor: null,
            useCORS: true,
            allowTaint: true,
            scale: window.devicePixelRatio || 2,
        });

        combinedReviewImages.value = [canvas.toDataURL("image/png")];
    } catch (e) {
        console.error("生成组合照片失败", e);
    }
};

const prepareCoverImages = async () => {
    await nextTick();

    const itemEl = reviewComboRef.value.querySelector(".review-image-item");

    const cssWidth = itemEl.offsetWidth;
    const cssHeight = 255;

    if (workItem.value?.executeEvidence?.length) {
        leftCoverImg.value = await coverImageToBase64HD(
            base_img_url2 + workItem.value.executeEvidence.at(-1),
            cssWidth,
            cssHeight
        );
    }

    if (workItem.value?.reviewImage?.length) {
        rightCoverImg.value = await coverImageToBase64HD(
            base_img_url2 + workItem.value.reviewImage.at(-1),
            cssWidth,
            cssHeight
        );
    }
};

const leftCoverImg = ref("");
const rightCoverImg = ref("");

function coverImageToBase64HD(imgUrl, cssWidth, cssHeight) {
    return new Promise((resolve, reject) => {
        const dpr = window.devicePixelRatio || 2;

        const img = new Image();
        img.crossOrigin = "anonymous";
        img.src = imgUrl;

        img.onload = () => {
            // ⚠️ 用“物理像素”创建 canvas
            const canvas = document.createElement("canvas");
            canvas.width = cssWidth * dpr;
            canvas.height = cssHeight * dpr;

            const ctx = canvas.getContext("2d");
            ctx.scale(dpr, dpr);

            const imgRatio = img.width / img.height;
            const targetRatio = cssWidth / cssHeight;

            let sx = 0,
                sy = 0,
                sw = img.width,
                sh = img.height;

            if (imgRatio > targetRatio) {
                sw = img.height * targetRatio;
                sx = (img.width - sw) / 2;
            } else {
                sh = img.width / targetRatio;
                sy = (img.height - sh) / 2;
            }

            ctx.drawImage(img, sx, sy, sw, sh, 0, 0, cssWidth, cssHeight);

            resolve(canvas.toDataURL("image/png"));
        };

        img.onerror = reject;
    });
}


const userInfoStr = localStorage.getItem("localUserInfo");
const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {};

async function handleForward() {
    setTimeout(async () => {
        // 获取要截图的DOM元素
        const element = reportDom.value;

        try {
            const canvas = await html2canvas(element, {
                scrollY: -window.scrollY, // 处理滚动条位置
                allowTaint: true, // 允许跨域图片
                useCORS: true, // 使用CORS
                scale: 2, // 提高分辨率（2倍）
                height: element.scrollHeight, // 设置完整高度
                width: element.scrollWidth, // 设置完整宽度
                logging: true, // 开启日志（调试用）
            });

            // 转换为图片并下载
            const image = canvas.toDataURL("image/png");
            const process = detectRuntimeEnvironment();
            // if (process === "wechat-webview") {
                const imgUrl = await uploadBase64(image, false);
                const params = {
                    val: 'share',
                    key: "report",
                };
                VE_API.mine.saveSessionStore({ ...params, text: imgUrl }).then((res) => {
                    if (res.success) {
                        wx.miniProgram.navigateTo({
                            url: `/pages/subPages/report_page/index`,
                        });
                    }
                });
            // }
            isDowload.value = true;
        } catch (error) {
            isDowload.value = true;
        }
    });


    // const image = await handleDownload(true);
    // const imgUrl = await uploadBase64(image, false);
    // const params = {
    //     miniUserId: 766,
    //     key: "report",
    // };
    // VE_API.mine.saveSessionStore({ ...params, text: imgUrl }).then((res) => {
    //     if (res.success) {
    //         wx.miniProgram.navigateTo({
    //             url: `/pages/subPages/report_page/index`,
    //         });
    //     }
    // });
}

watch(
    () => [workItem.value.executeEvidence, workItem.value.reviewImage],
    ([preImgs, reviewImgs]) => {
        if (preImgs && preImgs.length && reviewImgs && reviewImgs.length) {
            generateCombinedReviewImage();
        }
    },
    { deep: true }
);

// 清理数据的函数
const clearData = () => {
    workItem.value = {};
    reportData.value = {};
    paramsPage.value = {};
    loading.value = false;
    isDowload.value = true;
    combinedReviewImages.value = [];
    leftCoverImg.value = "";
    rightCoverImg.value = "";
};

onDeactivated(() => {
    clearData();
});

onUnmounted(() => {
    clearData();
});
</script>

<style lang="scss" scoped>
.achievement-report-page {
    width: 100%;
    height: 100vh;
    background: linear-gradient(195.35deg, #d4e4ff 16.34%, rgba(93, 189, 255, 0) 50.3%),
        linear-gradient(156.64deg, rgba(255, 255, 255, 0.16) 27.7%, rgba(255, 255, 255, 0) 72.82%);

    .report-content-wrap {
        height: calc(100% - 40px);
        padding-bottom: 60px;
        overflow: auto;
        box-sizing: border-box;
        position: relative;
        .bottom-btn {
            z-index: 2;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background: #fff;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 12px;
            box-sizing: border-box;
            box-shadow: 2px 2px 4.5px 0px rgba(0, 0, 0, 0.4);
            .btn-item {
                height: 40px;
                line-height: 40px;
                padding: 0 24px;
                border-radius: 20px;
                font-size: 14px;
                &.second {
                    color: #666666;
                    border: 1px solid rgba(153, 153, 153, 0.5);
                }
                &.primay {
                    padding: 0 34px;
                    background: linear-gradient(180deg, #76c3ff, #2199f8);
                    color: #fff;
                }
            }
        }
    }
    
    .code-icon {
        position: absolute;
        right: 10px;
        top: 12px;
        width: 48px;
    }
    .report-content {
        background: url("@/assets/img/home/report_bg.png") no-repeat center center;
        background-size: 100% auto;
        background-position: top center;
        padding: 24px 16px 16px;
        box-sizing: border-box;
        position: relative;
        .report-header {
            position: relative;
            .header-book {
                position: absolute;
                right: 0;
                bottom: -6px;
                height: 88px;
                z-index: 10;
            }
            .time-tag {
                background: linear-gradient(137.86deg, #9fd5ff 5.87%, #2199f8 82.98%);
                border-radius: 5px 0 5px 0;
                height: 23px;
                line-height: 23px;
                font-size: 13px;
                font-weight: 500;
                color: #fff;
                padding: 0 9px;
                width: fit-content;
            }
            .report-title {
                font-family: "PangMenZhengDao";
                font-size: 34px;
                line-height: 38px;
                color: #000000;
            }
            .report-info {
                padding: 10px 0 16px 0;
                .info-item {
                    width: fit-content;
                    display: flex;
                    height: 33px;
                    align-items: center;
                    padding: 0 6px 0 3px;
                    background: linear-gradient(90deg, rgba(255, 255, 255, 0.58) 0%, rgba(255, 255, 255, 0.0696) 100%);
                    border-radius: 20px;
                    border: 0.5px solid rgba(33, 153, 248, 0.35);
                    gap: 3px;
                    .info-icon {
                        width: 26px;
                        height: 26px;
                        object-fit: cover;
                        border-radius: 50%;
                    }
                    .info-text {
                        font-size: 14px;
                        color: #2199f8;
                    }
                }
                .info-item + .info-item {
                    margin-top: 5px;
                }
            }
        }

        .report-box {
            display: flex;
            align-items: center;
            padding: 8px;
            background: linear-gradient(0deg, #ffffff 86.32%, #2199f8 136.87%);
            border: 1px solid #ffffff;
            border-radius: 8px;
            gap: 5px;
            position: relative;
            .report-box-item {
                flex: 1;
                background: rgba(33, 153, 248, 0.1);
                border-radius: 8px;
                min-height: 62px;
                box-sizing: border-box;
                padding: 2px 4px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                .item-content {
                    color: #2199f8;
                    font-size: 14px;
                    text-align: center;
                }
                .item-title {
                    color: #000000;
                    font-size: 10px;
                    text-align: center;
                    padding-top: 5px;
                }
            }

            .box-title {
                position: absolute;
                top: -8px;
                left: 0;
                height: 32px;
                line-height: 26px;
                padding: 0 10px;
                color: #ffffff;
                background: url("@/assets/img/home/title-bg.png") no-repeat center center / 100% 100%;
            }
            .box-text {
                padding: 22px 0 12px 0;
            }
        }
        .report-box + .report-box {
            margin-top: 20px;
        }
        .report-excute {
            position: relative;
            margin-top: 12px;
            .tag-label {
                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;
            }
            ::v-deep {
                .carousel-container .carousel-wrapper .carousel-img {
                    min-width: calc(100vw - 32px);
                    width: calc(100vw - 32px);
                }
            }
        }
    }
    .download-btn {
        position: fixed;
        bottom: 20px;
        left: 50%;
        // background: #fff;
        // box-shadow: 2px 2px 4.5px 0px #00000066;
        // width: 100%;
        transform: translateX(-50%);
    }

    .review-hide-box {
        position: absolute;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        bottom: 0;
    }

    .review-image {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin: 12px;
        background: #fff;
        border-radius: 8px;
        .review-mask {
            z-index: 1;
            pointer-events: none;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            border-radius: 8px;
            background: linear-gradient(
                360deg,
                rgba(0, 0, 0, 0.78) 0%,
                rgba(0, 0, 0, 0.437208) 19.87%,
                rgba(0, 0, 0, 0) 33.99%
            );
            display: flex;
            flex-direction: column;
            align-items: baseline;
            justify-content: end;
            padding: 12px;
            box-sizing: border-box;
            color: #fff;
            .review-text {
                font-family: "PangMenZhengDao";
                font-size: 16px;
                margin-bottom: 1px;
            }
            .review-content {
                font-size: 10px;
                line-height: 15px;
            }
        }
        .vs-wrap {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 40px;
            height: 40px;
            z-index: 10;
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
        .review-image-item {
            position: relative;
            flex: 1;
            .review-image-item-title {
                position: absolute;
                top: 0;
                left: 0;
                background: rgba(54, 52, 52, 0.6);
                padding: 4px 10px;
                border-radius: 8px 0 8px 0;
                backdrop-filter: 4px;
                font-size: 12px;
                color: #fff;
            }
            // .review-image-item-img {
            //     width: 100%;
            //     height: 250px;
            //     object-fit: cover;
            // }
            .review-image-item-img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                object-position: center;
            }
            .left-img {
                border-radius: 8px 0 0 8px;
            }
            .right-img {
                border-radius: 0 8px 8px 0;
            }
        }
    }
}


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

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

        .action-buttons {
            padding: 12px 0 4px 0;
            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>
