<script setup lang="ts">
import SmallTitle from '../smallTitle/smallTitle.vue'
import './RegionalRevenue.less'
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
    GridComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import moment from 'moment';
import { handleGetRevenueReport, handleGetSPBayonetList } from '../../service';

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

let myChart: echarts.ECharts;
// 自定义颜色列表
const colorList = ['#FF307C', '#FF9500', '#FFD900', '#00FFB7', '#0094FF', '#7D4CD2'];
let allServiceId: string = '1143,1144,1186,1188,1189,1190,1191,1192,1193,979,999,1023,1029,1030,1031,1033,1037,1041,1078,1087,1095,1137,1141,1147,1157,1159,1164,1165,1170,1174,981,985,987,994,1007,1009,1010,1012,1016,971,996,1002,1017,1018,1022,1027,1032,1073,1076,1099,1118,1122,1140,1142,1150,1171,970,969,978,1001,1005,1015,1050,1051,1052,1053,1064,1066,1096,1097,1101,1103,1104,1105,1106,1109,1112,1114,1115,1116,1117,991,995,1039,1080,1094,1100,1107,1123,1127,1133,1154,1155,1161,1163,1179,1180,1019,1021,1048,1049,1056,1059,1062,1063,1069,1093,1067,1228,1008,1070,1072,1166,1113,1148,1153,986,1086,1075,1182,1068,1226,1218,1088,1090,1058,1044,1084,1077,1089,1081,1091,1083,1162,1036,1092,988,993,1111,1158,1194,1202,1198,1207,1216,1221,1203,1206,1209,1215,1227,1201,1205,1208,1214,1217,1229,1212,1065,1085,1055,1071,982,1168,1185,1110,977,1169,973,974,1011,1151,1121,1046,1045,1172,1146,976,1187,1156,1181,1136,1138,1211,983,1195,1131,1176,1167,1223,997,1252,1225,1043,1129,992,1149,975,1382,989,1047,1197,1025,1199,1183,1222,1178,1003,1013,1224,1139,1125,1173,1135,1038,1177,1060,1175,1184,1035,1026,1028,1079,1119,1120,1489'

// 图例数据
let lengedList = ref<any>([])
// 选择的是日 还是 月 1 为 日 2为月
let selectDataType = ref<number>(1)
// 是否显示图表
let showCharts = ref<boolean>(true)

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()
    const chartDom = document.getElementById('RegionalRevenue');
    if (!chartDom) return;

    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}%  ${res.realData[params.dataIndex].toLocaleString()}元</div>
                `;
            }
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['0%', '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.pieData
            }
        ],
        legend: {
            orient: 'vertical',
            left: 160,
            top: 'center',
            align: 'left',
            itemGap: 10,
            itemWidth: 12,
            itemHeight: 12,
            textStyle: {
                color: '#fff',
                rich: {
                    name: {
                        width: 90,  // 固定名称宽度
                        align: 'left',
                        padding: [0, 10, 0, 0]
                    },
                    percent: {
                        width: 50,    // 固定百分比宽度
                        align: 'right',
                        padding: [0, 10, 0, 0]
                    }
                }
            },
            formatter: function (name: any) {
                let percentData: any = res.lengedData.filter((item: any) => item.name === name)

                return `{name|${name}}{percent|${percentData[0].value}%}`; // 使用rich样式
            }
        }
    };

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

}

// 拿到数据
const handleGetData = async () => {
    const req: any = {
        StartDate: "2025-04-01",
        EndDate: "2025-04-30",
        DataType: selectDataType.value,
        ServerpartIds: props.currentService?.SERVERPART_ID || allServiceId,
        DataSourceType: 1,
    }
    const data = await handleGetRevenueReport(req)

    showCharts.value = true

    let category: string[] = []
    let seriesData: number[] = []
    let realData: number[] = []
    let pieData: any[] = []

    // 图例数据
    let lengedData: any = []

    if (data && data.length > 0) {
        data.forEach((item: any) => {
            if (item.children && item.children.length > 0) {

                let sum: number = 0
                item.children.forEach((subItem: any) => {
                    sum += subItem.TotalRevenue.Revenue_Amount
                })


                item.children.forEach((subItem: any) => {
                    category.push(subItem.Serverpart_Name)
                    seriesData.push(Number((subItem.TotalRevenue.Revenue_Amount / 10000).toFixed(2)))
                    realData.push(subItem.TotalRevenue.Revenue_Amount)
                    pieData.push({ value: Number((subItem.TotalRevenue.Revenue_Amount / 10000).toFixed(2)), name: subItem.Serverpart_Name })
                    // lengedData.push({ name: subItem.Serverpart_Name, value: subItem.TotalRevenue.Revenue_Amount.toLocaleString() }) 
                    lengedData.push({ name: subItem.Serverpart_Name, value: Number(((subItem.TotalRevenue.Revenue_Amount / sum) * 100).toFixed(2)) })

                })
            }

        })
    }

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

// 改变类型
const handleChangeDataType = async (value: number) => {
    showCharts.value = false
    selectDataType.value = value
    await handleGoMounted()
}


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

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

</script>




<template>
    <div class="RegionalRevenueBox">
        <SmallTitle :title="'区域营收占比'">
            <!-- <template #extra>
                <div class="RegionalRevenueSelect">
                    <div :class="selectDataType === 1 ? 'RegionalRevenueItem RegionalRevenueItemLeft selectRegionalRevenueItem' : 'RegionalRevenueItem RegionalRevenueItemLeft'"
                        @click="handleChangeDataType(1)">
                        日</div>
                    <div :class="selectDataType === 2 ? 'RegionalRevenueItem RegionalRevenueItemRight selectRegionalRevenueItem' : 'RegionalRevenueItem RegionalRevenueItemRight'"
                        @click="handleChangeDataType(2)">
                        月</div>

                </div>
            </template> -->
        </SmallTitle>

        <div class="RegionalRevenueCharts">
            <!-- <div class="RegionalRevenueUnit">万元</div> -->
            <div class="RegionalRevenueChartsContent">
                <div class="RegionalRevenue" id="RegionalRevenue" v-if="showCharts"></div>

                <!-- <template v-if="showCharts">
                    <div class="RegionalRevenueDataBoxList" v-if="lengedList && lengedList.length > 0">
                        <div class="RegionalRevenueDataBox" v-for="(item, index) in lengedList" :key="index">
                            <div class="RegionalRevenueDataLeftBox">
                                <div class="RegionalRevenueItem">
                                    <div class="RegionalRevenueItemLeged" :style="{ background: colorList[index] }">
                                    </div>
                                    <div class="RegionalRevenueItemLabel">{{ item.name }}</div>
                                    <div class="RegionalRevenueItemValue">{{ item.value }}</div>
                                    <div class="RegionalRevenueItemUnit">元</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template> -->

            </div>
        </div>
    </div>
</template>