<template>
    <BaseReport :feature="feature" :reportData="reportData" :reportParams="reportParams" :reportName="reportName"
        :reportDateTime="reportDateTime" :isEmpty="isEmpty" :isDone="isDone" isExample />
    <div class="w-20 h-20 z-[1000] fixed right-0 top-1/2 -translate-y-1/2">
        <img src="@/assets/images/example_sy.png" alt="example" class="w-full h-full object-contain" />
    </div>
</template>

<script setup>
import { aesDecrypt } from "@/utils/crypto";

const AES_KEY = import.meta.env.VITE_INQUIRE_AES_KEY;

const feature = ref("");
const reportData = ref([]);
const reportParams = ref({});
const reportName = ref("");
const reportDateTime = ref(null);
const isEmpty = ref(false);
const isDone = ref(false);
const active = ref(0);


onBeforeMount(() => {
    const query = new URLSearchParams(window.location.search);
    feature.value = query.get("feature");

    if (!feature.value) return;
    getReport();
});

const getReport = async () => {
    let queryUrl = `/query/example?feature=${feature.value}`;
    const { data, error } = await useApiFetch(queryUrl).get().json();

    if (data.value && !error.value) {
        if (data.value.code === 200) {
            if (!AES_KEY) {
                console.error("缺少解密密钥");
                isEmpty.value = true;
                isDone.value = true;
                return;
            }

            let decryptedData = data.value.data;

            if (typeof decryptedData === "string") {
                try {
                    const decryptedStr = aesDecrypt(decryptedData, AES_KEY);
                    decryptedData = JSON.parse(decryptedStr);
                } catch (err) {
                    console.error("报告数据解密失败", err);
                    isEmpty.value = true;
                    isDone.value = true;
                    return;
                }
            }

            if (!decryptedData) {
                isEmpty.value = true;
                isDone.value = true;
                return;
            }

            const sortedQueryData = Array.isArray(decryptedData.query_data)
                ? [...decryptedData.query_data].sort((a, b) => {
                    return a.feature.sort - b.feature.sort;
                })
                : [];
            reportData.value = sortedQueryData;
            console.log("reportData", reportData.value);
            reportParams.value = decryptedData.query_params || {};
            reportName.value = decryptedData.product_name || "";
            reportDateTime.value = decryptedData.create_time || null;
        } else if (data.value.code === 200003) {
            isEmpty.value = true;
        }
        isDone.value = true;
    }
};
</script>

<style lang="scss" scoped></style>
