LqEducationDepartmentDashboardService.AcquisitionFunnel.cs 50.1 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 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NCC.Common.Extension;
using NCC.Common.Helper;
using NCC.Common.Model.NPOI;
using NCC.DataEncryption;
using NCC.Extend.Entitys.Dto.LqEducationDepartmentDashboard;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_kd_pxmx;
using NCC.Extend.Entitys.lq_khxx;
using NCC.Extend.Entitys.lq_md_target;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_tkjlb;
using NCC.Extend.Entitys.lq_xh_hyhk;
using NCC.Extend.Helpers;
using NCC.FriendlyException;
using SqlSugar;

namespace NCC.Extend
{
    /// <summary>
    /// 教育部经营看板 - 拓客漏斗分析
    /// </summary>
    public partial class LqEducationDepartmentDashboardService
    {
        private const string DealTypeGoddessLife = "生美-女神卡";
        private const string DealTypeOtherLife = "生美-其他";
        private const string DealTypeTech = "科美";
        private const string DealTypeMedical = "医美";
        private const string TechBeautyCategory = "科美";
        private const string MedicalBeautyCategory = "医美";
        private const int UpgradeWindowDays = 90;

        private static readonly string[] AllDealTypes =
        {
            DealTypeGoddessLife, DealTypeOtherLife, DealTypeTech, DealTypeMedical
        };

        /// <summary>
        /// 获取拓客漏斗分析(①~⑦ + 结论)
        /// </summary>
        /// <remarks>
        /// 按教育部/门店范围与日期区间,聚合线索→到店→成交分型→90天升单全链路指标,供战略决策中心漏斗区块展示。
        ///
        /// 示例请求(全部教育部):
        /// ```json
        /// {
        ///   "startDate": "2026-09-01",
        ///   "endDate": "2026-09-17"
        /// }
        /// ```
        ///
        /// 示例请求(指定教育部):
        /// ```json
        /// {
        ///   "educationDepartmentId": "教育部组织ID",
        ///   "startDate": "2026-09-01",
        ///   "endDate": "2026-09-17"
        /// }
        /// ```
        ///
        /// 参数说明:
        /// - educationDepartmentId: 教育部组织ID,与 storeIds 二选一;都不传则统计全部挂教育部的门店
        /// - storeIds: 门店ID列表,与 educationDepartmentId 二选一
        /// - startDate: 统计开始日期(必填)
        /// - endDate: 统计结束日期(必填,须大于等于 startDate)
        ///
        /// 返回 storeRows:按拓客门店拆分的线索/到店/成交/升单。同一会员在多家门店拓客时各店分别计数,门店合计可能大于整体去重人数。
        /// </remarks>
        /// <param name="input">查询条件</param>
        /// <returns>拓客漏斗全量分析结果,含门店拆分 storeRows</returns>
        /// <response code="200">成功返回拓客漏斗分析数据</response>
        /// <response code="400">参数校验失败</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("GetAcquisitionFunnelAnalysis")]
        public async Task<EducationDepartmentDashboardAcquisitionFunnelOutput> GetAcquisitionFunnelAnalysis(
            [FromBody] EducationDepartmentDashboardAcquisitionFunnelInput input)
        {
            var (startInclusive, endExclusive, storeIds) = await ResolveAcquisitionFunnelContextAsync(input);
            if (!storeIds.Any())
            {
                return BuildEmptyAcquisitionFunnelOutput();
            }

            var facts = await ComputeAcquisitionFunnelFactsAsync(startInclusive, endExclusive, storeIds);
            if (facts == null)
            {
                return BuildEmptyAcquisitionFunnelOutput();
            }

            var output = BuildAcquisitionFunnelOutput(
                facts.LeadSet,
                facts.ArrivalSet,
                facts.DealSet,
                facts.UpgradedMembers,
                facts.MemberDealType,
                facts.UpgradeDetails,
                facts.TkGiftItemIdSet);
            output.StoreRows = await BuildAcquisitionFunnelStoreRowsAsync(
                facts.LeadRecords,
                facts.ArrivalSet,
                facts.DealSet,
                facts.UpgradedMembers);
            return output;
        }

        /// <summary>
        /// 导出拓客漏斗指定门店的会员明细
        /// </summary>
        /// <remarks>
        /// 导出所选门店在统计区间内的拓客会员,一行一名会员,并标注是否到店、是否成交、成交类型、首单日期、是否升单。
        /// 门店必须落在当前教育部(或全部教育部)的统计范围内。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "educationDepartmentId": "教育部组织ID",
        ///   "storeId": "门店ID",
        ///   "startDate": "2026-09-01",
        ///   "endDate": "2026-09-21"
        /// }
        /// ```
        ///
        /// 参数说明:
        /// - educationDepartmentId: 教育部组织ID,可选;不传则按全部教育部校验门店范围
        /// - storeId: 门店ID,必填
        /// - startDate: 统计开始日期(必填)
        /// - endDate: 统计结束日期(必填,须大于等于 startDate)
        /// </remarks>
        /// <param name="input">导出条件</param>
        /// <returns>导出文件名与下载地址</returns>
        /// <response code="200">成功返回下载地址;无数据时 url 为空并带 message</response>
        /// <response code="400">参数缺失或门店不在统计范围内</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("ExportAcquisitionFunnelStoreDetail")]
        public async Task<dynamic> ExportAcquisitionFunnelStoreDetail(
            [FromBody] EducationDepartmentDashboardAcquisitionFunnelStoreDetailInput input)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");
            var storeId = (input.StoreId ?? string.Empty).Trim();
            if (string.IsNullOrWhiteSpace(storeId)) throw NCCException.Oh("门店ID不能为空");

            var (startInclusive, endExclusive, scopedStoreIds) = await ResolveAcquisitionFunnelContextAsync(input);
            if (!scopedStoreIds.Any(x => string.Equals(x, storeId, StringComparison.OrdinalIgnoreCase)))
            {
                throw NCCException.Oh("门店不在当前统计范围内");
            }

            var facts = await ComputeAcquisitionFunnelFactsAsync(
                startInclusive,
                endExclusive,
                new List<string> { storeId });
            var exportRows = facts == null
                ? new List<AcquisitionFunnelStoreDetailExportOutput>()
                : await BuildStoreDetailExportRowsAsync(facts, storeId);
            if (!exportRows.Any())
            {
                return new { name = string.Empty, url = string.Empty, message = "没有找到符合条件的数据" };
            }

            var storeName = exportRows[0].StoreName;
            var safeStoreName = string.Join("_", (storeName ?? "门店").Split(Path.GetInvalidFileNameChars()));
            var excelconfig = new ExcelConfig
            {
                FileName = $"拓客漏斗门店明细_{safeStoreName}_{DateTime.Now:yyyyMMddHHmmss}.xls",
                HeadFont = "微软雅黑",
                HeadPoint = 10,
                IsAllSizeColumn = true,
                ColumnModel = BuildFunnelStoreDetailColumns()
                    .Select(x => new ExcelColumnModel { Column = x.field, ExcelColumn = x.value })
                    .ToList()
            };

            var exportFilesPath = Path.Combine(ResolveProjectRoot(), "ExportFiles");
            if (!Directory.Exists(exportFilesPath)) Directory.CreateDirectory(exportFilesPath);
            var addPath = Path.Combine(exportFilesPath, excelconfig.FileName);
            ExcelExportHelper<AcquisitionFunnelStoreDetailExportOutput>.Export(exportRows, excelconfig, addPath);

            var dateLabel = $"{startInclusive:yyyy-MM-dd} 至 {endExclusive.AddDays(-1):yyyy-MM-dd}";
            try
            {
                await _businessOperationLogService.WriteAsync(
                    BizLogModule,
                    "导出拓客漏斗门店明细",
                    "lq_tkjlb",
                    storeId,
                    $"导出拓客漏斗门店明细「{storeName}」{dateLabel},共 {exportRows.Count} 条",
                    JsonConvert.SerializeObject(new
                    {
                        filters = new
                        {
                            educationDepartmentId = input.EducationDepartmentId,
                            storeId,
                            startDate = startInclusive.ToString("yyyy-MM-dd"),
                            endDate = endExclusive.AddDays(-1).ToString("yyyy-MM-dd")
                        },
                        rowCount = exportRows.Count,
                        fileName = excelconfig.FileName
                    }));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "拓客漏斗门店明细导出业务日志写入失败");
            }

            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            return new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
            };
        }

        private async Task<AcquisitionFunnelFacts> ComputeAcquisitionFunnelFactsAsync(
            DateTime startInclusive,
            DateTime endExclusive,
            List<string> storeIds)
        {
            if (storeIds == null || !storeIds.Any()) return null;

            var tkGiftItemIds = await ItemCategoryRuleHelper.GetTkGiftItemIdsAsync(_db);
            var tkGiftItemIdSet = new HashSet<string>(tkGiftItemIds, StringComparer.Ordinal);

            var leadRecords = await _db.Queryable<LqTkjlbEntity>()
                .Where(x => storeIds.Contains(x.StoreId))
                .Where(x => x.ExpansionTime >= startInclusive && x.ExpansionTime < endExclusive)
                .Where(x => !SqlFunc.IsNullOrEmpty(x.MemberId))
                .Select(x => new LeadRecordRow
                {
                    StoreId = x.StoreId,
                    MemberId = x.MemberId,
                    ExpansionTime = x.ExpansionTime,
                    CustomerName = x.CustomerName,
                    CustomerPhone = x.CustomerPhone
                })
                .ToListAsync();

            var leadMemberIds = leadRecords
                .Select(x => x.MemberId)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Distinct(StringComparer.Ordinal)
                .ToList();
            if (!leadMemberIds.Any()) return null;

            var arrivalMemberIds = await _db.Queryable<LqXhHyhkEntity>()
                .Where(x => leadMemberIds.Contains(x.Hy))
                .Where(x => x.IsEffective == 1)
                .Where(x => x.Hksj >= startInclusive && x.Hksj < endExclusive)
                .Select(x => x.Hy)
                .Distinct()
                .ToListAsync();

            var billingRows = await _db.Queryable<LqKdKdjlbEntity>()
                .Where(x => leadMemberIds.Contains(x.Kdhy))
                .Where(x => x.IsEffective == 1)
                .Where(x => x.Sfyj > 0)
                .Where(x => x.Kdrq.HasValue)
                .Where(x => x.Kdrq.Value >= startInclusive && x.Kdrq.Value < endExclusive)
                .Select(x => new MemberBillRow
                {
                    BillId = x.Id,
                    MemberId = x.Kdhy,
                    BillingDate = x.Kdrq.Value
                })
                .ToListAsync();

            var firstBillByMember = billingRows
                .GroupBy(x => x.MemberId)
                .ToDictionary(
                    g => g.Key,
                    g => g.OrderBy(x => x.BillingDate).ThenBy(x => x.BillId, StringComparer.Ordinal).First());

            var dealMemberIds = firstBillByMember.Keys.ToList();
            var firstBillIds = firstBillByMember.Values.Select(x => x.BillId).Distinct().ToList();
            var firstBillDetails = firstBillIds.Any()
                ? await _db.Queryable<LqKdPxmxEntity>()
                    .Where(x => firstBillIds.Contains(x.Glkdbh))
                    .Where(x => x.IsEffective == 1)
                    .Select(x => new BillDetailRow
                    {
                        BillId = x.Glkdbh,
                        MemberId = x.MemberId,
                        ItemId = x.Px,
                        ItemName = x.Pxmc,
                        ItemCategory = x.ItemCategory,
                        ActualPrice = x.ActualPrice
                    })
                    .ToListAsync()
                : new List<BillDetailRow>();

            var detailsByBill = firstBillDetails
                .GroupBy(x => x.BillId)
                .ToDictionary(g => g.Key, g => g.ToList());
            var memberDealType = new Dictionary<string, string>(StringComparer.Ordinal);
            foreach (var pair in firstBillByMember)
            {
                detailsByBill.TryGetValue(pair.Value.BillId, out var details);
                memberDealType[pair.Key] = ClassifyDealType(details, tkGiftItemIdSet);
            }

            var upgradeEndByMember = firstBillByMember.ToDictionary(
                x => x.Key,
                x => x.Value.BillingDate.AddDays(UpgradeWindowDays));
            var maxUpgradeEnd = upgradeEndByMember.Values.DefaultIfEmpty(endExclusive).Max();
            var upgradeCandidateBills = dealMemberIds.Any()
                ? await _db.Queryable<LqKdKdjlbEntity>()
                    .Where(x => dealMemberIds.Contains(x.Kdhy))
                    .Where(x => x.IsEffective == 1)
                    .Where(x => x.Sfyj > 0)
                    .Where(x => x.Kdrq.HasValue)
                    .Where(x => x.Kdrq.Value >= startInclusive && x.Kdrq.Value <= maxUpgradeEnd)
                    .Select(x => new MemberBillRow
                    {
                        BillId = x.Id,
                        MemberId = x.Kdhy,
                        BillingDate = x.Kdrq.Value
                    })
                    .ToListAsync()
                : new List<MemberBillRow>();

            var upgradeBillIds = new HashSet<string>(StringComparer.Ordinal);
            var upgradedMembers = new HashSet<string>(StringComparer.Ordinal);
            foreach (var memberId in dealMemberIds)
            {
                if (!firstBillByMember.TryGetValue(memberId, out var firstBill)) continue;
                var windowEnd = upgradeEndByMember[memberId];
                var upgradeBills = upgradeCandidateBills.Where(x =>
                    x.MemberId == memberId &&
                    !string.Equals(x.BillId, firstBill.BillId, StringComparison.Ordinal) &&
                    x.BillingDate >= firstBill.BillingDate &&
                    x.BillingDate <= windowEnd).ToList();
                if (!upgradeBills.Any()) continue;
                upgradedMembers.Add(memberId);
                foreach (var bill in upgradeBills) upgradeBillIds.Add(bill.BillId);
            }

            var upgradeDetails = upgradeBillIds.Any()
                ? await _db.Queryable<LqKdPxmxEntity>()
                    .Where(x => upgradeBillIds.Contains(x.Glkdbh))
                    .Where(x => x.IsEffective == 1)
                    .Select(x => new BillDetailRow
                    {
                        BillId = x.Glkdbh,
                        MemberId = x.MemberId,
                        ItemId = x.Px,
                        ItemName = x.Pxmc,
                        ItemCategory = x.ItemCategory,
                        ActualPrice = x.ActualPrice
                    })
                    .ToListAsync()
                : new List<BillDetailRow>();

            var billMemberMap = upgradeCandidateBills
                .Where(x => !string.IsNullOrWhiteSpace(x.BillId) && !string.IsNullOrWhiteSpace(x.MemberId))
                .GroupBy(x => x.BillId, StringComparer.Ordinal)
                .ToDictionary(g => g.Key, g => g.First().MemberId, StringComparer.Ordinal);
            foreach (var detail in upgradeDetails)
            {
                if (!string.IsNullOrWhiteSpace(detail.MemberId)) continue;
                if (!string.IsNullOrWhiteSpace(detail.BillId)
                    && billMemberMap.TryGetValue(detail.BillId, out var memberId))
                {
                    detail.MemberId = memberId;
                }
            }

            return new AcquisitionFunnelFacts
            {
                LeadRecords = leadRecords,
                LeadSet = new HashSet<string>(leadMemberIds, StringComparer.Ordinal),
                ArrivalSet = new HashSet<string>(arrivalMemberIds, StringComparer.Ordinal),
                DealSet = new HashSet<string>(dealMemberIds, StringComparer.Ordinal),
                UpgradedMembers = upgradedMembers,
                MemberDealType = memberDealType,
                FirstBillDateByMember = firstBillByMember.ToDictionary(
                    x => x.Key,
                    x => x.Value.BillingDate,
                    StringComparer.Ordinal),
                UpgradeDetails = upgradeDetails,
                TkGiftItemIdSet = tkGiftItemIdSet
            };
        }

        private async Task<List<AcquisitionFunnelStoreRow>> BuildAcquisitionFunnelStoreRowsAsync(
            List<LeadRecordRow> leadRecords,
            HashSet<string> arrivalSet,
            HashSet<string> dealSet,
            HashSet<string> upgradedMembers)
        {
            var grouped = (leadRecords ?? new List<LeadRecordRow>())
                .Where(x => !string.IsNullOrWhiteSpace(x.StoreId) && !string.IsNullOrWhiteSpace(x.MemberId))
                .GroupBy(x => x.StoreId, StringComparer.OrdinalIgnoreCase)
                .Select(g =>
                {
                    var members = g.Select(x => x.MemberId).Distinct(StringComparer.Ordinal).ToList();
                    var leadCount = members.Count;
                    var arrivalCount = members.Count(arrivalSet.Contains);
                    var dealCount = members.Count(dealSet.Contains);
                    var upgradeCount = members.Count(upgradedMembers.Contains);
                    return new AcquisitionFunnelStoreRow
                    {
                        StoreId = g.Key,
                        LeadCount = leadCount,
                        ArrivalCount = arrivalCount,
                        ArrivalRate = SafePercent(arrivalCount, leadCount),
                        DealCount = dealCount,
                        DealRate = SafePercent(dealCount, arrivalCount),
                        UpgradeCount = upgradeCount,
                        UpgradeRate = SafePercent(upgradeCount, dealCount)
                    };
                })
                .ToList();

            if (!grouped.Any()) return grouped;

            var storeIds = grouped.Select(x => x.StoreId).ToList();
            var storeNames = await _db.Queryable<LqMdxxEntity>()
                .Where(x => storeIds.Contains(x.Id))
                .Select(x => new { x.Id, x.Dm })
                .ToListAsync();
            var nameMap = storeNames
                .Where(x => !string.IsNullOrWhiteSpace(x.Id))
                .GroupBy(x => x.Id, StringComparer.OrdinalIgnoreCase)
                .ToDictionary(g => g.Key, g => g.First().Dm ?? string.Empty, StringComparer.OrdinalIgnoreCase);

            foreach (var row in grouped)
            {
                row.StoreName = nameMap.TryGetValue(row.StoreId, out var name) && !string.IsNullOrWhiteSpace(name)
                    ? name
                    : "无";
            }

            return grouped
                .OrderByDescending(x => x.LeadCount)
                .ThenBy(x => x.StoreName)
                .ToList();
        }

        private async Task<List<AcquisitionFunnelStoreDetailExportOutput>> BuildStoreDetailExportRowsAsync(
            AcquisitionFunnelFacts facts,
            string storeId)
        {
            var members = facts.LeadRecords
                .Where(x => string.Equals(x.StoreId, storeId, StringComparison.OrdinalIgnoreCase))
                .Where(x => !string.IsNullOrWhiteSpace(x.MemberId))
                .GroupBy(x => x.MemberId, StringComparer.Ordinal)
                .Select(g => g.OrderBy(x => x.ExpansionTime).First())
                .ToList();
            if (!members.Any()) return new List<AcquisitionFunnelStoreDetailExportOutput>();

            var stores = await _db.Queryable<LqMdxxEntity>()
                .Where(x => x.Id == storeId)
                .Select(x => new { x.Dm })
                .ToListAsync();
            var storeName = stores.Select(x => x.Dm).FirstOrDefault();
            storeName = string.IsNullOrWhiteSpace(storeName) ? "无" : storeName;

            var missingIds = members
                .Where(x => string.IsNullOrWhiteSpace(x.CustomerName) || string.IsNullOrWhiteSpace(x.CustomerPhone))
                .Select(x => x.MemberId)
                .Distinct(StringComparer.Ordinal)
                .ToList();
            var memberMap = new Dictionary<string, (string Name, string Phone)>(StringComparer.Ordinal);
            if (missingIds.Any())
            {
                var khList = await _db.Queryable<LqKhxxEntity>()
                    .Where(x => missingIds.Contains(x.Id))
                    .Select(x => new { x.Id, x.Khmc, x.Sjh })
                    .ToListAsync();
                foreach (var kh in khList.Where(x => !string.IsNullOrWhiteSpace(x.Id)))
                {
                    memberMap[kh.Id] = (kh.Khmc, kh.Sjh);
                }
            }

            return members
                .OrderBy(x => x.ExpansionTime)
                .Select(x =>
                {
                    memberMap.TryGetValue(x.MemberId, out var kh);
                    var name = string.IsNullOrWhiteSpace(x.CustomerName) ? kh.Name : x.CustomerName;
                    var phone = string.IsNullOrWhiteSpace(x.CustomerPhone) ? kh.Phone : x.CustomerPhone;
                    var dealt = facts.DealSet.Contains(x.MemberId);
                    facts.MemberDealType.TryGetValue(x.MemberId, out var dealType);
                    facts.FirstBillDateByMember.TryGetValue(x.MemberId, out var firstBillDate);
                    return new AcquisitionFunnelStoreDetailExportOutput
                    {
                        StoreName = storeName,
                        MemberName = string.IsNullOrWhiteSpace(name) ? "无" : name,
                        MemberPhone = string.IsNullOrWhiteSpace(phone) ? "无" : phone,
                        ExpansionTime = x.ExpansionTime.ToString("yyyy-MM-dd HH:mm"),
                        Arrived = facts.ArrivalSet.Contains(x.MemberId) ? "是" : "否",
                        Dealt = dealt ? "是" : "否",
                        DealType = dealt && !string.IsNullOrWhiteSpace(dealType) ? dealType : "无",
                        FirstBillDate = dealt ? firstBillDate.ToString("yyyy-MM-dd") : "无",
                        Upgraded = facts.UpgradedMembers.Contains(x.MemberId) ? "是" : "否"
                    };
                })
                .ToList();
        }

        private static List<ParamsModel> BuildFunnelStoreDetailColumns() =>
            "[{\"value\":\"门店\",\"field\":\"StoreName\"},{\"value\":\"会员姓名\",\"field\":\"MemberName\"},{\"value\":\"手机号\",\"field\":\"MemberPhone\"},{\"value\":\"拓客时间\",\"field\":\"ExpansionTime\"},{\"value\":\"是否到店\",\"field\":\"Arrived\"},{\"value\":\"是否成交\",\"field\":\"Dealt\"},{\"value\":\"成交类型\",\"field\":\"DealType\"},{\"value\":\"首单日期\",\"field\":\"FirstBillDate\"},{\"value\":\"是否升单\",\"field\":\"Upgraded\"}]"
                .ToList<ParamsModel>();

        private async Task<(DateTime startInclusive, DateTime endExclusive, List<string> storeIds)>
            ResolveAcquisitionFunnelContextAsync(EducationDepartmentDashboardAcquisitionFunnelInput input)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");
            if (!input.StartDate.HasValue || !input.EndDate.HasValue)
                throw NCCException.Oh("开始日期与结束日期不能为空");

            var start = input.StartDate.Value.Date;
            var end = input.EndDate.Value.Date;
            if (end < start) throw NCCException.Oh("结束日期不能早于开始日期");

            if (!string.IsNullOrWhiteSpace(input.EducationDepartmentId) &&
                input.StoreIds != null && input.StoreIds.Any())
                throw NCCException.Oh("教育部ID和门店ID列表不能同时传入,请只传入其中一个");

            var storeIds = string.IsNullOrWhiteSpace(input.EducationDepartmentId) &&
                           (input.StoreIds == null || !input.StoreIds.Any())
                ? await GetAllEducationStoreIdsUnionForDateRangeAsync(start, end)
                : await GetStoreIdsUnionForDateRangeAsync(
                    input.EducationDepartmentId,
                    input.StoreIds,
                    start,
                    end);

            return (start, end.AddDays(1), storeIds);
        }

        /// <summary>
        /// 区间内全部挂教育部的门店(教育一部、教育二部等),并套用教育老师门店范围。
        /// </summary>
        private async Task<List<string>> GetAllEducationStoreIdsUnionForDateRangeAsync(
            DateTime startDate,
            DateTime endDate)
        {
            var months = BuildStatisticsMonthList(startDate, endDate);
            var union = new HashSet<string>(StringComparer.Ordinal);
            foreach (var month in months)
            {
                var monthStores = await _db.Queryable<LqMdTargetEntity>()
                    .Where(x => x.Month == month && !SqlFunc.IsNullOrEmpty(x.EducationDepartment))
                    .Select(x => x.StoreId)
                    .Distinct()
                    .ToListAsync();
                var ids = await GetStoreIdsAsync(null, monthStores, month);
                foreach (var id in ids.Where(x => !string.IsNullOrWhiteSpace(x)))
                {
                    union.Add(id);
                }
            }

            return union.ToList();
        }

        private async Task<List<string>> GetStoreIdsUnionForDateRangeAsync(
            string educationDepartmentId,
            List<string> storeIds,
            DateTime startDate,
            DateTime endDate)
        {
            var months = BuildStatisticsMonthList(startDate, endDate);
            var union = new HashSet<string>(StringComparer.Ordinal);
            foreach (var month in months)
            {
                var ids = await GetStoreIdsAsync(educationDepartmentId, storeIds, month);
                foreach (var id in ids.Where(x => !string.IsNullOrWhiteSpace(x)))
                {
                    union.Add(id);
                }
            }

            return union.ToList();
        }

        private static List<string> BuildStatisticsMonthList(DateTime startDate, DateTime endDate)
        {
            var months = new List<string>();
            var cursor = new DateTime(startDate.Year, startDate.Month, 1);
            var endMonth = new DateTime(endDate.Year, endDate.Month, 1);
            while (cursor <= endMonth)
            {
                months.Add(cursor.ToString("yyyyMM"));
                cursor = cursor.AddMonths(1);
            }

            return months;
        }

        private static string ClassifyDealType(List<BillDetailRow> details, HashSet<string> tkGiftItemIdSet)
        {
            if (details == null || !details.Any())
            {
                return DealTypeOtherLife;
            }

            if (details.Any(x => ItemCategoryRuleHelper.IsTkGiftItem(x.ItemId, tkGiftItemIdSet)))
            {
                return DealTypeGoddessLife;
            }

            var top = details
                .OrderByDescending(x => x.ActualPrice)
                .ThenBy(x => x.ItemId, StringComparer.Ordinal)
                .First();

            var category = top.ItemCategory?.Trim();
            if (string.Equals(category, LifeBeautyCategory, StringComparison.Ordinal))
                return DealTypeOtherLife;
            if (string.Equals(category, TechBeautyCategory, StringComparison.Ordinal))
                return DealTypeTech;
            if (string.Equals(category, MedicalBeautyCategory, StringComparison.Ordinal))
                return DealTypeMedical;

            return DealTypeOtherLife;
        }

        private EducationDepartmentDashboardAcquisitionFunnelOutput BuildAcquisitionFunnelOutput(
            HashSet<string> leadSet,
            HashSet<string> arrivalSet,
            HashSet<string> dealSet,
            HashSet<string> upgradedMembers,
            Dictionary<string, string> memberDealType,
            List<BillDetailRow> upgradeDetails,
            HashSet<string> tkGiftItemIdSet)
        {
            var leadCount = leadSet.Count;
            var arrivalCount = arrivalSet.Count;
            var dealCount = dealSet.Count;
            var upgradeCount = upgradedMembers.Count;

            var arrivalRate = SafePercent(arrivalCount, leadCount);
            var dealRate = SafePercent(dealCount, arrivalCount);
            var upgradeRate = SafePercent(upgradeCount, dealCount);
            var leadToDealRate = SafePercent(dealCount, leadCount);

            var output = new EducationDepartmentDashboardAcquisitionFunnelOutput
            {
                SummaryKpis = new AcquisitionFunnelSummaryKpis
                {
                    LeadCount = leadCount,
                    ArrivalCount = arrivalCount,
                    ArrivalRate = arrivalRate,
                    DealCount = dealCount,
                    DealRate = dealRate,
                    UpgradeCount = upgradeCount,
                    UpgradeRate = upgradeRate,
                    LeadToDealRate = leadToDealRate
                },
                FunnelSteps = BuildFunnelSteps(leadCount, arrivalCount, dealCount, upgradeCount,
                    arrivalRate, dealRate, upgradeRate),
                DropOffs = BuildDropOffs(leadCount, arrivalCount, dealCount, upgradeCount),
                DealTypeDistribution = BuildDealTypeDistribution(memberDealType, dealCount),
                LifeBeautySplit = BuildLifeBeautySplit(memberDealType, upgradedMembers, upgradeDetails, tkGiftItemIdSet),
                DealTypeUpgradeRates = BuildDealTypeUpgradeRates(memberDealType, upgradedMembers),
                MetricNote = BuildMetricNote(tkGiftItemIdSet)
            };

            var goddessUpgraded = upgradedMembers
                .Where(m => memberDealType.TryGetValue(m, out var t) && t == DealTypeGoddessLife)
                .ToHashSet(StringComparer.Ordinal);
            var otherLifeUpgraded = upgradedMembers
                .Where(m => memberDealType.TryGetValue(m, out var t) && t == DealTypeOtherLife)
                .ToHashSet(StringComparer.Ordinal);

            output.GoddessUpgradeFlow = BuildGoddessUpgradeFlow(goddessUpgraded, upgradeDetails);
            output.GoddessUpgradeTopItems = BuildUpgradeTopItems(
                upgradeDetails.Where(x => goddessUpgraded.Contains(x.MemberId)).ToList(), 10);
            output.OtherLifeUpgradeFlow = BuildOtherLifeUpgradeFlow(otherLifeUpgraded, upgradeDetails);
            output.OtherLifeUpgradeTopItems = BuildUpgradeTopItems(
                upgradeDetails.Where(x => otherLifeUpgraded.Contains(x.MemberId)).ToList(), 10);
            output.TechMedicalSupplement = BuildTechMedicalSupplement(
                memberDealType, upgradedMembers, upgradeDetails);
            output.Conclusions = BuildConclusions(output);

            return output;
        }

        private static List<AcquisitionFunnelStepItem> BuildFunnelSteps(
            int leadCount, int arrivalCount, int dealCount, int upgradeCount,
            decimal arrivalRate, decimal dealRate, decimal upgradeRate)
        {
            return new List<AcquisitionFunnelStepItem>
            {
                new AcquisitionFunnelStepItem { Name = "线索", Count = leadCount, RateLabel = "基准 100%" },
                new AcquisitionFunnelStepItem { Name = "到店", Count = arrivalCount, RateLabel = $"到店率 {arrivalRate:F2}%" },
                new AcquisitionFunnelStepItem { Name = "成交", Count = dealCount, RateLabel = $"成交率 {dealRate:F2}%" },
                new AcquisitionFunnelStepItem { Name = "升单", Count = upgradeCount, RateLabel = $"升单率 {upgradeRate:F2}%" }
            };
        }

        private static AcquisitionFunnelDropOffs BuildDropOffs(
            int leadCount, int arrivalCount, int dealCount, int upgradeCount)
        {
            var noArrival = Math.Max(0, leadCount - arrivalCount);
            var arrivalNoDeal = Math.Max(0, arrivalCount - dealCount);
            var dealNoUpgrade = Math.Max(0, dealCount - upgradeCount);

            return new AcquisitionFunnelDropOffs
            {
                NoArrivalCount = noArrival,
                NoArrivalRate = SafePercent(noArrival, leadCount),
                ArrivalNoDealCount = arrivalNoDeal,
                ArrivalNoDealRate = SafePercent(arrivalNoDeal, arrivalCount),
                DealNoUpgradeCount = dealNoUpgrade,
                DealNoUpgradeRate = SafePercent(dealNoUpgrade, dealCount)
            };
        }

        private static List<AcquisitionDealTypeDistributionItem> BuildDealTypeDistribution(
            Dictionary<string, string> memberDealType, int dealCount)
        {
            return AllDealTypes.Select(dealType =>
            {
                var count = memberDealType.Values.Count(x => x == dealType);
                return new AcquisitionDealTypeDistributionItem
                {
                    DealType = dealType,
                    Count = count,
                    Rate = SafePercent(count, dealCount)
                };
            }).ToList();
        }

        private static AcquisitionLifeBeautySplit BuildLifeBeautySplit(
            Dictionary<string, string> memberDealType,
            HashSet<string> upgradedMembers,
            List<BillDetailRow> upgradeDetails,
            HashSet<string> tkGiftItemIdSet)
        {
            var goddessDealMembers = memberDealType.Where(x => x.Value == DealTypeGoddessLife).Select(x => x.Key).ToList();
            var otherLifeDealMembers = memberDealType.Where(x => x.Value == DealTypeOtherLife).Select(x => x.Key).ToList();

            var goddessUpgraded = goddessDealMembers.Count(m => upgradedMembers.Contains(m));
            var otherLifeUpgraded = otherLifeDealMembers.Count(m => upgradedMembers.Contains(m));

            var goddessUpgradeLines = upgradeDetails.Where(x =>
                goddessDealMembers.Contains(x.MemberId) && upgradedMembers.Contains(x.MemberId)).ToList();
            var otherLifeUpgradeLines = upgradeDetails.Where(x =>
                otherLifeDealMembers.Contains(x.MemberId) && upgradedMembers.Contains(x.MemberId)).ToList();

            return new AcquisitionLifeBeautySplit
            {
                GoddessDealCount = goddessDealMembers.Count,
                GoddessUpgradeCount = goddessUpgraded,
                GoddessUpgradeRate = SafePercent(goddessUpgraded, goddessDealMembers.Count),
                GoddessUpgradeGoddessLineCount = CountLifeBeautyLines(goddessUpgradeLines, tkGiftItemIdSet, true),
                GoddessUpgradeOtherLifeLineCount = CountLifeBeautyLines(goddessUpgradeLines, tkGiftItemIdSet, false),
                OtherLifeDealCount = otherLifeDealMembers.Count,
                OtherLifeUpgradeCount = otherLifeUpgraded,
                OtherLifeUpgradeRate = SafePercent(otherLifeUpgraded, otherLifeDealMembers.Count),
                OtherLifeUpgradeGoddessLineCount = CountLifeBeautyLines(otherLifeUpgradeLines, tkGiftItemIdSet, true),
                OtherLifeUpgradeOtherLifeLineCount = CountLifeBeautyLines(otherLifeUpgradeLines, tkGiftItemIdSet, false)
            };
        }

        private static int CountLifeBeautyLines(
            List<BillDetailRow> lines,
            HashSet<string> tkGiftItemIdSet,
            bool goddessLines)
        {
            return lines.Count(x =>
                string.Equals(x.ItemCategory?.Trim(), LifeBeautyCategory, StringComparison.Ordinal) &&
                ItemCategoryRuleHelper.IsTkGiftItem(x.ItemId, tkGiftItemIdSet) == goddessLines);
        }

        private static List<AcquisitionDealTypeUpgradeRateItem> BuildDealTypeUpgradeRates(
            Dictionary<string, string> memberDealType,
            HashSet<string> upgradedMembers)
        {
            return AllDealTypes.Select(dealType =>
            {
                var dealMembers = memberDealType.Where(x => x.Value == dealType).Select(x => x.Key).ToList();
                var upgradeCount = dealMembers.Count(m => upgradedMembers.Contains(m));
                return new AcquisitionDealTypeUpgradeRateItem
                {
                    DealType = dealType,
                    DealCount = dealMembers.Count,
                    UpgradeCount = upgradeCount,
                    UpgradeRate = SafePercent(upgradeCount, dealMembers.Count)
                };
            }).ToList();
        }

        private static AcquisitionGoddessUpgradeFlow BuildGoddessUpgradeFlow(
            HashSet<string> upgradedMembers,
            List<BillDetailRow> upgradeDetails)
        {
            var lines = upgradeDetails.Where(x => upgradedMembers.Contains(x.MemberId)).ToList();
            var lifeCount = CountDistinctMembersByCategory(lines, LifeBeautyCategory);
            var techCount = CountDistinctMembersByCategory(lines, TechBeautyCategory);
            var medicalCount = CountDistinctMembersByCategory(lines, MedicalBeautyCategory);

            return new AcquisitionGoddessUpgradeFlow
            {
                LifeBeautyCustomerCount = lifeCount,
                TechBeautyCustomerCount = techCount,
                MedicalBeautyCustomerCount = medicalCount,
                FlowSummary = BuildFlowSummary("女神卡首单", lifeCount, techCount, medicalCount)
            };
        }

        private static AcquisitionOtherLifeUpgradeFlow BuildOtherLifeUpgradeFlow(
            HashSet<string> upgradedMembers,
            List<BillDetailRow> upgradeDetails)
        {
            var lines = upgradeDetails.Where(x => upgradedMembers.Contains(x.MemberId)).ToList();
            var lifeCount = CountDistinctMembersByCategory(lines, LifeBeautyCategory);
            var techCount = CountDistinctMembersByCategory(lines, TechBeautyCategory);
            var medicalCount = CountDistinctMembersByCategory(lines, MedicalBeautyCategory);

            return new AcquisitionOtherLifeUpgradeFlow
            {
                LifeBeautyCustomerCount = lifeCount,
                TechBeautyCustomerCount = techCount,
                MedicalBeautyCustomerCount = medicalCount,
                FlowSummary = BuildFlowSummary("其他生美首单", lifeCount, techCount, medicalCount)
            };
        }

        private static AcquisitionTechMedicalSupplement BuildTechMedicalSupplement(
            Dictionary<string, string> memberDealType,
            HashSet<string> upgradedMembers,
            List<BillDetailRow> upgradeDetails)
        {
            var techDealMembers = memberDealType.Where(x => x.Value == DealTypeTech).Select(x => x.Key).ToList();
            var medicalDealMembers = memberDealType.Where(x => x.Value == DealTypeMedical).Select(x => x.Key).ToList();
            var techFirstUpgraded = techDealMembers.Where(upgradedMembers.Contains).ToHashSet(StringComparer.Ordinal);
            var medicalFirstUpgraded = medicalDealMembers.Where(upgradedMembers.Contains).ToHashSet(StringComparer.Ordinal);

            var destLines = upgradeDetails
                .Where(x => upgradedMembers.Contains(x.MemberId))
                .ToList();
            var techDestLines = destLines
                .Where(x => string.Equals(x.ItemCategory?.Trim(), TechBeautyCategory, StringComparison.Ordinal))
                .ToList();
            var medicalDestLines = destLines
                .Where(x => string.Equals(x.ItemCategory?.Trim(), MedicalBeautyCategory, StringComparison.Ordinal))
                .ToList();
            var techDestCount = techDestLines
                .Select(x => x.MemberId)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Distinct(StringComparer.Ordinal)
                .Count();
            var medicalDestCount = medicalDestLines
                .Select(x => x.MemberId)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Distinct(StringComparer.Ordinal)
                .Count();

            return new AcquisitionTechMedicalSupplement
            {
                TechDealCount = techDealMembers.Count,
                TechUpgradeCount = Math.Max(techFirstUpgraded.Count, techDestCount),
                TechUpgradeRate = SafePercent(techFirstUpgraded.Count, techDealMembers.Count),
                TechFlowSummary = techDestCount > 0
                    ? $"升单进入科美 {techDestCount} 人(首单为科美 {techDealMembers.Count} 人)"
                    : BuildFlowSummary("科美首单",
                        CountDistinctMembersByCategory(upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), LifeBeautyCategory),
                        CountDistinctMembersByCategory(upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), TechBeautyCategory),
                        CountDistinctMembersByCategory(upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), MedicalBeautyCategory)),
                TechUpgradeTopItems = BuildUpgradeTopItems(techDestLines.Any() ? techDestLines : upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), 10),
                MedicalDealCount = medicalDealMembers.Count,
                MedicalUpgradeCount = Math.Max(medicalFirstUpgraded.Count, medicalDestCount),
                MedicalUpgradeRate = SafePercent(medicalFirstUpgraded.Count, medicalDealMembers.Count),
                MedicalFlowSummary = medicalDestCount > 0
                    ? $"升单进入医美 {medicalDestCount} 人(首单为医美 {medicalDealMembers.Count} 人)"
                    : BuildFlowSummary("医美首单",
                        CountDistinctMembersByCategory(upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), LifeBeautyCategory),
                        CountDistinctMembersByCategory(upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), TechBeautyCategory),
                        CountDistinctMembersByCategory(upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), MedicalBeautyCategory)),
                MedicalUpgradeTopItems = BuildUpgradeTopItems(medicalDestLines.Any() ? medicalDestLines : upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), 10)
            };
        }

        private static List<AcquisitionUpgradeTopItem> BuildUpgradeTopItems(List<BillDetailRow> lines, int topN)
        {
            return lines
                .GroupBy(x => new
                {
                    ItemId = x.ItemId ?? string.Empty,
                    ItemName = string.IsNullOrWhiteSpace(x.ItemName) ? "无" : x.ItemName.Trim(),
                    ItemCategory = x.ItemCategory ?? string.Empty
                })
                .Select(g => new AcquisitionUpgradeTopItem
                {
                    ItemId = g.Key.ItemId,
                    ItemName = g.Key.ItemName,
                    ItemCategory = string.IsNullOrWhiteSpace(g.Key.ItemCategory) ? "无" : g.Key.ItemCategory,
                    CustomerCount = g.Select(x => x.MemberId).Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().Count(),
                    LineCount = g.Count()
                })
                .OrderByDescending(x => x.LineCount)
                .ThenByDescending(x => x.CustomerCount)
                .Take(topN)
                .ToList();
        }

        private static int CountDistinctMembersByCategory(List<BillDetailRow> lines, string category)
        {
            return lines
                .Where(x => string.Equals(x.ItemCategory?.Trim(), category, StringComparison.Ordinal))
                .Select(x => x.MemberId)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Distinct(StringComparer.Ordinal)
                .Count();
        }

        private static string BuildFlowSummary(string prefix, int lifeCount, int techCount, int medicalCount)
        {
            return $"{prefix}升单客户流向:生美 {lifeCount} 人、科美 {techCount} 人、医美 {medicalCount} 人";
        }

        private static List<string> BuildConclusions(EducationDepartmentDashboardAcquisitionFunnelOutput output)
        {
            var kpis = output.SummaryKpis;
            var dropOffs = output.DropOffs;
            var goddessSplit = output.LifeBeautySplit;
            var conclusions = new List<string>
            {
                $"统计期内共获取线索 {kpis.LeadCount} 人,到店率 {kpis.ArrivalRate:F2}%,线索→成交转化率 {kpis.LeadToDealRate:F2}%。",
                $"成交客户 {kpis.DealCount} 人,其中 90 天内升单 {kpis.UpgradeCount} 人,整体升单率 {kpis.UpgradeRate:F2}%。",
                $"未到店流失 {dropOffs.NoArrivalCount} 人(占线索 {dropOffs.NoArrivalRate:F2}%),到店未成交 {dropOffs.ArrivalNoDealCount} 人(占到店 {dropOffs.ArrivalNoDealRate:F2}%)。"
            };

            if (goddessSplit.GoddessDealCount + goddessSplit.OtherLifeDealCount > 0)
            {
                conclusions.Add(
                    $"生美成交中女神卡 {goddessSplit.GoddessDealCount} 人(升单率 {goddessSplit.GoddessUpgradeRate:F2}%),其他生美 {goddessSplit.OtherLifeDealCount} 人(升单率 {goddessSplit.OtherLifeUpgradeRate:F2}%)。");
            }

            conclusions.Add(
                "升单按首单成交日后 90 天内再次开单统计,筛选区间末段成交客户的升单可能被观察窗截断。");

            return conclusions.Take(5).ToList();
        }

        private static string BuildMetricNote(HashSet<string> tkGiftItemIdSet)
        {
            var ids = tkGiftItemIdSet.Any() ? string.Join(",", tkGiftItemIdSet) : ItemCategoryRuleHelper.DefaultTkGiftItemIds;
            return "线索=拓客管理按会员ID去重(不含调整明细);到店=线索会员在区间内有有效耗卡;成交=线索会员在区间内有有效开单(F_IsEffective=1且实付业绩>0);"
                   + "成交类型按区间内最早一笔开单判定:含配置女神卡品项ID→生美-女神卡,否则按该单实付金额最大明细的品项分类;"
                   + $"女神卡品项ID={ids};升单=首单后90天内不同开单编号再次成交(观察窗可超出筛选结束日)。";
        }

        private static EducationDepartmentDashboardAcquisitionFunnelOutput BuildEmptyAcquisitionFunnelOutput()
        {
            var output = new EducationDepartmentDashboardAcquisitionFunnelOutput
            {
                SummaryKpis = new AcquisitionFunnelSummaryKpis(),
                FunnelSteps = BuildFunnelSteps(0, 0, 0, 0, 0m, 0m, 0m),
                DropOffs = BuildDropOffs(0, 0, 0, 0),
                DealTypeDistribution = BuildDealTypeDistribution(new Dictionary<string, string>(), 0),
                LifeBeautySplit = new AcquisitionLifeBeautySplit(),
                DealTypeUpgradeRates = BuildDealTypeUpgradeRates(new Dictionary<string, string>(), new HashSet<string>()),
                GoddessUpgradeFlow = new AcquisitionGoddessUpgradeFlow { FlowSummary = "暂无数据" },
                OtherLifeUpgradeFlow = new AcquisitionOtherLifeUpgradeFlow { FlowSummary = "暂无数据" },
                TechMedicalSupplement = new AcquisitionTechMedicalSupplement
                {
                    TechFlowSummary = "暂无数据",
                    MedicalFlowSummary = "暂无数据"
                },
                MetricNote = BuildMetricNote(new HashSet<string> { ItemCategoryRuleHelper.DefaultTkGiftItemIds })
            };
            output.Conclusions = new List<string> { "当前筛选条件下暂无拓客漏斗数据。" };
            return output;
        }

        private static decimal SafePercent(int numerator, int denominator)
        {
            if (denominator <= 0) return 0m;
            return Math.Round((decimal)numerator / denominator * 100m, 2);
        }

        private class MemberBillRow
        {
            public string BillId { get; set; }
            public string MemberId { get; set; }
            public DateTime BillingDate { get; set; }
        }

        private class LeadRecordRow
        {
            public string StoreId { get; set; }
            public string MemberId { get; set; }
            public DateTime ExpansionTime { get; set; }
            public string CustomerName { get; set; }
            public string CustomerPhone { get; set; }
        }

        private class AcquisitionFunnelFacts
        {
            public List<LeadRecordRow> LeadRecords { get; set; } = new List<LeadRecordRow>();
            public HashSet<string> LeadSet { get; set; } = new HashSet<string>(StringComparer.Ordinal);
            public HashSet<string> ArrivalSet { get; set; } = new HashSet<string>(StringComparer.Ordinal);
            public HashSet<string> DealSet { get; set; } = new HashSet<string>(StringComparer.Ordinal);
            public HashSet<string> UpgradedMembers { get; set; } = new HashSet<string>(StringComparer.Ordinal);
            public Dictionary<string, string> MemberDealType { get; set; } = new Dictionary<string, string>(StringComparer.Ordinal);
            public Dictionary<string, DateTime> FirstBillDateByMember { get; set; } = new Dictionary<string, DateTime>(StringComparer.Ordinal);
            public List<BillDetailRow> UpgradeDetails { get; set; } = new List<BillDetailRow>();
            public HashSet<string> TkGiftItemIdSet { get; set; } = new HashSet<string>(StringComparer.Ordinal);
        }

        private class BillDetailRow
        {
            public string BillId { get; set; }
            public string MemberId { get; set; }
            public string ItemId { get; set; }
            public string ItemName { get; set; }
            public string ItemCategory { get; set; }
            public decimal ActualPrice { get; set; }
        }
    }
}