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

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

let myChart: echarts.ECharts;
// 当前查询的时间
let searchTime = ref<string>()

onMounted(async () => {
    await handleGoMounted()
})

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

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

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

    console.log('fhdsuFHDSJFAHKD', res);


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

    myChart = echarts.init(chartDom);

    const option = {
        xAxis: {
            type: 'category',
            data: res.category,
            axisLabel: {
                interval: 0,  // 改为0表示显示所有刻度
                showMinLabel: true,
                showMaxLabel: true,
                color: '#fff', // x轴标签颜色
                fontSize: 12   // 可调整字体大小防止重叠
            },
            axisLine: {
                lineStyle: {
                    color: '#fff' // x轴线颜色
                }
            },
            axisTick: {
                alignWithLabel: true // 保证刻度线和标签对齐
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '营收金额(万元)',
                splitLine: {
                    show: false
                },
                nameTextStyle: {
                    color: '#fff',
                    padding: [0, 30, 0, 0]  // 调整单位位置
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#fff' // y轴线颜色
                    }
                },
                axisLabel: {
                    color: '#fff', // y轴标签颜色
                    formatter: '{value}' // 添加单位
                }
            }
        ],
        grid: {
            left: '10',    // 增加左侧空间
            right: '10',   // 增加右侧空间
            bottom: '10',
            top: '50',
            containLabel: true
        },
        series: [
            {
                name: `${res.currentYear}年营收`,
                data: res?.seriesData || [],
                type: 'bar',
                barWidth: 5,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0],
                    color: '#008CFF' // 直接指定颜色
                }
            },
            {
                name: `${res.lastYear}年营收`,
                data: res?.seriesDataLastYear || [],
                type: 'bar',
                barWidth: 5,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0],
                    color: '#69BCFF' // 直接指定颜色
                }
            }
        ],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow' // 阴影指示器（适合柱状图）
            },
            formatter: function (params: any) {
                let result = params[0].axisValue + '<br/>';
                params.forEach((item: any, index: number) => {
                    result += `${item.marker} ${item.seriesName}: ${index === 0 ? res?.realData[item.dataIndex] : res?.realDataLastYear[item.dataIndex]}元<br/>`;
                });
                return result;
            }
        },
        legend: {

            data: [`${res.currentYear}年营收`, `${res.lastYear}年营收`], // 使用动态名称
            textStyle: {
                color: '#fff', // 图例文字颜色
                fontSize: 12
            },
            right: '0',      // 距离右侧10px
            top: '0',       // 距离顶部10px
        },
        color: ['#008CFF', '#69BCFF'] // 只需要两个颜色对应两个系列
    };

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

}

// 拿到数据的方法
const handleGetData = async () => {
    let category: number[] = []
    let seriesData: number[] = []
    let realData: string[] = []
    let seriesDataLastYear: number[] = []
    let realDataLastYear: string[] = []


    const req: any = {
        StatisticsDate: moment().format('YYYY'),
        // ProvinceCode: '340000',
        ProvinceCode: '530000',
        StatisticsType: 4,
    }
    const data = await handleGetRevenueTrend(req)

    if (data && data.length > 0) {
        data.forEach((item: any) => {
            category.push(item.name)
            seriesData.push(Number((Number(item.value) / 10000).toFixed(2)))
            realData.push(Number(item.value).toLocaleString())
        })
    }

    const lastYearReq: any = {
        StatisticsDate: moment().subtract(1, 'y').format('YYYY'),
        // ProvinceCode: '340000',
        ProvinceCode: '530000',
        StatisticsType: 4,
    }
    const lastYearData = await handleGetRevenueTrend(lastYearReq)

    if (lastYearData && lastYearData.length > 0) {
        lastYearData.forEach((item: any) => {
            seriesDataLastYear.push(Number((Number(item.value) / 10000).toFixed(2)))
            realDataLastYear.push(Number(item.value).toLocaleString())
        })
    }

    console.log('datadatadatadatadatadatadata', data);
    console.log('lastYearDatalastYearDatalastYearDatalastYearDatalastYearData', lastYearData);


    let res: any = {
        category: category,// x轴的内容
        seriesData: seriesData,// 今年的数据
        realData: realData,// 今年的实际数据
        seriesDataLastYear: seriesDataLastYear,// 去年的数据
        realDataLastYear: realDataLastYear,// 去年的实际数据
        currentYear: moment().format('YYYY'),
        lastYear: moment().subtract(1, 'y').format('YYYY')
    }
    return res
}


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

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


</script>

<template>
    <div class="VehicleModelStayBox">
        <!-- <SmallTitle :title="`车型停留分析/日均${searchTime ? `(${searchTime}月)` : ''}`"></SmallTitle> -->
        <SmallTitle :title="`经营效益趋势`"></SmallTitle>

        <div class="VehicleModelStayCharts" style="margin-top:15px">
            <div class="VehicleModelStay" id="VehicleModelStay"></div>
        </div>
    </div>
</template>