<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: {
                    width: 60,
                    color: '#fff', // y轴标签颜色
                    formatter: '{value}' // 添加单位
                }
            }
        ],
        grid: {
            left: '0',    // 增加左侧空间
            right: '0',   // 增加右侧空间
            bottom: '0',
            top: '50',
            containLabel: true
        },
        series: [
            {
                name: `${res.currentYear}年营收`,
                data: res?.seriesData || [],
                type: 'bar',
                barWidth: 5,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0],
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#46B8F3' },   // 顶部颜色
                        { offset: 1, color: '#1A4AF6' }    // 底部颜色
                    ])
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: function (params: any) {
                        // 自定义显示内容
                        return res.addList && res.addList[params.dataIndex] ? `${res.addList[params.dataIndex]}%` : '';
                    },
                    color: '#fff',  // 文字颜色
                    fontSize: 10     // 文字大小
                }
            },
            {
                name: `${res.lastYear}年营收`,
                data: res?.seriesDataLastYear || [],
                type: 'bar',
                barWidth: 5,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0],
                    color: '#3CD495' // 直接指定颜色
                }
            }
        ],
        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].toLocaleString() : res?.realDataLastYear[item.dataIndex].toLocaleString()}元<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: number[] = []
    let seriesDataLastYear: number[] = []
    let realDataLastYear: number[] = []


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

    let VehicleModelStay = sessionStorage.getItem('VehicleModelStay')
    let data: any = []

    let aiData: any = {}
    if (VehicleModelStay) {
        data = JSON.parse(VehicleModelStay)
    } else {
        data = await handleGetRevenueTrend(req)
        sessionStorage.setItem("VehicleModelStay", JSON.stringify(data))
    }


    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))

            aiData[`${item.name}`] = item.value + "元"
        })
    }

    let yesAiData: any = {}
    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))

            yesAiData[`${item.name}`] = item.value + "元"
        })
    }

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


    let addList: string[] = []
    if (category && category.length > 0) {
        for (let i = 0; i < category.length; i++) {
            let current: number = realData[i]
            let yes: number = realDataLastYear[i]
            let add: string = ""
            if (current > 0 && yes > 0) {
                add = (((current - yes) / yes) * 100).toFixed(2)
            }
            addList.push(add)
        }
    }

    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'),
        addList: addList
    }

    let VehicleModelStayAI = sessionStorage.getItem('VehicleModelStayAI')
    if (VehicleModelStayAI) { } else {
        let aiRes: any = {}
        aiRes[`${res.currentYear}年`] = aiData
        aiRes[`${res.lastYear}年`] = yesAiData
        sessionStorage.setItem("VehicleModelStayAI", JSON.stringify(aiRes))
    }



    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>