LqStatisticsService.cs 29 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqMdxx;
using NCC.Extend.Entitys.Dto.LqStatistics;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_yjmxb;
using NCC.Extend.Interfaces.LqStatistics;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;

namespace NCC.Extend.LqStatistics
{
    /// <summary>
    /// 绿纤统计服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "绿纤统计服务", Name = "LqStatistics", Order = 200, Groups = new[] { "Default" })]
    [Route("api/Extend/[controller]")]
    public class LqStatisticsService : ILqStatisticsService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<LqMdxxEntity> _lqMdxxRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly ILogger<LqStatisticsService> _logger;

        /// <summary>
        /// 初始化一个<see cref="LqStatisticsService"/>类型的新实例
        /// </summary>
        public LqStatisticsService(ISqlSugarRepository<LqMdxxEntity> lqMdxxRepository, IUserManager userManager, ILogger<LqStatisticsService> logger)
        {
            _lqMdxxRepository = lqMdxxRepository;
            _db = _lqMdxxRepository.Context;
            _userManager = userManager;
            _logger = logger;
        }

        #region 获取门店业绩统计列表
        /// <summary>
        /// 获取门店业绩统计列表
        /// </summary>
        /// <returns>门店业绩统计列表</returns>
        [HttpGet]
        public async Task<List<StorePerformanceOutput>> GetStorePerformanceList()
        {
            try
            {
                _logger.LogInformation("开始查询门店业绩统计列表");

                var storeList = await _lqMdxxRepository
                    .AsQueryable()
                    .Where(x => x.Status == 1)
                    .Select(x => new StorePerformanceOutput
                    {
                        StoreId = x.Id,
                        StoreName = x.Dm,
                        StoreCode = x.Mdbm,
                        BusinessUnitId = x.Syb,
                        BusinessUnitName = x.Syb,
                        TargetPerformance = x.Xsyj ?? 0,
                        ActualPerformance = 0,
                        CompletionRate = 0,
                    })
                    .ToListAsync();

                _logger.LogInformation("门店业绩统计列表查询完成,返回{Count}条记录", storeList.Count);

                return storeList;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询门店业绩统计列表时发生错误");
                throw NCCException.Oh("查询门店业绩统计列表失败", ex);
            }
        }
        #endregion

        #region 获取门店统计信息
        /// <summary>
        /// 获取门店统计信息
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>门店统计结果</returns>
        [HttpPost("StoreStatistics")]
        public async Task<StoreStatisticsOutput> GetStoreStatistics(StoreStatisticsInput input)
        {
            try
            {
                _logger.LogInformation("开始查询门店统计信息,查询日期:{StartDate} - {EndDate},门店ID:{StoreId}", input.StartDate, input.EndDate, input.StoreId);

                // 构建查询参数
                var parameters = new Dictionary<string, object> { { "@startDate", input.StartDate.ToString("yyyy-MM-dd 00:00:00") }, { "@endDate", input.EndDate.ToString("yyyy-MM-dd 23:59:59") } };

                // 构建WHERE条件
                var whereClause = "WHERE (order_date >= @startDate AND order_date <= @endDate OR order_date IS NULL)";

                if (!string.IsNullOrEmpty(input.StoreId))
                {
                    whereClause += " AND store_id = @storeId";
                    parameters.Add("@storeId", input.StoreId);
                }

                // 构建SQL查询
                var sql =
                    $@"
                    SELECT 
                        store_id AS StoreId,
                        store_name AS StoreName,
                        store_code AS StoreCode,
                        business_unit_id AS BusinessUnitId,
                        business_unit_name AS BusinessUnitName,
                        target_performance AS TargetPerformance,
                        SUM(COALESCE(actual_amount, 0)) AS ActualPerformance,
                        COUNT(order_id) AS OrderCount,
                        CASE 
                            WHEN target_performance > 0 
                            THEN ROUND((SUM(COALESCE(actual_amount, 0)) / target_performance) * 100, 2) 
                            ELSE 0 
                        END AS CompletionRate
                    FROM v_store_daily_consume_stats
                    {whereClause}
                    GROUP BY 
                        store_id, 
                        store_name, 
                        store_code, 
                        business_unit_id, 
                        business_unit_name, 
                        target_performance
                    ORDER BY ActualPerformance DESC";

                _logger.LogInformation("执行SQL查询:{Sql}", sql);
                _logger.LogInformation("查询参数:{Parameters}", string.Join(", ", parameters.Select(p => $"{p.Key}={p.Value}")));

                var results = await _db.Ado.SqlQueryAsync<dynamic>(sql, parameters);

                _logger.LogInformation("查询到门店统计数据数量:{Count}", results.Count);

                // 转换为输出格式
                var storeList = results
                    .Select(r => new StoreStatisticsInfo
                    {
                        StoreId = r.StoreId?.ToString() ?? "",
                        StoreName = r.StoreName?.ToString() ?? "",
                        StoreCode = r.StoreCode?.ToString() ?? "",
                        BusinessUnitId = r.BusinessUnitId?.ToString() ?? "",
                        BusinessUnitName = r.BusinessUnitName?.ToString() ?? "",
                        TargetPerformance = Convert.ToDecimal(r.TargetPerformance ?? 0),
                        ActualPerformance = Convert.ToDecimal(r.ActualPerformance ?? 0),
                        OrderCount = Convert.ToInt32(r.OrderCount ?? 0),
                        CompletionRate = Convert.ToDecimal(r.CompletionRate ?? 0),
                    })
                    .ToList();

                _logger.LogInformation("门店统计信息查询完成,返回{Count}条记录", storeList.Count);

                return new StoreStatisticsOutput { StoreList = storeList, TotalCount = storeList.Count };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询门店统计信息时发生错误,查询日期:{StartDate} - {EndDate},门店ID:{StoreId}", input.StartDate, input.EndDate, input.StoreId);
                throw NCCException.Oh("查询门店统计信息失败", ex);
            }
        }
        #endregion

        #region 获取事业部业绩统计
        /// <summary>
        /// 获取事业部业绩统计
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>事业部业绩统计结果</returns>
        [HttpPost("BusinessUnitStatistics")]
        public async Task<BusinessUnitStatisticsOutput> GetBusinessUnitStatistics(BusinessUnitStatisticsInput input)
        {
            try
            {
                _logger.LogInformation("开始查询事业部业绩统计,查询日期:{StartDate} - {EndDate},事业部ID:{BusinessUnitId}", input.StartDate, input.EndDate, input.BusinessUnitId);

                // 构建查询参数
                var parameters = new Dictionary<string, object> { { "@startDate", input.StartDate.ToString("yyyy-MM-dd 00:00:00") }, { "@endDate", input.EndDate.ToString("yyyy-MM-dd 23:59:59") } };

                // 构建WHERE条件
                var whereClause = "WHERE (order_date >= @startDate AND order_date <= @endDate OR order_date IS NULL)";

                if (!string.IsNullOrEmpty(input.BusinessUnitId))
                {
                    whereClause += " AND department_id = @businessUnitId";
                    parameters.Add("@businessUnitId", input.BusinessUnitId);
                }

                // 构建SQL查询
                var sql =
                    $@"
                    SELECT 
                        department_id AS DepartmentId,
                        department_name AS DepartmentName,
                        parent_id AS ParentId,
                        parent_name AS ParentName,
                        SUM(COALESCE(target_amount, 0)) AS TotalTargetAmount,
                        SUM(COALESCE(actual_amount, 0)) AS TotalActualAmount,
                        COUNT(order_id) AS TotalOrderCount,
                        CASE 
                            WHEN SUM(COALESCE(target_amount, 0)) > 0 
                            THEN ROUND((SUM(COALESCE(actual_amount, 0)) / SUM(COALESCE(target_amount, 0))) * 100, 2) 
                            ELSE 0 
                        END AS CompletionRate
                    FROM v_department_performance_flow
                    {whereClause}
                    GROUP BY 
                        department_id, 
                        department_name, 
                        parent_id, 
                        parent_name
                    ORDER BY TotalActualAmount DESC";

                _logger.LogInformation("执行SQL查询:{Sql}", sql);
                _logger.LogInformation("查询参数:{Parameters}", string.Join(", ", parameters.Select(p => $"{p.Key}={p.Value}")));

                var results = await _db.Ado.SqlQueryAsync<dynamic>(sql, parameters);

                _logger.LogInformation("查询到事业部业绩数据数量:{Count}", results.Count);

                // 转换为输出格式
                var businessUnitList = results
                    .Select(r => new BusinessUnitStatisticsInfo
                    {
                        DepartmentId = r.DepartmentId?.ToString() ?? "",
                        DepartmentName = r.DepartmentName?.ToString() ?? "",
                        ParentId = r.ParentId?.ToString() ?? "",
                        ParentName = r.ParentName?.ToString() ?? "",
                        TotalTargetAmount = Convert.ToDecimal(r.TotalTargetAmount ?? 0),
                        TotalActualAmount = Convert.ToDecimal(r.TotalActualAmount ?? 0),
                        TotalOrderCount = Convert.ToInt32(r.TotalOrderCount ?? 0),
                        CompletionRate = Convert.ToDecimal(r.CompletionRate ?? 0),
                    })
                    .ToList();

                _logger.LogInformation("事业部业绩统计查询完成,返回{Count}条记录", businessUnitList.Count);

                return new BusinessUnitStatisticsOutput { BusinessUnitList = businessUnitList, TotalCount = businessUnitList.Count };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询事业部业绩统计时发生错误,查询日期:{StartDate} - {EndDate},事业部ID:{BusinessUnitId}", input.StartDate, input.EndDate, input.BusinessUnitId);
                throw NCCException.Oh("查询事业部业绩统计失败", ex);
            }
        }
        #endregion

        #region 获取其他部门业绩统计
        /// <summary>
        /// 获取其他部门业绩统计
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>其他部门业绩统计结果</returns>
        [HttpPost("OtherDepartmentStatistics")]
        public async Task<OtherDepartmentStatisticsOutput> GetOtherDepartmentStatistics(OtherDepartmentStatisticsInput input)
        {
            try
            {
                _logger.LogInformation("开始查询其他部门业绩统计,查询日期:{StartDate} - {EndDate},部门ID:{DepartmentId}", input.StartDate, input.EndDate, input.DepartmentId);

                // 构建查询参数
                var parameters = new Dictionary<string, object> { { "@startDate", input.StartDate.ToString("yyyy-MM-dd 00:00:00") }, { "@endDate", input.EndDate.ToString("yyyy-MM-dd 23:59:59") } };

                // 构建WHERE条件
                var whereClause = "WHERE (order_date >= @startDate AND order_date <= @endDate OR order_date IS NULL)";

                if (!string.IsNullOrEmpty(input.DepartmentId))
                {
                    whereClause += " AND department_id = @departmentId";
                    parameters.Add("@departmentId", input.DepartmentId);
                }

                // 构建SQL查询
                var sql =
                    $@"
                    SELECT 
                        department_id AS DepartmentId,
                        department_name AS DepartmentName,
                        parent_id AS ParentId,
                        parent_name AS ParentName,
                        SUM(COALESCE(target_amount, 0)) AS TotalTargetAmount,
                        SUM(COALESCE(actual_amount, 0)) AS TotalActualAmount,
                        COUNT(order_id) AS TotalOrderCount,
                        CASE 
                            WHEN SUM(COALESCE(target_amount, 0)) > 0 
                            THEN ROUND((SUM(COALESCE(actual_amount, 0)) / SUM(COALESCE(target_amount, 0))) * 100, 2) 
                            ELSE 0 
                        END AS CompletionRate
                    FROM v_other_department_performance_flow
                    {whereClause}
                    GROUP BY 
                        department_id, 
                        department_name, 
                        parent_id, 
                        parent_name
                    ORDER BY TotalActualAmount DESC";

                _logger.LogInformation("执行SQL查询:{Sql}", sql);
                _logger.LogInformation("查询参数:{Parameters}", string.Join(", ", parameters.Select(p => $"{p.Key}={p.Value}")));

                var results = await _db.Ado.SqlQueryAsync<dynamic>(sql, parameters);

                _logger.LogInformation("查询到其他部门业绩数据数量:{Count}", results.Count);

                // 转换为输出格式
                var departmentList = results
                    .Select(r => new OtherDepartmentStatisticsInfo
                    {
                        DepartmentId = r.DepartmentId?.ToString() ?? "",
                        DepartmentName = r.DepartmentName?.ToString() ?? "",
                        ParentId = r.ParentId?.ToString() ?? "",
                        ParentName = r.ParentName?.ToString() ?? "",
                        TotalTargetAmount = Convert.ToDecimal(r.TotalTargetAmount ?? 0),
                        TotalActualAmount = Convert.ToDecimal(r.TotalActualAmount ?? 0),
                        TotalOrderCount = Convert.ToInt32(r.TotalOrderCount ?? 0),
                        CompletionRate = Convert.ToDecimal(r.CompletionRate ?? 0),
                    })
                    .ToList();

                _logger.LogInformation("其他部门业绩统计查询完成,返回{Count}条记录", departmentList.Count);

                return new OtherDepartmentStatisticsOutput { DepartmentList = departmentList, TotalCount = departmentList.Count };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询其他部门业绩统计时发生错误,查询日期:{StartDate} - {EndDate},部门ID:{DepartmentId}", input.StartDate, input.EndDate, input.DepartmentId);
                throw NCCException.Oh("查询其他部门业绩统计失败", ex);
            }
        }
        #endregion

        #region 获取经理业绩统计
        /// <summary>
        /// 获取经理业绩统计
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>经理业绩统计结果</returns>
        [HttpPost("ManagerStatistics")]
        public async Task<ManagerStatisticsOutput> GetManagerStatistics(ManagerStatisticsInput input)
        {
            try
            {
                _logger.LogInformation("开始查询经理业绩统计,查询日期:{StartDate} - {EndDate},事业部ID:{BusinessUnitId}", input.StartDate, input.EndDate, input.BusinessUnitId);

                // 构建查询参数
                var parameters = new Dictionary<string, object> { { "@startDate", input.StartDate.ToString("yyyy-MM-dd 00:00:00") }, { "@endDate", input.EndDate.ToString("yyyy-MM-dd 23:59:59") } };

                // 构建WHERE条件
                var whereClause = "WHERE (flow.order_date >= @startDate AND flow.order_date <= @endDate OR flow.order_date IS NULL)";

                if (!string.IsNullOrEmpty(input.BusinessUnitId))
                {
                    whereClause += " AND basic.business_unit_id = @businessUnitId";
                    parameters.Add("@businessUnitId", input.BusinessUnitId);
                }

                // 构建SQL查询 - 按经理和门店统计
                var sql =
                    $@"
                    SELECT 
                        basic.manager_user_id AS ManagerUserId,
                        basic.manager_name AS ManagerName,
                        basic.business_unit_id AS BusinessUnitId,
                        basic.business_unit_name AS BusinessUnitName,
                        basic.store_id AS StoreId,
                        basic.store_name AS StoreName,
                        COALESCE(smx.smx1, 0) AS TargetPerformance,
                        SUM(COALESCE(flow.actual_amount, 0)) AS ActualPerformance,
                        COUNT(flow.order_id) AS OrderCount,
                        CASE 
                            WHEN COALESCE(smx.smx1, 0) > 0 
                            THEN ROUND((SUM(COALESCE(flow.actual_amount, 0)) / COALESCE(smx.smx1, 0)) * 100, 2) 
                            ELSE 0 
                        END AS CompletionRate
                    FROM v_manager_store_basic basic
                    LEFT JOIN lq_zjl_mdsmxsz smx ON basic.store_id = smx.md_id AND basic.manager_user_id = smx.zjl_userid
                    LEFT JOIN v_department_performance_flow flow ON basic.store_id = flow.store_id
                    {whereClause}
                    GROUP BY 
                        basic.manager_user_id, 
                        basic.manager_name, 
                        basic.business_unit_id, 
                        basic.business_unit_name,
                        basic.store_id,
                        basic.store_name,
                        smx.smx1
                    ORDER BY ActualPerformance DESC";

                _logger.LogInformation("执行SQL查询:{Sql}", sql);
                _logger.LogInformation("查询参数:{Parameters}", string.Join(", ", parameters.Select(p => $"{p.Key}={p.Value}")));

                var results = await _db.Ado.SqlQueryAsync<dynamic>(sql, parameters);

                _logger.LogInformation("查询到经理业绩数据数量:{Count}", results.Count);

                // 转换为输出格式
                var managerList = results
                    .Select(r => new ManagerStatisticsInfo
                    {
                        ManagerName = r.ManagerName?.ToString() ?? "",
                        ManagerUserId = r.ManagerUserId?.ToString() ?? "",
                        BusinessUnitName = r.BusinessUnitName?.ToString() ?? "",
                        BusinessUnitId = r.BusinessUnitId?.ToString() ?? "",
                        StoreName = r.StoreName?.ToString() ?? "",
                        StoreId = r.StoreId?.ToString() ?? "",
                        TargetPerformance = Convert.ToDecimal(r.TargetPerformance ?? 0),
                        ActualPerformance = Convert.ToDecimal(r.ActualPerformance ?? 0),
                        OrderCount = Convert.ToInt32(r.OrderCount ?? 0),
                        CompletionRate = Convert.ToDecimal(r.CompletionRate ?? 0),
                    })
                    .ToList();

                _logger.LogInformation("经理业绩统计查询完成,返回{Count}条记录", managerList.Count);

                return new ManagerStatisticsOutput { ManagerList = managerList, TotalCount = managerList.Count };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询经理业绩统计时发生错误,查询日期:{StartDate} - {EndDate},事业部ID:{BusinessUnitId}", input.StartDate, input.EndDate, input.BusinessUnitId);
                throw NCCException.Oh("查询经理业绩统计失败", ex);
            }
        }
        #endregion

        #region 获取经理业绩汇总统计
        /// <summary>
        /// 获取经理业绩汇总统计
        /// </summary>
        /// <remarks>
        /// 统计每个经理的目标业绩总和、完成业绩总和、完成率等汇总信息
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "startDate": "2025-01-01T00:00:00",
        ///   "endDate": "2025-01-31T23:59:59",
        ///   "businessUnitId": "事业部ID(可选)"
        /// }
        /// ```
        ///
        /// 参数说明:
        /// - startDate: 开始日期,格式:yyyy-MM-ddTHH:mm:ss
        /// - endDate: 结束日期,格式:yyyy-MM-ddTHH:mm:ss
        /// - businessUnitId: 事业部ID,可选参数,不传则查询所有事业部
        ///
        /// 返回数据说明:
        /// - ManagerName: 经理姓名
        /// - ManagerUserId: 经理用户ID
        /// - BusinessUnitName: 事业部名称
        /// - BusinessUnitId: 事业部ID
        /// - StoreCount: 管理门店数量
        /// - TotalTargetPerformance: 目标业绩总和
        /// - TotalActualPerformance: 完成业绩总和
        /// - CompletionRate: 完成率(%)
        /// - TotalOrderCount: 开单总数量
        /// </remarks>
        /// <param name="input">查询参数</param>
        /// <returns>经理业绩汇总统计结果</returns>
        /// <response code="200">成功返回经理业绩汇总统计数据</response>
        /// <response code="400">请求参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("ManagerSummaryStatistics")]
        public async Task<ManagerSummaryStatisticsOutput> GetManagerSummaryStatistics(ManagerStatisticsInput input)
        {
            try
            {
                _logger.LogInformation("开始查询经理业绩汇总统计,查询日期:{StartDate} - {EndDate},事业部ID:{BusinessUnitId}", input.StartDate, input.EndDate, input.BusinessUnitId);

                // 构建查询参数
                var parameters = new Dictionary<string, object> { { "@startDate", input.StartDate.ToString("yyyy-MM-dd 00:00:00") }, { "@endDate", input.EndDate.ToString("yyyy-MM-dd 23:59:59") } };

                // 构建WHERE条件
                var whereClause = "WHERE (flow.order_date >= @startDate AND flow.order_date <= @endDate OR flow.order_date IS NULL)";

                if (!string.IsNullOrEmpty(input.BusinessUnitId))
                {
                    whereClause += " AND basic.business_unit_id = @businessUnitId";
                    parameters.Add("@businessUnitId", input.BusinessUnitId);
                }

                // 构建SQL查询 - 按经理汇总统计
                var sql =
                    $@"
                    SELECT 
                        basic.manager_user_id AS ManagerUserId,
                        basic.manager_name AS ManagerName,
                        basic.business_unit_id AS BusinessUnitId,
                        basic.business_unit_name AS BusinessUnitName,
                        COUNT(DISTINCT basic.store_id) AS StoreCount,
                        SUM(COALESCE(smx.smx1, 0)) AS TotalTargetPerformance,
                        SUM(COALESCE(flow.actual_amount, 0)) AS TotalActualPerformance,
                        COUNT(flow.order_id) AS TotalOrderCount,
                        CASE 
                            WHEN SUM(COALESCE(smx.smx1, 0)) > 0 
                            THEN ROUND((SUM(COALESCE(flow.actual_amount, 0)) / SUM(COALESCE(smx.smx1, 0))) * 100, 2) 
                            ELSE 0 
                        END AS CompletionRate
                    FROM v_manager_store_basic basic
                    LEFT JOIN lq_zjl_mdsmxsz smx ON basic.store_id = smx.md_id AND basic.manager_user_id = smx.zjl_userid
                    LEFT JOIN v_department_performance_flow flow ON basic.store_id = flow.store_id
                    {whereClause}
                    GROUP BY 
                        basic.manager_user_id, 
                        basic.manager_name, 
                        basic.business_unit_id, 
                        basic.business_unit_name
                    ORDER BY TotalActualPerformance DESC";

                _logger.LogInformation("执行SQL查询:{Sql}", sql);
                _logger.LogInformation("查询参数:{Parameters}", string.Join(", ", parameters.Select(p => $"{p.Key}={p.Value}")));

                var results = await _db.Ado.SqlQueryAsync<dynamic>(sql, parameters);

                _logger.LogInformation("查询到经理业绩汇总数据数量:{Count}", results.Count);

                // 转换为输出格式
                var managerSummaryList = results
                    .Select(r => new ManagerSummaryStatisticsInfo
                    {
                        ManagerName = r.ManagerName?.ToString() ?? "",
                        ManagerUserId = r.ManagerUserId?.ToString() ?? "",
                        BusinessUnitName = r.BusinessUnitName?.ToString() ?? "",
                        BusinessUnitId = r.BusinessUnitId?.ToString() ?? "",
                        StoreCount = Convert.ToInt32(r.StoreCount ?? 0),
                        TotalTargetPerformance = Convert.ToDecimal(r.TotalTargetPerformance ?? 0),
                        TotalActualPerformance = Convert.ToDecimal(r.TotalActualPerformance ?? 0),
                        TotalOrderCount = Convert.ToInt32(r.TotalOrderCount ?? 0),
                        CompletionRate = Convert.ToDecimal(r.CompletionRate ?? 0),
                    })
                    .ToList();

                _logger.LogInformation("经理业绩汇总统计查询完成,返回{Count}条记录", managerSummaryList.Count);

                return new ManagerSummaryStatisticsOutput { ManagerSummaryList = managerSummaryList, TotalCount = managerSummaryList.Count };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询经理业绩汇总统计时发生错误,查询日期:{StartDate} - {EndDate},事业部ID:{BusinessUnitId}", input.StartDate, input.EndDate, input.BusinessUnitId);
                throw NCCException.Oh("查询经理业绩汇总统计失败", ex);
            }
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 递归获取子部门列表
        /// </summary>
        /// <param name="parentId">父部门ID</param>
        /// <returns>子部门列表</returns>
        private async Task<List<DepartmentInfo>> GetSubDepartmentsRecursively(string parentId)
        {
            var subDepartments = new List<DepartmentInfo>();

            try
            {
                // 查询直接子部门
                var directChildren = await _db.Queryable<OrganizeEntity>()
                    .Where(x => x.ParentId == parentId && x.EnabledMark == 1 && x.DeleteMark == null)
                    .Select(x => new DepartmentInfo
                    {
                        DepartmentId = x.Id,
                        DepartmentName = x.FullName,
                        ParentId = x.ParentId,
                    })
                    .ToListAsync();

                subDepartments.AddRange(directChildren);

                // 递归查询每个子部门的子部门
                foreach (var child in directChildren)
                {
                    var grandChildren = await GetSubDepartmentsRecursively(child.DepartmentId);
                    subDepartments.AddRange(grandChildren);
                }

                return subDepartments;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "递归获取子部门列表时发生错误,父部门ID:{ParentId}", parentId);
                return subDepartments;
            }
        }
        #endregion
    }

    /// <summary>
    /// 部门信息
    /// </summary>
    public class DepartmentInfo
    {
        /// <summary>
        /// 部门ID
        /// </summary>
        public string DepartmentId { get; set; }

        /// <summary>
        /// 部门名称
        /// </summary>
        public string DepartmentName { get; set; }

        /// <summary>
        /// 父部门ID
        /// </summary>
        public string ParentId { get; set; }
    }
}