LqBusinessUnitDashboardService.Features.cs 41 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 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NCC.Common.Core.Manager;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Common.Helper;
using NCC.Common.Model.NPOI;
using NCC.DataEncryption;
using NCC.Extend.Entitys.Dto.LqBusinessUnitDashboard;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_khxx;
using NCC.Extend.Entitys.lq_md_target;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_xh_feedback;
using NCC.Extend.Entitys.lq_xh_hyhk;
using NCC.Extend.Interfaces.BusinessOperationLog;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;

namespace NCC.Extend
{
    /// <summary>
    /// 事业部驾驶舱四项能力:三美占比、服务日志、重复充值
    /// </summary>
    public partial class LqBusinessUnitDashboardService
    {
        private const string CapabilityBizLogModule = "事业部看板";

        #region 三美占比

        /// <summary>
        /// 获取事业部驾驶舱三美净业绩占比
        /// </summary>
        /// <remarks>
        /// 口径:净业绩 = 开单品项实付 − 退卡;占比分母 = 生美+科美+医美合计(不含产品)。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "businessUnitId": "734725299018663173",
        ///   "statisticsMonth": "202607"
        /// }
        /// ```
        /// </remarks>
        /// <param name="input">公共筛选条件</param>
        /// <returns>三美净业绩及占比</returns>
        /// <response code="200">成功返回占比统计</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("GetCategoryShareStatistics")]
        public async Task<BusinessUnitDashboardCategoryShareOutput> GetCategoryShareStatistics(
            [FromBody] BusinessUnitDashboardStatisticsInput input)
        {
            ValidateCapabilityStatisticsInput(input);
            var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
            if (!storeIds.Any()) return new BusinessUnitDashboardCategoryShareOutput();

            var (billingLife, billingTech, billingMedical, billingProduct) =
                await CalculatePerformanceByCategory(storeIds, input.StatisticsMonth, false);
            var (refundLife, refundTech, refundMedical, refundProduct) =
                await CalculatePerformanceByCategory(storeIds, input.StatisticsMonth, true);

            var lifeNet = billingLife - refundLife;
            var techNet = billingTech - refundTech;
            var medicalNet = billingMedical - refundMedical;
            var productNet = billingProduct - refundProduct;
            var threeBeautyTotal = lifeNet + techNet + medicalNet;

            var result = new BusinessUnitDashboardCategoryShareOutput
            {
                LifeBeautyNetPerformance = lifeNet,
                TechBeautyNetPerformance = techNet,
                MedicalBeautyNetPerformance = medicalNet,
                ProductNetPerformance = productNet,
                ThreeBeautyTotal = threeBeautyTotal,
                LifeBeautyPercentage = threeBeautyTotal > 0
                    ? decimal.Round(lifeNet / threeBeautyTotal * 100m, 2) : 0m,
                TechBeautyPercentage = threeBeautyTotal > 0
                    ? decimal.Round(techNet / threeBeautyTotal * 100m, 2) : 0m,
                MedicalBeautyPercentage = threeBeautyTotal > 0
                    ? decimal.Round(medicalNet / threeBeautyTotal * 100m, 2) : 0m,
                ShareData = new List<BusinessUnitCategoryShareItem>
                {
                    new BusinessUnitCategoryShareItem
                    {
                        ItemCategory = "生美",
                        NetPerformance = lifeNet,
                        Percentage = threeBeautyTotal > 0
                            ? decimal.Round(lifeNet / threeBeautyTotal * 100m, 2) : 0m
                    },
                    new BusinessUnitCategoryShareItem
                    {
                        ItemCategory = "科美",
                        NetPerformance = techNet,
                        Percentage = threeBeautyTotal > 0
                            ? decimal.Round(techNet / threeBeautyTotal * 100m, 2) : 0m
                    },
                    new BusinessUnitCategoryShareItem
                    {
                        ItemCategory = "医美",
                        NetPerformance = medicalNet,
                        Percentage = threeBeautyTotal > 0
                            ? decimal.Round(medicalNet / threeBeautyTotal * 100m, 2) : 0m
                    }
                }
            };

            return result;
        }

        #endregion

        #region 服务日志

        /// <summary>
        /// 获取事业部驾驶舱服务日志统计
        /// </summary>
        /// <remarks>
        /// 管辖门店取自 lq_md_target;日志表 lq_xh_feedback;
        /// 覆盖率分母为有效耗卡(不限生美)。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "businessUnitId": "734725299018663173",
        ///   "statisticsMonth": "202607"
        /// }
        /// ```
        /// </remarks>
        /// <param name="input">公共筛选条件</param>
        /// <returns>日志数、覆盖率、照片完整率</returns>
        /// <response code="200">成功返回统计</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("GetServiceLogStatistics")]
        public async Task<BusinessUnitServiceLogStatisticsOutput> GetServiceLogStatistics(
            [FromBody] BusinessUnitDashboardStatisticsInput input)
        {
            ValidateCapabilityStatisticsInput(input);
            var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
            if (!storeIds.Any()) return new BusinessUnitServiceLogStatisticsOutput();

            var (startDate, endDateTime) = GetCapabilityMonthRange(input.StatisticsMonth);
            var consumeIds = await QueryValidConsumeIdsAsync(storeIds, startDate, endDateTime);
            if (!consumeIds.Any()) return new BusinessUnitServiceLogStatisticsOutput();

            var logs = await _db.Queryable<LqXhFeedbackEntity>()
                .Where(x => consumeIds.Contains(x.ConsumeId))
                .Where(x => x.CreateTime >= startDate && x.CreateTime <= endDateTime)
                .Select(x => new ServiceLogMetricRow
                {
                    ConsumeId = x.ConsumeId,
                    BeforeImage = x.BeforeImage,
                    AfterImage = x.AfterImage
                })
                .ToListAsync();

            var coveredConsumeCount = logs.Select(x => x.ConsumeId).Distinct().Count();
            var completePhotoCount = logs.Count(x =>
                !string.IsNullOrWhiteSpace(x.BeforeImage) &&
                !string.IsNullOrWhiteSpace(x.AfterImage));

            return new BusinessUnitServiceLogStatisticsOutput
            {
                ServiceLogCount = logs.Count,
                ValidConsumeCount = consumeIds.Count,
                CoveredConsumeCount = coveredConsumeCount,
                CoverageRate = consumeIds.Count > 0
                    ? decimal.Round((decimal)coveredConsumeCount / consumeIds.Count * 100m, 2) : 0m,
                CompletePhotoLogCount = completePhotoCount,
                CompletePhotoRate = logs.Count > 0
                    ? decimal.Round((decimal)completePhotoCount / logs.Count * 100m, 2) : 0m
            };
        }

        /// <summary>
        /// 分页查询事业部驾驶舱服务日志
        /// </summary>
        /// <remarks>
        /// 筛选条件与 GetServiceLogStatistics 一致,关联有效耗卡(不限生美)。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "businessUnitId": "734725299018663173",
        ///   "statisticsMonth": "202607",
        ///   "currentPage": 1,
        ///   "pageSize": 20
        /// }
        /// ```
        /// </remarks>
        /// <param name="input">分页筛选条件</param>
        /// <returns>服务日志分页列表</returns>
        /// <response code="200">成功返回列表</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("GetServiceLogList")]
        public async Task<dynamic> GetServiceLogList([FromBody] BusinessUnitServiceLogListInput input)
        {
            var (list, total) = await QueryServiceLogListAsync(input, true);
            return PageResult<BusinessUnitServiceLogListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<BusinessUnitServiceLogListOutput>
                {
                    list = list,
                    pagination = new PagedModel
                    {
                        PageIndex = NormalizeCapabilityPageIndex(input.currentPage),
                        PageSize = NormalizeCapabilityPageSize(input.pageSize),
                        Total = total
                    }
                });
        }

        /// <summary>
        /// 导出事业部驾驶舱服务日志
        /// </summary>
        /// <remarks>
        /// 导出条件与 GetServiceLogList 一致,成功后写入中文业务操作日志。
        /// </remarks>
        /// <param name="input">筛选条件</param>
        /// <returns>Excel 下载信息</returns>
        /// <response code="200">成功返回下载链接</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("ExportServiceLogList")]
        public async Task<dynamic> ExportServiceLogList([FromBody] BusinessUnitServiceLogListInput input)
        {
            var (list, _) = await QueryServiceLogListAsync(input, false);
            return await ExportCapabilityDataAsync(
                list,
                "导出服务日志",
                "lq_xh_feedback",
                input,
                "[{\"value\":\"门店\",\"field\":\"storeName\"},{\"value\":\"会员\",\"field\":\"memberName\"}," +
                "{\"value\":\"老师\",\"field\":\"createUserName\"},{\"value\":\"备注\",\"field\":\"remark\"}," +
                "{\"value\":\"前照片\",\"field\":\"beforeImage\"},{\"value\":\"后照片\",\"field\":\"afterImage\"}," +
                "{\"value\":\"照片完整\",\"field\":\"hasCompletePhotos\"},{\"value\":\"创建时间\",\"field\":\"createTime\"}]");
        }

        #endregion

        #region 重复充值

        /// <summary>
        /// 校验同会员同自然日是否已有有效开单或耗卡(软提醒)
        /// </summary>
        /// <remarks>
        /// 开单/耗卡保存前调用;scene 为 Billing 或 Consume;编辑时传 excludeId 排除当前单据。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "memberId": "834643959459349765",
        ///   "bizDate": "2026-07-27",
        ///   "scene": "Billing",
        ///   "excludeId": null
        /// }
        /// ```
        /// </remarks>
        /// <param name="input">校验参数</param>
        /// <returns>是否存在重复及提醒文案</returns>
        /// <response code="200">成功返回校验结果</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("CheckSameDayDuplicate")]
        public async Task<BusinessUnitCheckSameDayDuplicateOutput> CheckSameDayDuplicate(
            [FromBody] BusinessUnitCheckSameDayDuplicateInput input)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");
            if (string.IsNullOrWhiteSpace(input.MemberId)) throw NCCException.Oh("会员ID不能为空");
            if (input.BizDate == default) throw NCCException.Oh("业务日期不能为空");

            var dateStart = input.BizDate.Date;
            var dateEnd = dateStart.AddDays(1);
            var scene = (input.Scene ?? string.Empty).Trim();

            var billingQuery = _db.Queryable<LqKdKdjlbEntity>()
                .Where(x => x.Kdhy == input.MemberId && x.IsEffective == 1)
                .Where(x => x.Kdrq >= dateStart && x.Kdrq < dateEnd);
            if (!string.IsNullOrWhiteSpace(input.ExcludeId) &&
                scene.Equals(nameof(DuplicateRechargeScene.Billing), StringComparison.OrdinalIgnoreCase))
            {
                billingQuery = billingQuery.Where(x => x.Id != input.ExcludeId);
            }

            var consumeQuery = _db.Queryable<LqXhHyhkEntity>()
                .Where(x => x.Hy == input.MemberId && x.IsEffective == 1)
                .Where(x => x.Hksj >= dateStart && x.Hksj < dateEnd);
            if (!string.IsNullOrWhiteSpace(input.ExcludeId) &&
                scene.Equals(nameof(DuplicateRechargeScene.Consume), StringComparison.OrdinalIgnoreCase))
            {
                consumeQuery = consumeQuery.Where(x => x.Id != input.ExcludeId);
            }

            var billingCount = await billingQuery.CountAsync();
            var consumeCount = await consumeQuery.CountAsync();
            var existingCount = billingCount + consumeCount;

            return new BusinessUnitCheckSameDayDuplicateOutput
            {
                HasDuplicate = existingCount > 0,
                ExistingCount = existingCount,
                Message = existingCount > 0
                    ? "该会员当日已有有效开单或耗卡记录,请确认是否继续操作"
                    : string.Empty
            };
        }

        /// <summary>
        /// 分页查询重复充值审计列表(同会员同自然日第2笔及以后的开单+耗卡)
        /// </summary>
        /// <remarks>
        /// 门店范围取自 lq_md_target;统计月份内按会员+自然日合并开单与耗卡,返回当日第2笔及以后记录。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "businessUnitId": "734725299018663173",
        ///   "statisticsMonth": "202607",
        ///   "currentPage": 1,
        ///   "pageSize": 20
        /// }
        /// ```
        /// </remarks>
        /// <param name="input">分页筛选条件</param>
        /// <returns>重复充值审计分页列表</returns>
        /// <response code="200">成功返回审计列表</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("GetDuplicateRechargeAuditList")]
        public async Task<dynamic> GetDuplicateRechargeAuditList(
            [FromBody] BusinessUnitDuplicateRechargeAuditListInput input)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");

            var (startDate, endDateTime) = ResolveDuplicateAuditDateRange(input);
            var storeIds = await ResolveDuplicateAuditStoreIdsAsync(input, startDate);
            if (!storeIds.Any())
            {
                return PageResult<BusinessUnitDuplicateRechargeAuditListOutput>.SqlSugarPageResult(
                    new SqlSugarPagedList<BusinessUnitDuplicateRechargeAuditListOutput>
                    {
                        list = new List<BusinessUnitDuplicateRechargeAuditListOutput>(),
                        pagination = new PagedModel
                        {
                            PageIndex = NormalizeCapabilityPageIndex(input.currentPage),
                            PageSize = NormalizeCapabilityPageSize(input.pageSize),
                            Total = 0
                        }
                    });
            }

            var auditRows = await BuildDuplicateRechargeAuditRowsAsync(storeIds, startDate, endDateTime);

            if (!string.IsNullOrWhiteSpace(input.StoreId))
                auditRows = auditRows.Where(x => x.StoreId == input.StoreId).ToList();

            if (!string.IsNullOrWhiteSpace(input.MemberName))
            {
                var memberName = input.MemberName.Trim();
                auditRows = auditRows.Where(x =>
                    !string.IsNullOrWhiteSpace(x.MemberName) &&
                    x.MemberName.Contains(memberName)).ToList();
            }

            if (!string.IsNullOrWhiteSpace(input.BizType))
            {
                var bizType = input.BizType.Trim();
                auditRows = auditRows.Where(x =>
                    x.BizType.Equals(bizType, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
            if (keyword != null)
            {
                auditRows = auditRows.Where(x =>
                    (x.MemberName != null && x.MemberName.Contains(keyword)) ||
                    (x.StoreName != null && x.StoreName.Contains(keyword))).ToList();
            }

            auditRows = auditRows.OrderByDescending(x => x.BizTime).ToList();
            var total = auditRows.Count;
            var pageIndex = NormalizeCapabilityPageIndex(input.currentPage);
            var pageSize = NormalizeCapabilityPageSize(input.pageSize);
            var pageList = auditRows.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return PageResult<BusinessUnitDuplicateRechargeAuditListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<BusinessUnitDuplicateRechargeAuditListOutput>
                {
                    list = pageList,
                    pagination = new PagedModel
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        Total = total
                    }
                });
        }

        #endregion

        #region 私有辅助

        private void ValidateCapabilityStatisticsInput(BusinessUnitDashboardStatisticsInput input)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");
            if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
                throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
            if (string.IsNullOrWhiteSpace(input.BusinessUnitId) &&
                (input.StoreIds == null || !input.StoreIds.Any()))
                throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
        }

        /// <summary>
        /// 解析重复充值审计日期范围:优先 StartTime/EndTime,否则按 StatisticsMonth。
        /// </summary>
        private static (DateTime startDate, DateTime endDateTime) ResolveDuplicateAuditDateRange(
            BusinessUnitDuplicateRechargeAuditListInput input)
        {
            if (input.StartTime.HasValue || input.EndTime.HasValue)
            {
                var start = (input.StartTime ?? input.EndTime ?? DateTime.Today).Date;
                var endDay = (input.EndTime ?? input.StartTime ?? DateTime.Today).Date;
                if (endDay < start)
                    throw NCCException.Oh("结束时间不能早于开始时间");
                if ((endDay - start).TotalDays > 92)
                    throw NCCException.Oh("审计日期范围不能超过 92 天");
                return (start, endDay.AddDays(1).AddSeconds(-1));
            }

            if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
                throw NCCException.Oh("请传入日期范围或统计月份(YYYYMM)");

            return GetCapabilityMonthRange(input.StatisticsMonth);
        }

        /// <summary>
        /// 解析重复充值审计门店范围:事业部/门店列表/全开店。
        /// </summary>
        private async Task<List<string>> ResolveDuplicateAuditStoreIdsAsync(
            BusinessUnitDuplicateRechargeAuditListInput input, DateTime startDate)
        {
            if (!string.IsNullOrWhiteSpace(input.StoreId))
                return new List<string> { input.StoreId };

            if (input.StoreIds != null && input.StoreIds.Any(x => !string.IsNullOrWhiteSpace(x)))
                return input.StoreIds.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();

            if (!string.IsNullOrWhiteSpace(input.BusinessUnitId))
            {
                var month = !string.IsNullOrWhiteSpace(input.StatisticsMonth) && input.StatisticsMonth.Length == 6
                    ? input.StatisticsMonth
                    : startDate.ToString("yyyyMM");
                return await GetStoreIdsAsync(input.BusinessUnitId, null, month);
            }

            // 监控中心未选事业部:取全部开店门店
            return await _db.Queryable<LqMdxxEntity>()
                .Where(x => x.Zxzt == "开店")
                .Select(x => x.Id)
                .ToListAsync();
        }

        private static (DateTime startDate, DateTime endDateTime) GetCapabilityMonthRange(string statisticsMonth)
        {
            var year = int.Parse(statisticsMonth.Substring(0, 4));
            var month = int.Parse(statisticsMonth.Substring(4, 2));
            var startDate = new DateTime(year, month, 1);
            var endDate = startDate.AddMonths(1).AddDays(-1);
            var endDateTime = statisticsMonth == DateTime.Now.ToString("yyyyMM")
                ? DateTime.Now
                : endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
            return (startDate, endDateTime);
        }

        private static int NormalizeCapabilityPageIndex(int value) => value > 0 ? value : 1;

        private static int NormalizeCapabilityPageSize(int value) => value > 0 ? value : 20;

        private async Task<List<string>> QueryValidConsumeIdsAsync(
            List<string> storeIds, DateTime startDate, DateTime endDateTime)
        {
            return await _db.Queryable<LqXhHyhkEntity>()
                .Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
                .Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
                .Select(x => x.Id)
                .Distinct()
                .ToListAsync();
        }

        private async Task<(List<BusinessUnitServiceLogListOutput> list, int total)> QueryServiceLogListAsync(
            BusinessUnitServiceLogListInput input, bool paged)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");
            ValidateCapabilityStatisticsInput(new BusinessUnitDashboardStatisticsInput
            {
                BusinessUnitId = input.BusinessUnitId,
                StoreIds = input.StoreIds,
                StatisticsMonth = input.StatisticsMonth
            });

            var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
            if (!storeIds.Any()) return (new List<BusinessUnitServiceLogListOutput>(), 0);

            var (startDate, endDateTime) = GetCapabilityMonthRange(input.StatisticsMonth);
            // 直接按门店+有效耗卡时间过滤,避免数千 consumeId 的 IN 导致列表/导出超时
            var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
            var query = _db.Queryable<
                    LqXhFeedbackEntity,
                    LqXhHyhkEntity,
                    LqKhxxEntity,
                    LqMdxxEntity,
                    UserEntity>((log, consume, member, store, user) => new JoinQueryInfos(
                    JoinType.Inner, log.ConsumeId == consume.Id,
                    JoinType.Left, log.MemberId == member.Id,
                    JoinType.Left, consume.Md == store.Id,
                    JoinType.Left, log.CreateUser == user.Id))
                .Where((log, consume, member, store, user) =>
                    storeIds.Contains(consume.Md) &&
                    consume.IsEffective == 1 &&
                    consume.Hksj.HasValue &&
                    consume.Hksj.Value >= startDate &&
                    consume.Hksj.Value <= endDateTime &&
                    log.CreateTime >= startDate &&
                    log.CreateTime <= endDateTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), (log, consume, member, store, user) =>
                    consume.Md == input.StoreId)
                .WhereIF(!string.IsNullOrWhiteSpace(input.MemberName), (log, consume, member, store, user) =>
                    member.Khmc.Contains(input.MemberName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CreateUserName), (log, consume, member, store, user) =>
                    user.RealName.Contains(input.CreateUserName))
                .WhereIF(input.HasCompletePhotos == true, (log, consume, member, store, user) =>
                    log.BeforeImage != null && log.BeforeImage != "" &&
                    log.AfterImage != null && log.AfterImage != "")
                .WhereIF(input.HasCompletePhotos == false, (log, consume, member, store, user) =>
                    log.BeforeImage == null || log.BeforeImage == "" ||
                    log.AfterImage == null || log.AfterImage == "")
                .WhereIF(keyword != null, (log, consume, member, store, user) =>
                    member.Khmc.Contains(keyword) ||
                    store.Dm.Contains(keyword) ||
                    user.RealName.Contains(keyword) ||
                    log.Remark.Contains(keyword))
                .OrderBy((log, consume, member, store, user) => log.CreateTime, OrderByType.Desc)
                .Select((log, consume, member, store, user) => new BusinessUnitServiceLogListOutput
                {
                    ServiceLogId = log.Id,
                    ConsumeId = log.ConsumeId,
                    StoreId = consume.Md,
                    StoreName = store.Dm,
                    MemberId = log.MemberId,
                    MemberName = member.Khmc,
                    CreateUserId = log.CreateUser,
                    CreateUserName = user.RealName,
                    Remark = log.Remark,
                    BeforeImage = log.BeforeImage,
                    AfterImage = log.AfterImage,
                    HasCompletePhotos =
                        log.BeforeImage != null && log.BeforeImage != "" &&
                        log.AfterImage != null && log.AfterImage != "",
                    CreateTime = log.CreateTime
                });

            if (paged)
            {
                var page = await query.ToPagedListAsync(
                    NormalizeCapabilityPageIndex(input.currentPage),
                    NormalizeCapabilityPageSize(input.pageSize));
                return (page.list.ToList(), page.pagination.Total);
            }

            var list = await query.ToListAsync();
            return (list, list.Count);
        }

        private async Task<List<BusinessUnitDuplicateRechargeAuditListOutput>> BuildDuplicateRechargeAuditRowsAsync(
            List<string> storeIds, DateTime startDate, DateTime endDateTime)
        {
            var billingRows = await _db.Queryable<LqKdKdjlbEntity, LqMdxxEntity, LqKhxxEntity>(
                    (bill, store, member) => new JoinQueryInfos(
                        JoinType.Left, bill.Djmd == store.Id,
                        JoinType.Left, bill.Kdhy == member.Id))
                .Where((bill, store, member) =>
                    storeIds.Contains(bill.Djmd) &&
                    bill.IsEffective == 1 &&
                    bill.Kdrq.HasValue &&
                    bill.Kdrq.Value >= startDate &&
                    bill.Kdrq.Value <= endDateTime &&
                    !string.IsNullOrWhiteSpace(bill.Kdhy))
                .Select((bill, store, member) => new DuplicateRechargeRawRow
                {
                    BizId = bill.Id,
                    BizType = nameof(DuplicateRechargeBizType.Billing),
                    BizTypeName = "开单",
                    MemberId = bill.Kdhy,
                    MemberName = member.Khmc,
                    StoreId = bill.Djmd,
                    StoreName = store.Dm,
                    BizTime = bill.Kdrq.Value,
                    Amount = bill.Sfyj
                })
                .ToListAsync();

            var consumeRows = await _db.Queryable<LqXhHyhkEntity, LqMdxxEntity, LqKhxxEntity>(
                    (consume, store, member) => new JoinQueryInfos(
                        JoinType.Left, consume.Md == store.Id,
                        JoinType.Left, consume.Hy == member.Id))
                .Where((consume, store, member) =>
                    storeIds.Contains(consume.Md) &&
                    consume.IsEffective == 1 &&
                    consume.Hksj.HasValue &&
                    consume.Hksj.Value >= startDate &&
                    consume.Hksj.Value <= endDateTime &&
                    !string.IsNullOrWhiteSpace(consume.Hy))
                .Select((consume, store, member) => new DuplicateRechargeRawRow
                {
                    BizId = consume.Id,
                    BizType = nameof(DuplicateRechargeBizType.Consume),
                    BizTypeName = "耗卡",
                    MemberId = consume.Hy,
                    MemberName = member.Khmc ?? consume.Hymc,
                    StoreId = consume.Md,
                    StoreName = store.Dm,
                    BizTime = consume.Hksj.Value,
                    Amount = consume.Xfje ?? 0m
                })
                .ToListAsync();

            var grouped = billingRows.Concat(consumeRows)
                .GroupBy(x => new { x.MemberId, BizDate = x.BizTime.Date })
                .Where(g => g.Count() >= 2);

            var result = new List<BusinessUnitDuplicateRechargeAuditListOutput>();
            foreach (var group in grouped)
            {
                var ordered = group.OrderBy(x => x.BizTime).ThenBy(x => x.BizId).ToList();
                var dayTotal = ordered.Count;
                for (var i = 1; i < ordered.Count; i++)
                {
                    var row = ordered[i];
                    result.Add(new BusinessUnitDuplicateRechargeAuditListOutput
                    {
                        BizId = row.BizId,
                        BizType = row.BizType,
                        BizTypeName = row.BizTypeName,
                        MemberId = row.MemberId,
                        MemberName = string.IsNullOrWhiteSpace(row.MemberName) ? "无" : row.MemberName,
                        StoreId = row.StoreId,
                        StoreName = string.IsNullOrWhiteSpace(row.StoreName) ? "无" : row.StoreName,
                        BizTime = row.BizTime,
                        BizDate = row.BizTime.Date,
                        Amount = row.Amount,
                        DaySequence = i + 1,
                        DayTotalCount = dayTotal
                    });
                }
            }

            return result;
        }

        private async Task<dynamic> ExportCapabilityDataAsync<T>(
            List<T> exportData,
            string actionCode,
            string bizType,
            object filters,
            string columnsJson)
        {
            if (exportData == null || !exportData.Any())
                return new { name = string.Empty, url = string.Empty, message = "没有找到符合条件的数据" };

            var columns = columnsJson.ToList<ParamsModel>();
            var excelConfig = new ExcelConfig
            {
                FileName = actionCode + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls",
                HeadFont = "微软雅黑",
                HeadPoint = 10,
                IsAllSizeColumn = true,
                ColumnModel = columns.Select(x => new ExcelColumnModel
                {
                    Column = x.field,
                    ExcelColumn = x.value
                }).ToList()
            };

            var exportFilesPath = Path.Combine(ResolveCapabilityProjectRoot(), "ExportFiles");
            if (!Directory.Exists(exportFilesPath)) Directory.CreateDirectory(exportFilesPath);
            var addPath = Path.Combine(exportFilesPath, excelConfig.FileName);
            ExcelExportHelper<T>.Export(exportData, excelConfig, addPath);
            var encryptedFileName = _userManager.UserId + "|" + addPath + "|xls";

            await _businessOperationLogService.WriteAsync(
                CapabilityBizLogModule,
                actionCode,
                bizType,
                null,
                $"{actionCode},共 {exportData.Count} 条",
                JsonConvert.SerializeObject(new
                {
                    filters,
                    rowCount = exportData.Count,
                    fileName = excelConfig.FileName
                }));

            return new
            {
                name = excelConfig.FileName,
                url = "/api/File/Download?encryption=" +
                      DESCEncryption.Encrypt(encryptedFileName, "NCC")
            };
        }

        private static string ResolveCapabilityProjectRoot()
        {
            var baseDir = AppContext.BaseDirectory;
            var dir = new DirectoryInfo(baseDir);
            while (dir != null && dir.Parent != null)
            {
                if (dir.GetDirectories(".git").Any()) return dir.FullName;
                dir = dir.Parent;
            }

            dir = new DirectoryInfo(baseDir);
            while (dir != null && dir.Parent != null)
            {
                if (dir.GetFiles("*.sln").Any()) return dir.FullName;
                dir = dir.Parent;
            }

            return baseDir;
        }

        private class ServiceLogMetricRow
        {
            public string ConsumeId { get; set; }
            public string BeforeImage { get; set; }
            public string AfterImage { get; set; }
        }

        private class DuplicateRechargeRawRow
        {
            public string BizId { get; set; }
            public string BizType { get; set; }
            public string BizTypeName { get; set; }
            public string MemberId { get; set; }
            public string MemberName { get; set; }
            public string StoreId { get; set; }
            public string StoreName { get; set; }
            public DateTime BizTime { get; set; }
            public decimal Amount { get; set; }
        }

        private class StoreRankingMetricsRow
        {
            public string StoreId { get; set; }
            public decimal BillingPerformance { get; set; }
            public decimal ConsumePerformance { get; set; }
            public decimal RefundAmount { get; set; }
            public int BillingCount { get; set; }
            public int ConsumeCount { get; set; }
            public int HeadCount { get; set; }
            public int PersonCount { get; set; }
            public decimal ProjectCount { get; set; }
            public decimal TargetPerformance { get; set; }
        }

        /// <summary>
        /// 批量加载门店排行指标,避免门店循环 N+1
        /// </summary>
        private async Task<List<StoreRankingMetricsRow>> LoadStoreRankingMetricsBatchAsync(
            List<string> storeIds, DateTime startDate, DateTime endDateTime, string statisticsMonth)
        {
            if (!storeIds.Any()) return new List<StoreRankingMetricsRow>();

            var billingRows = await _db.Queryable<LqKdKdjlbEntity>()
                .Where(x => storeIds.Contains(x.Djmd) && x.IsEffective == 1)
                .Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
                .GroupBy(x => x.Djmd)
                .Select(x => new StoreRankingMetricsRow
                {
                    StoreId = x.Djmd,
                    BillingPerformance = SqlFunc.AggregateSum(x.Sfyj),
                    BillingCount = SqlFunc.AggregateCount(x.Id)
                })
                .ToListAsync();

            var refundRows = await _db.Queryable<LqHytkHytkEntity>()
                .Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
                .Where(x => x.Tksj.HasValue &&
                            x.Tksj.Value.Date >= startDate.Date &&
                            x.Tksj.Value.Date <= endDateTime.Date)
                .GroupBy(x => x.Md)
                .Select(x => new { StoreId = x.Md, RefundAmount = SqlFunc.AggregateSum(x.ActualRefundAmount ?? x.Tkje ?? 0) })
                .ToListAsync();

            var consumeRows = await _db.Queryable<LqXhHyhkEntity>()
                .Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
                .Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
                .GroupBy(x => x.Md)
                .Select(x => new StoreRankingMetricsRow
                {
                    StoreId = x.Md,
                    ConsumePerformance = SqlFunc.AggregateSum(x.Xfje ?? 0),
                    ConsumeCount = SqlFunc.AggregateCount(x.Id)
                })
                .ToListAsync();

            var headCountRows = await _db.Queryable<LqXhHyhkEntity>()
                .Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
                .Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
                .Where(x => !string.IsNullOrWhiteSpace(x.Hy))
                .GroupBy(x => x.Md)
                .Select(x => new { StoreId = x.Md, HeadCount = SqlFunc.AggregateDistinctCount(x.Hy) })
                .ToListAsync();

            var storeIdsStr = string.Join("','", storeIds);
            var personCountSql = $@"
                SELECT xh.Md AS StoreId,
                       COUNT(DISTINCT CONCAT(xh.Hy, '-', DATE_FORMAT(xh.Hksj, '%Y-%m-%d'))) AS PersonCount
                FROM lq_xh_hyhk xh
                WHERE xh.Md IN ('{storeIdsStr}')
                  AND xh.F_IsEffective = 1
                  AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
                  AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'
                  AND xh.Hy IS NOT NULL AND TRIM(xh.Hy) != ''
                GROUP BY xh.Md";
            var personCountRows = await _db.Ado.SqlQueryAsync<dynamic>(personCountSql);

            var projectCountSql = $@"
                SELECT xh.Md AS StoreId,
                       COALESCE(SUM(COALESCE(px.F_OriginalProjectNumber, px.F_ProjectNumber, 0)), 0) AS ProjectCount
                FROM lq_xh_pxmx px
                INNER JOIN lq_xh_hyhk xh ON px.F_ConsumeInfoId = xh.F_Id
                WHERE xh.Md IN ('{storeIdsStr}')
                  AND xh.F_IsEffective = 1
                  AND px.F_IsEffective = 1
                  AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
                  AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'
                GROUP BY xh.Md";
            var projectCountRows = await _db.Ado.SqlQueryAsync<dynamic>(projectCountSql);

            var targetRows = await _db.Queryable<LqMdTargetEntity>()
                .Where(x => storeIds.Contains(x.StoreId) && x.Month == statisticsMonth)
                .GroupBy(x => x.StoreId)
                .Select(x => new { StoreId = x.StoreId, Target = SqlFunc.AggregateSum(x.BusinessUnitTarget) })
                .ToListAsync();

            var billingDict = billingRows.ToDictionary(x => x.StoreId ?? string.Empty, x => x);
            var refundDict = refundRows.ToDictionary(x => x.StoreId ?? string.Empty, x => x.RefundAmount);
            var consumeDict = consumeRows.ToDictionary(x => x.StoreId ?? string.Empty, x => x);
            var headCountDict = headCountRows.ToDictionary(x => x.StoreId ?? string.Empty, x => x.HeadCount);
            var personCountDict = (personCountRows ?? Enumerable.Empty<dynamic>())
                .ToDictionary(x => (string)(x.StoreId ?? string.Empty), x => Convert.ToInt32(x.PersonCount ?? 0));
            var projectCountDict = (projectCountRows ?? Enumerable.Empty<dynamic>())
                .ToDictionary(x => (string)(x.StoreId ?? string.Empty), x => Convert.ToDecimal(x.ProjectCount ?? 0));
            var targetDict = targetRows.ToDictionary(x => x.StoreId ?? string.Empty, x => x.Target);

            return storeIds.Select(storeId =>
            {
                billingDict.TryGetValue(storeId, out var billing);
                consumeDict.TryGetValue(storeId, out var consume);
                refundDict.TryGetValue(storeId, out var refundAmount);
                headCountDict.TryGetValue(storeId, out var headCount);
                personCountDict.TryGetValue(storeId, out var personCount);
                projectCountDict.TryGetValue(storeId, out var projectCount);
                targetDict.TryGetValue(storeId, out var targetPerformance);

                var billingPerformance = billing?.BillingPerformance ?? 0m;
                return new StoreRankingMetricsRow
                {
                    StoreId = storeId,
                    BillingPerformance = billingPerformance,
                    ConsumePerformance = consume?.ConsumePerformance ?? 0m,
                    RefundAmount = refundAmount,
                    BillingCount = billing?.BillingCount ?? 0,
                    ConsumeCount = consume?.ConsumeCount ?? 0,
                    HeadCount = headCount,
                    PersonCount = personCount,
                    ProjectCount = projectCount,
                    TargetPerformance = targetPerformance
                };
            }).ToList();
        }

        #endregion
    }
}