<script setup lang="ts">
import SmallTitle from '../smallTitle/smallTitle.vue';
import './VehicleStayAnalysis.less'
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 { onBeforeUnmount, onMounted, watch } from 'vue';
import { handleGetBayonetSTAList } from '../../service';
import moment from 'moment';

// 注册组件
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 handleGetData()
    console.log('handleGetDatahandleGetDatahandleGetDatahandleGetData', res);

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

    myChart = echarts.init(chartDom);

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: function (params: any) {
                return `
                <div style="font-weight:bold">${params[0].name}</div>
                <div>车辆占比: ${params[0].value}%</div>
                <div>停留时间: ${params[1].value}分钟</div>
            `;
            }
        },
        legend: {
            data: ['车辆占比', '停留时间']
        },
        grid: {
            left: '5%',
            right: '5%',
            bottom: '5%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: res.category,
            axisLabel: {
                interval: 0,
                width: 60,
                overflow: 'truncate'
            }
        },
        yAxis: [
            { // 左侧Y轴（车辆占比）
                type: 'value',
                name: '车辆占比(%)',
                min: 0,
                max: 100,
                axisLine: { show: true },
                splitLine: { show: false }
            },
            { // 右侧Y轴（停留时间）
                type: 'value',
                name: '停留时间(分钟)',
                axisLine: { show: true },
                splitLine: { show: false },
                position: 'right'
            }
        ],
        series: [
            { // 柱状图（车辆占比）
                name: '车辆占比',
                type: 'bar',
                data: res.realData,
                yAxisIndex: 0, // 使用右侧Y轴
                barWidth: 5,
                itemStyle: {
                    borderRadius: [4, 4, 0, 0],
                    color: '#0094FF'
                }
            },
            { // 折线图（停留时间）
                name: '停留时间',
                type: 'bar',
                yAxisIndex: 1, // 使用右侧Y轴
                data: res.seriesData,
                barWidth: 5,
                itemStyle: {
                    borderRadius: [4, 4, 0, 0],
                    color: '#00FFB7',
                }
            }
        ]
    };


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

const handleGetData = async () => {
    const req: any = {
        ContainWhole: true,
        StatisticsDate: moment().subtract(1, 'd').format('YYYY-MM-DD'),
        Serverpart_ID: props.currentService?.SERVERPART_ID || "",
    }

    const data = await handleGetBayonetSTAList(req)
    console.log('daskdhjfhsidugfajskdfhsjalkfhsduifhsdi', data);


    let category: string[] = []
    let seriesData: number[] = []
    let realData: number[] = []

    let obj: any = data[0]
    category = obj.Vehicle_Type
    if (obj.StayTimesList && obj.StayTimesList.length > 0) {
        obj.StayTimesList.forEach((item: any) => {
            seriesData.push(Number(item.value))
        })
    }
    if (obj.VehicleCountList && obj.VehicleCountList.length > 0) {
        let sum: number = 0
        obj.VehicleCountList.forEach((item: any) => {
            sum += Number(item.value)
        })

        obj.VehicleCountList.forEach((item: any) => {
            realData.push(Number((Number(item.value) / sum * 100).toFixed(2)))
        })

    }


    return {
        category: category,
        seriesData: seriesData,
        realData: realData,
    }
}

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

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

</script>

<template>
    <div class="VehicleStayAnalysisBox">
        <SmallTitle title="车型停留分析/日均" />

        <div class="VehicleStayAnalysisContent">
            <div class="VehicleStayAnalysisCharts" id="VehicleStayAnalysisCharts"></div>
        </div>
    </div>
</template>