<script setup lang="ts">
import SmallTitle from '../smallTitle/smallTitle.vue'
import './AnalysisOfMember.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('AnalysisOfMember');
    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: `每周优品爆款`,
                data: res?.data || [],
                type: 'bar',
                barWidth: 10,
                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: `其他类型`,
                data: res?.otherData || [],
                type: 'bar',
                barWidth: 10,
                itemStyle: {
                    borderRadius: [3, 3, 0, 0],
                    color: "#3CD495"
                }
            }
        ],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow' // 阴影指示器（适合柱状图）
            },
            formatter: function (params: any) {
                console.log('params', params);
                let str: string = `<div>${params[0].name}</div>`
                params.forEach((item: any) => {
                    str += `<div>${item.seriesName}：${item.value}%</div>`
                })
                return str

                // 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: [`每周优品爆款`, `其他类型`], // 使用动态名称
            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[] = []


    let res: any = {
        category: ["购买数量", "交易金额", "订单笔数", "购买人数"],
        data: [50.99, 48.89, 82.95, 85.05],
        otherData: [49.01, 51.11, 17.05, 14.95]
    }

    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="AnalysisOfMember" id="AnalysisOfMember"></div>
        </div>
    </div>
</template>