<script setup lang="ts">
import './ThisMonthBenefits.less'
import bussinessIcon from '../../../../assets/image/bussinessIcon.png'
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { handleGetWelFareSummary } from '../../service';
import SmallTitle from '../smallTitle/smallTitle.vue';
import moment from 'moment';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
    GridComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GraphicComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import businessFormatCenterIcon from '../../../../assets/image/businessFormatCenterIcon.png'


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

let myChart: echarts.ECharts;

// 自定义颜色列表
const colorList = ['#FF9500', '#00FFB7', '#0094FF', '#7D4CD2', '#69BCFF'];

// 拿到的实际数据
let allRealData = ref<any>()

onMounted(async () => {
    const res: any = await handleGetData()

    const chartDom = document.getElementById('CoreCategory');
    if (!chartDom) return;
    const rect = chartDom.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;

    // 计算center位置（20%，50%）对应的实际像素
    const centerX = width * 0.2;
    const centerY = height * 0.5;

    myChart = echarts.init(chartDom);

    const option = {
        tooltip: {  // 新增 tooltip 配置
            trigger: 'item',  // 触发类型：坐标轴触发
            axisPointer: {    // 坐标轴指示器配置
                type: 'shadow' // 阴影指示器（适合柱状图）
            },
            formatter: function (params: any) {  // 自定义提示框内容
                return `
                <div style="font-weight:bold">${params.data.name} ${params?.percent}%</div>
            `;
            }
        },
        legend: {  // 新增图例配置
            show: true,  // 显示图例
            orient: 'vertical',  // 垂直排列
            left: '40%',  // 距离左侧的距离
            top: 0,  // 顶部对齐
            // type: 'scroll',
            textStyle: {  // 图例文字样式
                color: '#fff',  // 文字颜色设为白色
                fontSize: 12  // 可自定义字体大小
            },
            formatter: function (name: string) {  // 自定义图例文本
                // 从 res.seriesData 中找到对应的数据项
                const dataItem = res.seriesData.find((item: any) => item.name === name);
                // 返回自定义格式的文本，例如："名称 (值)"
                return `${name} (${dataItem?.percent || 0}%)`;
                // 或者使用其他自定义格式，比如：
                // return `${name}: ${res.realData[res.seriesData.findIndex(item => item.name === name)]}`;
            }
        },
        graphic: {  // 关键配置：在图表中心添加图片
            elements: [
                {
                    type: 'image',
                    style: {
                        image: businessFormatCenterIcon,
                        width: 83,
                        height: 83
                    },
                    left: centerX - 41.5,
                    top: centerY - 41.5,
                    z: 10
                }
            ]
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['85%', '100%'],
                center: ['20%', '50%'],
                avoidLabelOverlap: false,
                // itemStyle: {
                //     color: function (params: any) {
                //         return colorList[params.dataIndex];
                //     }
                // },
                label: {
                    show: false
                },
                emphasis: false,
                labelLine: {
                    show: false
                },
                data: res.seriesData
            }
        ]
    };

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

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

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

const handleGetData = async () => {
    const req: any = {
        ProvinceCode: '530000',
        StatisticsMonth: moment().subtract(1, 'M').format('YYYYMM')
    }
    // const data = await handleGetWelFareSummary(req)

    let ThisMonthBenefits = sessionStorage.getItem('ThisMonthBenefits')
    let data: any = []
    if (ThisMonthBenefits) {
        data = JSON.parse(ThisMonthBenefits)
    } else {
        data = await handleGetWelFareSummary(req)
        sessionStorage.setItem("ThisMonthBenefits", JSON.stringify(data))
    }

    console.log('fjidsfhasjfasdfdsf', data);


    let seriesData: any = []
    let realData: any = []
    let category: any = []

    allRealData.value = data

    let list: any = data.WelFareGoodsTypeList.slice(0, 5)
    if (list && list.length > 0) {
        let sum: number = 0
        list.forEach((item: any) => {
            sum += item.GoodsCount
        })


        list.forEach((item: any) => {
            category.push(item.GoodsTypeName)
            seriesData.push({ name: item.GoodsTypeName, value: item.GoodsCount, percent: ((item.GoodsCount / sum) * 100).toFixed(2) })
        })
    }

    let res: any = {
        category: category,// x轴的内容
        seriesData: seriesData,// y轴的数据
        realData: realData// 真实数据
    }
    return res
}

</script>


<template>
    <div class="ThisMonthBenefitsBox">
        <div class="ThisMonthBenefitsContent">
            <div class="ThisMonthBenefitsContentLeft">
                <img class="thisMonthIcon" :src="bussinessIcon" />
                <div class="thisMonthTitle">本月福利金发放额度</div>
            </div>

            <div class="ThisMonthBenefitsContentRight">
                <span class="thisMonthValue">{{ allRealData?.value?.distributeAmount || '0' }}</span>
                <span class="thisMonthUnit">元</span>
            </div>
        </div>


        <div class="CoreCategoryBox">
            <SmallTitle title="核心品类占比" />

            <div class="CoreCategoryCharts">
                <div class="CoreCategory" id="CoreCategory"></div>
            </div>
        </div>
    </div>
</template>