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

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

let myChart: echarts.ECharts;
// 自定义颜色列表
const colorList = ['#A8DBFF', '#5DBBFF', '#0094FF', '#005CE5'];
// 图例
const categoryList: any = ["25以下", "25-35", "35-45", "45以上"]

onMounted(async () => {

    const res: any = await handleGetData()

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


    myChart = echarts.init(chartDom);

    const option = {
        tooltip: {  // 新增 tooltip 配置
            trigger: 'item',  // 触发类型：坐标轴触发
            confine: true,  // 将 tooltip 限制在图表区域内
            // axisPointer: {    // 坐标轴指示器配置
            //     type: 'shadow' // 阴影指示器（适合柱状图）
            // },
            formatter: function (params: any) {  // 自定义提示框内容
                console.log('params', params);

                return `<div>
                    <div>男性：${res.seriesDataMan[params.dataIndex]}%</div>
                    <div>女性：${res.seriesDataWoman[params.dataIndex]}%</div>
                </div>`
                // return `
                //     <div style="font-weight:bold">${params.data.name} ${params?.percent}%  ${res.realData[params.dataIndex].toLocaleString()}元</div>
                // `;
            }
        },
        xAxis: {
            type: 'category',
            data: res.category,
            axisLabel: {
                interval: 0, // 强制显示所有标签
                hideOverlap: false, // 禁止自动隐藏重叠标签
            },
            axisTick: {
                alignWithLabel: true // 保证刻度线与标签对齐
            }
        },
        yAxis: {
            type: 'value',
            name: '%',
            splitLine: { show: false },
            axisLine: {
                show: true,
            },
            splitNumber: 4
        },
        grid: {
            left: '10',    // 增加左侧空间
            right: '10',   // 增加右侧空间
            bottom: '30',
            top: '30',
            containLabel: true
        },
        series: [
            {
                // data: [120, 200, 150, 80, 70, 110, 130],
                data: res.seriesDataMan,
                name: '男性',
                // realData: res.realData,
                type: 'bar',
                barWidth: '6',
                showBackground: true,
                backgroundStyle: {
                    borderRadius: [4, 4, 0, 0],
                    // color: 'rgba(23, 42, 70, 1)'
                    color: 'rgba(0, 148, 255, 0.1)'
                },
                itemStyle: {
                    borderRadius: [4, 4, 0, 0],
                    color: '#0094FF'
                    // 动态返回渐变颜色
                    // color: function (params: any) {
                    //     return new echarts.graphic.LinearGradient(
                    //         0, 0, 0, 1, // 渐变方向（垂直）
                    //         [
                    //             { offset: 0, color: '#008CFF' }, // 渐变起始色
                    //             { offset: 1, color: '#00F6FF' }  // 渐变结束色
                    //         ]
                    //     );
                    // }
                }
            },
            {
                // data: [120, 200, 150, 80, 70, 110, 130],
                data: res.seriesDataWoman,
                name: '女性',
                // realData: res.realData,
                type: 'bar',
                barWidth: '6',
                showBackground: true,
                backgroundStyle: {
                    borderRadius: [4, 4, 0, 0],
                    // color: 'rgba(23, 42, 70, 1)'
                    color: 'rgba(0, 148, 255, 0.1)'
                },
                itemStyle: {
                    borderRadius: [4, 4, 0, 0],
                    color: '#FF5E5E'
                    // 动态返回渐变颜色
                    // color: function (params: any) {
                    //     return new echarts.graphic.LinearGradient(
                    //         0, 0, 0, 1, // 渐变方向（垂直）
                    //         [
                    //             { offset: 0, color: '#008CFF' }, // 渐变起始色
                    //             { offset: 1, color: '#00F6FF' }  // 渐变结束色
                    //         ]
                    //     );
                    // }
                }
            },

        ],
        legend: {
            data: ['男性', '女性'], // 与series中的name对应
            bottom: 0, // 距离底部10px
            left: 'center', // 水平居中
            itemWidth: 12, // 图例标记宽度
            itemHeight: 12, // 图例标记高度
            itemGap: 20, // 图例项间距
            textStyle: {
                color: '#fff' // 图例文字颜色
            }
        },
    };


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

// 拿到年龄数据
const handleGetData = async () => {
    let category: any = []
    let seriesData: any = []
    let percentData: any = []

    const req: any = {
        provinceCode: '530000',
        statisticsMonth: moment(moment().subtract(1, 'M')).format('YYYYMM'),
    }
    const data = await handleGetCustomerAgeRatio(req)

    console.log('fdisfsauifhdsaj', data);

    // for (let i = 0; i < 4; i++) {
    //     let sum: number = (data[0].data[i] + data[1].data[i])
    //     seriesData.push(sum.toFixed(2))
    //     percentData.push((sum / 200 * 100).toFixed(2))
    // }

    // 男生
    let seriesDataMan: number[] = []
    // 女生
    let seriesDataWoman: number[] = []
    if (data && data.length > 0) {
        data.forEach((item: any) => {
            if (item.name === '男性') {
                seriesDataMan = item.data
            } else if (item.name === '女性') {
                seriesDataWoman = item.data
            }
        })
    }


    let res: any = {
        category: ["25以下", "25-35", "35-45", "45以上"],// x轴的内容
        seriesDataMan: seriesDataMan,// 男生
        seriesDataWoman: seriesDataWoman// 女生
    }

    return res
}


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

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

</script>

<template>
    <div class="CustomerAgeGroupBox">
        <SmallTitle :title="'年龄'" :pageType="'center'"></SmallTitle>

        <div class="CustomerAgeGroupCharts">
            <!-- <div class="CustomerAgeGroupUnit">万人</div> -->
            <div class="CustomerAgeGroup" id="CustomerAgeGroup"></div>

            <!-- <div class="legendBox">
                <div class="legendItem" v-for="(item, index) in categoryList" :key="index"
                    :style="{ marginBottom: index <= 1 ? '6px' : '' }">
                    <div class="legendIcon" :style="{ background: colorList[index] }"></div>
                    <div class="legendLabel">{{ item }}</div>
                </div>
            </div> -->
        </div>
    </div>
</template>