<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts"; // 引入 ECharts
import LTable from "@/components/LTable.vue";
import LTitle from "@/components/LTitle.vue";

const props = defineProps({
    data: {
        type: Object,
        required: true,
    },
});

const { data } = props;

// 图表相关
const chartInstance = ref(null); // ECharts 实例
const chartRef = ref(null); // 图表容器 DOM
const chartData = ref({});

const tableData = ref([]);

const opts = ref({
    color: ["#FAC858", "#EE6666", "#73C0DE", "#3CA272"],
});

function calculateTotalStats(data) {
    const timeDimensions = {
        m3: "近3月",
        m6: "近6月",
        m9: "近9月",
        m12: "近1年",
    };

    const result = [];
    for (const timeKey of Object.keys(timeDimensions)) {
        const countKey = `tl_id_${timeKey}_nbank_passlendamt`;
        let money = 1;
        if (data[countKey] !== undefined) {
            money = getLevelRange(Number(data[countKey] || 1), 3000);
        }
        result.push({
            date: timeDimensions[timeKey],
            money,
        });
    }

    return result;
}

function totalStats(data) {
    const timeDimensions = {
        m3: "近3月",
        m6: "近6月",
        m9: "近9月",
        m12: "近1年",
    };

    const result = {
        totalApplyCount: [],
        totalOrgCount: [],
    };

    for (const timeKey of Object.keys(timeDimensions)) {
        let totalApplyCount = 0;
        let totalOrgCount = 0;

        const applyCountKey = `tl_id_${timeKey}_nbank_passnum`;
        const orgCountKey = `tl_id_${timeKey}_nbank_passorg`;

        if (
            data[applyCountKey] !== undefined &&
            data[orgCountKey] !== undefined
        ) {
            totalApplyCount += Number(data[applyCountKey] || 0);
            totalOrgCount += Number(data[orgCountKey] || 0);
        }

        result.totalApplyCount.push(totalApplyCount);
        result.totalOrgCount.push(totalOrgCount);
    }

    return result;
}

function getLevelRange(level, threshold) {
    const upperLimit = level * threshold;
    const lowerLimit = (level - 1) * threshold;
    return `${lowerLimit}元 - ${upperLimit}元`;
}

// 初始化图表
function initChart() {
    if (!chartRef.value) return;

    if (!chartInstance.value) {
        chartInstance.value = echarts.init(chartRef.value);
    }

    const option = {
        color: opts.value.color,
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow",
            },
        },
        legend: {},
        xAxis: {
            type: "category",
            data: chartData.value.categories,
        },
        yAxis: {
            type: "value",
        },
        series: chartData.value.series.map((item) => ({
            name: item.name,
            type: "bar",
            data: item.data,
        })),
    };

    chartInstance.value.setOption(option);
}

// 更新图表
function updateChart() {
    if (chartInstance.value) {
        const option = {
            xAxis: {
                data: chartData.value.categories,
            },
            series: chartData.value.series.map((item) => ({
                name: item.name,
                data: item.data,
            })),
        };
        chartInstance.value.setOption(option);
    }
}

onMounted(() => {
    tableData.value = calculateTotalStats(data);
    console.log("tableData", tableData);
    const chatData = totalStats(data);

    chartData.value = {
        categories: ["近3月", "近6月", "近9月", "近1年"],
        series: [
            {
                name: "借贷次数",
                data: chatData.totalApplyCount,
            },
            {
                name: "借贷机构数",
                data: chatData.totalOrgCount,
            },
        ],
    };

    initChart();
});
</script>

<template>
    <div class="card">
        <div class="flex flex-col gap-y-4">
            <LTitle title="借贷次数" type="blue-green" />
            <div ref="chartRef" class="chart-container"></div>
            <LTitle title="借贷额度" type="blue-green" />
            <LTable :data="tableData" type="blue-green">
                <template #header>
                    <th class="border px-4 py-2">时间段</th>
                    <th class="border px-4 py-2">借贷数额</th>
                </template>
                <template #default="{ row }">
                    <td class="border px-4 py-2">{{ row.date }}</td>
                    <td class="border px-4 py-2">{{ row.money }}</td>
                </template>
            </LTable>
        </div>
    </div>
</template>

<style scoped>
.chart-container {
    width: 100%;
    height: 400px;
}
</style>
