<script setup lang="ts">
import SmallTitle from '../smallTitle/smallTitle.vue'
import { onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
    GridComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import './TrendOfTrafficFlow.less'
import moment from 'moment';
import { handleGetMonthAnalysis, handleGetProvinceMonthAnalysis } from '../../service';

// 注册组件
echarts.use([
    BarChart,
    GridComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    CanvasRenderer
]);

let myChart: echarts.ECharts;

onMounted(async () => {

    await handleGoMounted()
});


// 传入的数据
const props = defineProps<{
    currentService?: any;
}>();

// 监听传入的选中服务区
watch(
    () => props.currentService,
    (newVal, oldVal) => {
        handleGoMounted()
    },
    { deep: true }
);

// 初始运行的方法
const handleGoMounted = async () => {
    const res = await handleGetSectionFlowCount()

    const chartDom = document.getElementById('TrendOfTrafficFlow');
    if (!chartDom) return;

    myChart = echarts.init(chartDom);

    const option = {
        xAxis: {
            type: 'category',
            data: res.category,
            axisLabel: {
                color: '#fff',
                overflow: 'truncate', // 超出部分显示为省略号
                ellipsis: '...',     // 自定义省略符号（可选）
                interval: 0          // 强制显示所有标签
                // rotate: 30,  // 标签旋转30度（防止重叠）
            },
            axisLine: {
                lineStyle: {
                    color: '#fff' // 设置 x 轴线颜色为白色（可选）
                }
            }
            // data: res.category
        },
        yAxis: {
            type: 'value',
            name: '万辆',  // 仅在此处显示单位
            nameTextStyle: {
                color: '#fff',
                padding: [0, 30, 0, 0]  // 调整单位位置
            },
            axisLabel: {
                width: 60,
                color: '#fff',
                formatter: '{value}'  // 刻度值保持纯数字
            },
            axisLine: {
                show: true, // 显示 y 轴线
                lineStyle: {
                    color: '#fff' // 设置 y 轴线颜色为白色（可选）
                }
            },
            splitLine: { show: false },
            splitNumber: 5
        },
        series: [
            {
                name: `${res.currentYear}年断面流量`,
                // data: [120, 200, 150, 80, 70, 110, 130],
                data: res.seriesData,
                realData: res.realData,
                type: 'bar',
                barWidth: 5,
                smooth: true,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: function (params: any) {
                        // 自定义显示内容
                        return res.addRateList && res.addRateList[params.dataIndex] ? `${res.addRateList[params.dataIndex]}%` : '';
                    },
                    color: '#fff',  // 文字颜色
                    fontSize: 10     // 文字大小
                }
            },
            {
                name: `${res.yesYear}年断面流量`,
                data: res.yesSeriesData,
                realData: res.yesRealData,
                type: 'bar',
                barWidth: 5,
                smooth: true,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0]
                }
            },
        ],
        grid: {
            left: '0',    // 左侧间距
            right: '0',   // 右侧间距
            bottom: '0',    // 底部间距
            top: '40',       // 顶部间距
            containLabel: true // 确保坐标轴标签在grid内
        },
        tooltip: {  // 新增 tooltip 配置
            trigger: 'axis',  // 触发类型：坐标轴触发
            axisPointer: {    // 坐标轴指示器配置
                type: 'shadow' // 阴影指示器（适合柱状图）
            },
            formatter: function (params: any) {  // 自定义提示框内容
                // params 是数组，包含当前 hover 的所有系列数据
                return `<div>
                        <div>${params[0].seriesName}：${res?.realData[params[0]?.dataIndex].toLocaleString()}辆</div>
                        <div>${params[1].seriesName}：${res?.yesRealData[params[1]?.dataIndex].toLocaleString()}辆</div>
                    </div>`
            }
        },
        color: ['#008CFF', '#69BCFF', '#FF5E5E', '#FF9500'],
        legend: {
            data: [`${res.currentYear}年断面流量`, `${res.yesYear}年断面流量`],
            textStyle: {
                color: '#fff',
                fontSize: 12  // 设置图例文字大小为12px
            },
            right: '4%',
            top: '0%',
            orient: 'horizontal',
            type: 'scroll'     // 如果图例过长，启用滚动
        },
    };


    myChart.setOption(option);
    window.addEventListener('resize', resizeChart);
}

// 拿到断面流量数据
const handleGetSectionFlowCount = async () => {
    // const req: any = {
    //     // StatisticsMonth: moment().subtract(1, 'M').format('YYYYMM'),
    //     StatisticsMonth: "202504",
    //     Serverpart_ID: props.currentService?.SERVERPART_ID || "",
    //     SortStr: "SectionFlow_Count desc",
    //     ProvinceCode: "530000"
    // }
    // let data = await handleGetProvinceMonthAnalysis(req)

    const req: any = {
        ProvinceCode: '530000',
        StatisticsDate: moment().format('YYYY-MM-DD'),
        StartDate: moment().startOf('y').format('YYYY-MM-DD'),
        EndDate: moment().endOf('M').format('YYYY-MM-DD'),
    }

    let TrendOfTrafficFlow = sessionStorage.getItem('TrendOfTrafficFlow')
    let data: any = []
    if (TrendOfTrafficFlow) {
        data = JSON.parse(TrendOfTrafficFlow)
    } else {
        data = await handleGetMonthAnalysis(req)
        sessionStorage.setItem("TrendOfTrafficFlow", JSON.stringify(data))
    }


    const yesReq: any = {
        ProvinceCode: '530000',
        StatisticsDate: moment().subtract(1, 'y').endOf('M').format('YYYY-MM-DD'),
        StartDate: moment().subtract(1, 'y').startOf('y').format('YYYY-MM-DD'),
        EndDate: moment().subtract(1, 'y').endOf('M').format('YYYY-MM-DD'),
    }
    // let yesData = await handleGetMonthAnalysis(yesReq)


    let TrendOfTrafficFlowYes = sessionStorage.getItem('TrendOfTrafficFlowYes')
    let yesData: any = []
    if (TrendOfTrafficFlowYes) {
        yesData = JSON.parse(TrendOfTrafficFlowYes)
    } else {
        yesData = await handleGetMonthAnalysis(yesReq)
        sessionStorage.setItem("TrendOfTrafficFlowYes", JSON.stringify(yesData))
    }

    // let list = data.slice(0, 5)
    let category: string[] = []
    let seriesData: number[] = []
    let realData: number[] = []

    if (data && data.length > 0) {
        data.forEach((item: any) => {
            category.push(`${item.Statistics_Month}月`)
            seriesData.push(Number((item.SectionFlow_Count / 10000).toFixed(2)))
            realData.push(item.SectionFlow_Count)
        })
    }

    let yesSeriesData: number[] = []
    let yesRealData: number[] = []

    if (yesData && yesData.length > 0) {
        yesData.forEach((item: any) => {
            yesSeriesData.push(Number((item.SectionFlow_Count / 10000).toFixed(2)))
            yesRealData.push(item.SectionFlow_Count)
        })
    }

    // 算出增长率
    let addRateList: string[] = []
    for (let i = 0; i < category.length; i++) {
        let currentValue: number = realData[i]
        let yesValue: number = yesRealData[i]
        let add = ""
        if (yesValue > 0 && currentValue > 0) {
            add = (((currentValue - yesValue) / yesValue) * 100).toFixed(2)
        }
        addRateList.push(add)
    }



    // list.forEach((item: any) => {
    //     category.push(item.Serverpart_Name.split('服务区')[0])
    //     seriesData.push(Number((item.SectionFlow_Count / 10000).toFixed(2)))
    //     realData.push(item.SectionFlow_Count.toLocaleString())
    // })

    let res = {
        category: category,// x轴的内容
        seriesData: seriesData,// y轴的数据
        realData: realData,
        yesSeriesData: yesSeriesData,
        yesRealData: yesRealData,
        currentYear: moment().format('YYYY'),
        yesYear: moment().subtract(1, 'y').format('YYYY'),
        addRateList: addRateList
    }

    return res
}

const resizeChart = () => {
    myChart?.resize();
};

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart);
    myChart?.dispose();
});
</script>

<template>
    <div class="TrendOfTrafficFlowBox">
        <SmallTitle :title="`断面流量`" />

        <div class="TrendOfTrafficFlowCharts">
            <div class="TrendOfTrafficFlow" id="TrendOfTrafficFlow"></div>
        </div>
    </div>
</template>
