<template>
    <view class="regional-revenue">
        <!-- 区域营收占比标题 -->
        <view class="section-header">
            <text class="section-title">区域营收占比</text>
        </view>

        <!-- 区域营收占比图表 -->
        <view class="chart-container">
            <!-- 图表加载效果 -->
            <ChartLoading v-if="isLoading" text="数据加载中..." />
            <!-- 实际图表 -->
            <QiunDataCharts v-else type="pie" :opts="chartOpts" :chartData="chartData" :canvas2d="true"
                :inScrollView="true" canvasId="regionalRevenueChart" :animation="false" :ontap="true" :ontouch="true"
                tooltipFormat="regionalRevenueChart" />
        </view>
    </view>
</template>

<script>
import QiunDataCharts from './qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
import ChartLoading from './ChartLoading.vue'
import request from "@/util/index.js";
import moment from 'moment'
import { wrapTreeNode } from "@/util/dateTime";

export default {
    components: {
        QiunDataCharts,
        ChartLoading
    },
    props: {
        selectTime: {
            type: String,
            default: ""
        },
    },
    data() {
        return {
            isLoading: false,
            // 所有服务区ID
            allServiceId: '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',

            // 图表原始数据
            rawData: {
                seriesData: [],
                legendData: []
            }
        }
    },

    computed: {
        // 检查是否有图表数据
        hasChartData() {
            return this.rawData.seriesData && this.rawData.seriesData.length > 0
        },

        // 图表数据
        chartData() {
            return {
                series: [{
                    data: this.rawData.seriesData
                }]
            }
        },

        // 图表配置
        chartOpts() {
            return {
                padding: [15, 15, 15, 15],
                dataLabel: false,
                legend: {
                    show: true,
                    position: 'right',
                    float: 'center',
                    fontSize: 12,
                    fontColor: '#333333',
                },
                extra: {
                    pie: {
                        activeRadius: 10,
                        offsetAngle: 0,
                        labelWidth: 0,
                        border: false,
                        borderWidth: 2,
                        borderColor: '#FFFFFF'
                    }
                },
                percentageList: this.rawData.legendData
            }
        }
    },

    watch: {
        selectTime: {
            handler(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.handleGetRegionalRevenueData()
                }
            },
            immediate: false
        }
    },

    onReady() {
        this.handleGetRegionalRevenueData()
    },

    methods: {
        // 获取区域营收占比数据
        async handleGetRegionalRevenueData() {
            this.isLoading = true

            let list = uni.getStorageSync('allServiceList');
            if (list && list.length > 0) {
            } else {
                const serviceReq = {
                    Province_Code: "530000"
                }
                const serviceList = await request.$apiGet(
                    "CommercialApi/BaseInfo/GetServerpartList",
                    serviceReq
                );
                list = serviceList.Result_Data.List
            }

            let allId = ''
            list.forEach((item) => {
                if (allId) {
                    allId += `,${item.SERVERPART_ID}`
                } else {
                    allId = item.SERVERPART_ID
                }
            })

            const req = {
                StartDate: this.selectTime ? moment(this.selectTime).startOf('M').format('YYYY-MM-DD') : moment().startOf('M').format('YYYY-MM-DD'),
                EndDate: this.selectTime ? moment(this.selectTime).endOf('M').format('YYYY-MM-DD') : moment().endOf('M').format('YYYY-MM-DD'),
                DataType: 1, // 默认按日统计
                ServerpartIds: allId, // 使用所有服务区ID
                DataSourceType: 1,
            }

            const data = await this.getRevenueReport(req);


            this.isLoading = false
            // 处理数据
            this.processChartData(wrapTreeNode(data.Result_Data.List))
        },

        // 发起API请求获取区域营收占比数据
        async getRevenueReport(params) {
            const data = await request.$webGet(
                "EShangApiMain/Revenue/GetRevenueReport",
                params
            );
            return data || []
        },

        // 处理图表数据
        processChartData(data) {
            let seriesData = []
            let legendData = []

            console.log('dadasdjifhdlsk', data);

            // 处理数据：获取区域营收占比数据
            if (data && data.length > 0) {
                data.forEach((regionItem) => {
                    if (regionItem.children && regionItem.children.length > 0) {
                        // 计算总和用于计算百分比
                        let sum = 0
                        regionItem.children.forEach((subItem) => {
                            sum += subItem.TotalRevenue.Revenue_Amount
                        })

                        // 处理每个服务区的数据
                        regionItem.children.forEach((subItem, index) => {
                            let revenueAmount = Number((subItem.TotalRevenue.Revenue_Amount / 10000).toFixed(2))
                            let percentage = Number(((subItem.TotalRevenue.Revenue_Amount / sum) * 100).toFixed(2))

                            seriesData.push({
                                name: subItem.Serverpart_Name.split('管理单元')[0],
                                value: revenueAmount
                            })

                            legendData.push({
                                name: subItem.Serverpart_Name.split('管理单元')[0],
                                value: percentage + '%'
                            })
                        })
                    }
                })
            }

            // 更新图表数据
            this.rawData = {
                seriesData: seriesData,
                legendData: legendData
            }

        },

    }
}
</script>

<style scoped lang="less">
@primary-color: #46B8F3;
@secondary-color: #3CD495;
@danger-color: #FF5E5E;
@success-color: #52C41A;
@text-primary: #333;
@text-secondary: #666;
@text-light: #999;
@bg-white: #ffffff;
@border-radius: 16rpx;
@shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

.regional-revenue {
    margin-top: 24rpx;

    .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        padding: 0 8rpx;

        .section-title {
            font-size: 30rpx;
            font-weight: 600;
            color: @text-primary;
        }
    }

    .chart-container {
        background: @bg-white;
        border-radius: @border-radius;
        padding: 24rpx;
        box-shadow: @shadow;
        margin-bottom: 24rpx;
        width: 100%;
        box-sizing: border-box;
        height: 400rpx;
    }
}
</style>