TeamMemberAppService.cs 40 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 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
using System.IO;
using FoodLabeling.Application.Contracts.Dtos.Common;
using FoodLabeling.Application.Contracts.Dtos.TeamMember;
using FoodLabeling.Application.Contracts.IServices;
using FoodLabeling.Application.Helpers;
using FoodLabeling.Application.Options;
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Guids;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Entities.ValueObjects;
using Yi.Framework.Rbac.Domain.Helpers;
using Yi.Framework.Rbac.Domain.Managers;
using Yi.Framework.SqlSugarCore.Abstractions;

namespace FoodLabeling.Application.Services;

/// <summary>
/// 成员(Team Member)服务,对外仅在 food-labeling-us 暴露
/// </summary>
public class TeamMemberAppService : ApplicationService, ITeamMemberAppService
{
    private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
    private readonly UserManager _userManager;
    private readonly ISqlSugarDbContext _dbContext;
    private readonly IGuidGenerator _guidGenerator;
    private readonly IOptionsSnapshot<FoodLabelingBatchImportOptions> _batchImportOptions;

    public TeamMemberAppService(
        ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
        UserManager userManager,
        ISqlSugarDbContext dbContext,
        IGuidGenerator guidGenerator,
        IOptionsSnapshot<FoodLabelingBatchImportOptions> batchImportOptions)
    {
        _userRepository = userRepository;
        _userManager = userManager;
        _dbContext = dbContext;
        _guidGenerator = guidGenerator;
        _batchImportOptions = batchImportOptions;
    }

    /// <inheritdoc />
    public async Task<PagedResultWithPageDto<TeamMemberGetListOutputDto>> GetListAsync(TeamMemberGetListInputVo input)
    {
        var pageIndex = PagedQueryConvention.PageIndexFromSkipCount(input.SkipCount);
        var pageSize = input.MaxResultCount;
        RefAsync<int> total = 0;

        var scopeLocationIds = await TeamMemberListScopeHelper.ResolveListLocationIdsAsync(
            CurrentUser,
            _dbContext,
            input.PartnerId,
            input.GroupId,
            input.LocationId);

        var query = await BuildFilteredUserQueryAsync(input, scopeLocationIds);
        var users = await query
            .OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
            .OrderByDescending(u => u.CreationTime)
            .ToPageListAsync(input.SkipCount, input.MaxResultCount, total);

        var items = await MapUsersToOutputAsync(
            users,
            scopeLocationIds,
            restrictAssignedLocationsToFilter: scopeLocationIds is not null);

        var totalCount = (long)total;
        return new PagedResultWithPageDto<TeamMemberGetListOutputDto>
        {
            PageIndex = pageIndex,
            PageSize = pageSize,
            TotalCount = totalCount,
            TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
            Items = items
        };
    }

    /// <inheritdoc />
    public async Task<TeamMemberGetOutputDto> GetAsync(Guid id)
    {
        var user = await _userRepository.GetByIdAsync(id);
        if (user is null || user.IsDeleted)
        {
            throw new UserFriendlyException("成员不存在");
        }

        var userIdString = id.ToString();
        var links = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
            .Where(x => !x.IsDeleted && x.UserId == userIdString)
            .ToListAsync();

        var locationIds = links.Select(x => x.LocationId).Distinct().ToList();
        var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
            .Where(x => !x.IsDeleted)
            .WhereIF(locationIds.Count > 0, x => locationIds.Contains(x.Id.ToString()))
            .Select(x => new { x.Id, x.LocationCode, x.LocationName })
            .ToListAsync();

        var assigned = locations.Select(x => new TeamMemberAssignedLocationDto
        {
            Id = x.Id.ToString(),
            LocationCode = x.LocationCode,
            LocationName = x.LocationName
        }).ToList();

        var role = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity>().FirstAsync(x => x.UserId == id);

        var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
            _dbContext.SqlSugarClient, locationIds);
        var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
            _dbContext.SqlSugarClient, locationIds);

        if (await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(_dbContext.SqlSugarClient, role?.RoleId) &&
            partnerIds.Count > 0)
        {
            (regionIds, assigned) = await ApplyCompanyAdminDisplayScopeAsync(
                role?.RoleId, partnerIds, regionIds, assigned);
            locationIds = assigned.Select(x => x.Id).ToList();
        }

        return new TeamMemberGetOutputDto
        {
            Id = user.Id,
            FullName = user.Name ?? string.Empty,
            UserName = user.UserName,
            Email = user.Email,
            Phone = user.Phone,
            State = user.State,
            RoleId = role?.RoleId,
            PartnerIds = partnerIds,
            RegionIds = regionIds,
            GroupIds = regionIds,
            LocationIds = locationIds,
            AssignedLocations = assigned
        };
    }

    /// <inheritdoc />
    public async Task<TeamMemberGetOutputDto> CreateAsync(TeamMemberCreateInputVo input)
    {
        var mergedLocationIds = await ResolveTeamMemberLocationIdsForSaveAsync(input, input.RoleId);

        var user = new UserAggregateRoot
        {
            UserName = input.UserName.Trim(),
            Name = input.FullName.Trim(),
            Nick = input.FullName.Trim(),
            Email = input.Email?.Trim(),
            Phone = input.Phone,
            State = input.State,
            EncryPassword = new EncryPasswordValueObject(input.Password.Trim())
        };

        EntityHelper.TrySetId(user, _guidGenerator.Create);
        user.BuildPassword();

        await _userManager.CreateAsync(user);

        if (input.RoleId != null)
        {
            await _userManager.GiveUserSetRoleAsync(new List<Guid> { user.Id }, new List<Guid> { input.RoleId.Value });
        }

        await UpsertUserLocationsAsync(user.Id, mergedLocationIds);

        return await GetAsync(user.Id);
    }

    /// <inheritdoc />
    public async Task<TeamMemberGetOutputDto> UpdateAsync(Guid id, TeamMemberUpdateInputVo input)
    {
        var mergedLocationIds = await ResolveTeamMemberLocationIdsForSaveAsync(input);

        var user = await _userRepository.GetByIdAsync(id);
        if (user is null || user.IsDeleted)
        {
            throw new UserFriendlyException("成员不存在");
        }

        user.Name = input.FullName.Trim();
        user.UserName = input.UserName.Trim();
        user.Email = input.Email?.Trim();
        user.Phone = input.Phone;
        user.State = input.State;

        var passwordChanged = false;
        if (!string.IsNullOrWhiteSpace(input.Password))
        {
            UserPasswordHelper.ApplyPlainPassword(user, input.Password);
            passwordChanged = true;
        }

        await _userRepository.UpdateAsync(user);
        if (passwordChanged)
        {
            await UserPasswordHelper.EnsurePasswordColumnsPersistedAsync(
                _userRepository,
                user.Id,
                user.EncryPassword.Password,
                user.EncryPassword.Salt);
        }

        if (input.RoleId != null)
        {
            await _userManager.GiveUserSetRoleAsync(new List<Guid> { id }, new List<Guid> { input.RoleId.Value });
        }
        else
        {
            await _userManager.GiveUserSetRoleAsync(new List<Guid> { id }, new List<Guid>());
        }

        await UpsertUserLocationsAsync(id, mergedLocationIds);

        return await GetAsync(id);
    }

    /// <inheritdoc />
    public async Task DeleteAsync(Guid id)
    {
        var user = await _userRepository.GetByIdAsync(id);
        if (user is null || user.IsDeleted)
        {
            return;
        }

        user.IsDeleted = true;
        await _userRepository.UpdateAsync(user);

        var userIdString = id.ToString();
        var currentUserId = CurrentUser?.Id?.ToString();
        await _dbContext.SqlSugarClient.Updateable<UserLocationDbEntity>()
            .SetColumns(x => new UserLocationDbEntity
            {
                IsDeleted = true,
                LastModificationTime = DateTime.Now,
                LastModifierId = currentUserId
            })
            .Where(x => x.UserId == userIdString && !x.IsDeleted)
            .ExecuteCommandAsync();
    }

    /// <inheritdoc />
    public Task<IActionResult> DownloadTeamMemberImportTemplateAsync()
    {
        var opt = _batchImportOptions.Value;
        var fileName = opt.TeamMemberTemplateFileName?.Trim();
        if (string.IsNullOrWhiteSpace(fileName))
        {
            fileName = "Team-Member-批量导入模板.xlsx";
        }

        var stream = TeamMemberBatchExcelHelper.BuildImportTemplateWorkbook();
        const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        return Task.FromResult<IActionResult>(new FileStreamResult(stream, contentType)
        {
            FileDownloadName = fileName
        });
    }

    /// <inheritdoc />
    public async Task<IActionResult> ExportTeamMembersPdfAsync([FromQuery] TeamMemberGetListInputVo input)
    {
        QuestPDF.Settings.License = LicenseType.Community;

        var scopeLocationIds = await TeamMemberListScopeHelper.ResolveListLocationIdsAsync(
            CurrentUser,
            _dbContext,
            input.PartnerId,
            input.GroupId,
            input.LocationId);

        var query = await BuildFilteredUserQueryAsync(input, scopeLocationIds);
        var users = await query
            .OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
            .OrderByDescending(u => u.CreationTime)
            .ToListAsync();

        var rows = await MapUsersToOutputAsync(
            users,
            scopeLocationIds,
            restrictAssignedLocationsToFilter: scopeLocationIds is not null);

        var regionNameMap = await LoadRegionNameMapAsync(
            rows.SelectMany(r => r.RegionIds).Distinct(StringComparer.Ordinal));

        var fileName = $"team-members_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf";
        var document = Document.Create(container =>
        {
            container.Page(page =>
            {
                page.Margin(22);
                page.DefaultTextStyle(x => x.FontSize(8));
                page.Header().Text("Team Members").SemiBold().FontSize(16);
                page.Content().PaddingTop(8).Table(table =>
                {
                    table.ColumnsDefinition(c =>
                    {
                        c.RelativeColumn(1.3f);
                        c.RelativeColumn(1.5f);
                        c.RelativeColumn(1.0f);
                        c.RelativeColumn(1.0f);
                        c.RelativeColumn(1.4f);
                        c.RelativeColumn(2.0f);
                        c.RelativeColumn(0.7f);
                    });

                    static IContainer CellHeader(IContainer c) =>
                        c.Background(Colors.Grey.Lighten3).Padding(4).DefaultTextStyle(x => x.SemiBold());

                    table.Cell().Element(CellHeader).Text("Name");
                    table.Cell().Element(CellHeader).Text("Email");
                    table.Cell().Element(CellHeader).Text("Phone");
                    table.Cell().Element(CellHeader).Text("Role");
                    table.Cell().Element(CellHeader).Text("Region");
                    table.Cell().Element(CellHeader).Text("Assigned Locations");
                    table.Cell().Element(CellHeader).Text("Status");

                    foreach (var e in rows)
                    {
                        var regionText = e.RegionIds.Count == 0
                            ? "无"
                            : string.Join("; ",
                                e.RegionIds.Select(id =>
                                    regionNameMap.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name)
                                        ? name
                                        : id));
                        var locText = e.AssignedLocations.Count == 0
                            ? "无"
                            : string.Join("; ",
                                e.AssignedLocations.Select(a =>
                                    $"{a.LocationCode} - {a.LocationName}"));
                        var status = e.State ? "Active" : "Inactive";
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(e.FullName ?? string.Empty);
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(e.Email ?? "无");
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(e.Phone?.ToString() ?? "无");
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(string.IsNullOrWhiteSpace(e.RoleName) ? "无" : e.RoleName);
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(regionText);
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(locText);
                        table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
                            .Text(status);
                    }
                });
            });
        });

        var stream = new MemoryStream();
        document.GeneratePdf(stream);
        stream.Position = 0;
        return new FileStreamResult(stream, "application/pdf") { FileDownloadName = fileName };
    }

    /// <inheritdoc />
    public async Task<TeamMemberBatchImportResultDto> ImportTeamMembersBatchAsync(
        [FromForm] TeamMemberBatchImportInputVo input)
    {
        if (input?.File is null || input.File.Length == 0)
        {
            throw new UserFriendlyException("请上传 Excel 文件(form 字段名:file)");
        }

        var opt = _batchImportOptions.Value;
        if (input.File.Length > opt.MaxUploadBytes)
        {
            throw new UserFriendlyException($"文件过大,最大允许 {opt.MaxUploadBytes / 1024 / 1024} MB");
        }

        var ext = Path.GetExtension(input.File.FileName)?.ToLowerInvariant();
        if (ext != ".xlsx")
        {
            throw new UserFriendlyException("仅支持 .xlsx 格式的 Excel 文件");
        }

        var roleMap = await BuildRoleNameToIdMapAsync();
        await using var uploadStream = input.File.OpenReadStream();
        var parseErrors = new List<TeamMemberBatchImportErrorDto>();
        var rows = TeamMemberBatchExcelHelper.ParseImportWorkbook(
            uploadStream,
            opt.MaxImportRows <= 0 ? 5000 : opt.MaxImportRows,
            roleMap,
            opt.TeamMemberImportDefaultPassword?.Trim() ?? string.Empty,
            out var headerErrors);
        parseErrors.AddRange(headerErrors);

        var result = new TeamMemberBatchImportResultDto();
        if (rows.Count == 0 && parseErrors.Count > 0)
        {
            result.Errors = parseErrors;
            result.FailCount = parseErrors.Count;
            return result;
        }

        foreach (var (rowNum, vo) in rows)
        {
            try
            {
                if (vo.RegionIds is { Count: > 0 })
                {
                    vo.RegionIds = await ResolveRegionIdsFromImportTokensAsync(vo.RegionIds);
                }

                if (vo.LocationIds is { Count: > 0 })
                {
                    vo.LocationIds = await ResolveLocationIdsFromImportTokensAsync(vo.LocationIds);
                }

                await CreateAsync(vo);
                result.SuccessCount++;
            }
            catch (UserFriendlyException ex)
            {
                result.FailCount++;
                result.Errors.Add(new TeamMemberBatchImportErrorDto
                {
                    RowNumber = rowNum,
                    UserName = vo.UserName,
                    Message = ex.Message
                });
            }
        }

        result.Errors.InsertRange(0, parseErrors);
        return result;
    }

    /// <inheritdoc />
    public async Task<TeamMemberBulkUpdateResultDto> UpdateTeamMembersBulkAsync(
        [FromBody] TeamMemberBulkUpdateInputVo input)
    {
        if (input?.Items is null || input.Items.Count == 0)
        {
            throw new UserFriendlyException("请至少提交一条编辑数据(items 不能为空)");
        }

        var opt = _batchImportOptions.Value;
        var maxItems = opt.MaxBulkUpdateItems <= 0 ? 500 : opt.MaxBulkUpdateItems;
        if (input.Items.Count > maxItems)
        {
            throw new UserFriendlyException($"单次批量编辑最多允许 {maxItems} 条,请分批提交");
        }

        var effectiveCount = input.Items.Count(static x => x is not null && x.Id != Guid.Empty);
        if (effectiveCount == 0)
        {
            throw new UserFriendlyException("没有有效的成员 Id(请为待保存行填写 id)");
        }

        var result = new TeamMemberBulkUpdateResultDto();
        for (var i = 0; i < input.Items.Count; i++)
        {
            var item = input.Items[i];
            if (item is null || item.Id == Guid.Empty)
            {
                continue;
            }

            try
            {
                await UpdateAsync(item.Id, item);
                result.SuccessCount++;
            }
            catch (UserFriendlyException ex)
            {
                result.FailCount++;
                result.Errors.Add(new TeamMemberBulkUpdateErrorDto
                {
                    RowNumber = i + 1,
                    Id = item.Id,
                    Message = ex.Message
                });
            }
        }

        return result;
    }

    private async Task<Dictionary<string, Guid>> BuildRoleNameToIdMapAsync()
    {
        var roles = await _dbContext.SqlSugarClient.Queryable<RoleAggregateRoot>()
            .Where(r => !r.IsDeleted)
            .Select(r => new { r.Id, r.RoleName })
            .ToListAsync();

        return roles
            .Where(r => !string.IsNullOrWhiteSpace(r.RoleName))
            .GroupBy(r => TeamMemberBatchExcelHelper.NormalizeRoleKey(r.RoleName!))
            .ToDictionary(g => g.Key, g => g.First().Id);
    }

    private async Task<List<string>> ResolveLocationIdsFromImportTokensAsync(List<string> tokens)
    {
        var result = new List<string>();
        foreach (var raw in tokens)
        {
            var s = raw.Trim();
            if (string.IsNullOrEmpty(s))
            {
                continue;
            }

            var idx = s.IndexOf(" -", StringComparison.Ordinal);
            var key = idx > 0 ? s[..idx].Trim() : s.Trim();
            if (Guid.TryParse(key, out var gid))
            {
                var byId = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
                    .Where(x => !x.IsDeleted && x.Id == gid)
                    .FirstAsync();
                if (byId is null)
                {
                    throw new UserFriendlyException($"无效门店 Id:{key}");
                }

                result.Add(byId.Id.ToString());
                continue;
            }

            var byCode = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
                .Where(x => !x.IsDeleted && x.LocationCode == key)
                .FirstAsync();
            if (byCode is null)
            {
                throw new UserFriendlyException($"未找到门店 LocationCode:{key}(亦可填 location.Id Guid)");
            }

            result.Add(byCode.Id.ToString());
        }

        return result.Distinct().ToList();
    }

    private async Task<List<string>> ResolveRegionIdsFromImportTokensAsync(List<string> tokens)
    {
        var result = new List<string>();
        foreach (var raw in tokens)
        {
            var s = raw.Trim();
            if (string.IsNullOrEmpty(s))
            {
                continue;
            }

            var idx = s.IndexOf(" -", StringComparison.Ordinal);
            var key = idx > 0 ? s[..idx].Trim() : s.Trim();

            if (Guid.TryParse(key, out _))
            {
                var byId = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
                    .Where(x => !x.IsDeleted && x.Id == key)
                    .FirstAsync();
                if (byId is null)
                {
                    throw new UserFriendlyException($"无效 Region Id:{key}");
                }

                result.Add(byId.Id.Trim());
                continue;
            }

            var matches = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
                .Where(x => !x.IsDeleted)
                .ToListAsync();
            matches = matches
                .Where(x => string.Equals(x.GroupName?.Trim(), key, StringComparison.OrdinalIgnoreCase))
                .ToList();

            if (matches.Count == 0)
            {
                throw new UserFriendlyException($"未找到 Region:{key}(可填 fl_group.Id 或 GroupName)");
            }

            if (matches.Count > 1)
            {
                throw new UserFriendlyException(
                    $"Region 名称「{key}」存在多条记录,请改用 fl_group.Id(Guid)");
            }

            result.Add(matches[0].Id.Trim());
        }

        return result.Distinct(StringComparer.Ordinal).ToList();
    }

    private async Task<Dictionary<string, string>> LoadRegionNameMapAsync(IEnumerable<string> regionIds)
    {
        var ids = regionIds
            .Where(x => !string.IsNullOrWhiteSpace(x))
            .Select(x => x.Trim())
            .Distinct(StringComparer.Ordinal)
            .ToList();
        if (ids.Count == 0)
        {
            return new Dictionary<string, string>(StringComparer.Ordinal);
        }

        var groups = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
            .Where(x => !x.IsDeleted && ids.Contains(x.Id))
            .Select(x => new { x.Id, x.GroupName })
            .ToListAsync();

        return groups
            .Where(x => !string.IsNullOrWhiteSpace(x.Id))
            .ToDictionary(
                x => x.Id.Trim(),
                x => x.GroupName?.Trim() ?? x.Id.Trim(),
                StringComparer.Ordinal);
    }

    private async Task<ISugarQueryable<UserAggregateRoot>> BuildFilteredUserQueryAsync(
        TeamMemberGetListInputVo input,
        List<string>? scopeLocationIds)
    {
        var keyword = input.Keyword?.Trim();
        var query = _userRepository._DbQueryable
            .Where(u => !u.IsDeleted)
            .WhereIF(!string.IsNullOrWhiteSpace(keyword),
                u => (u.Name != null && u.Name.Contains(keyword!)) ||
                     u.UserName.Contains(keyword!) ||
                     (u.Email != null && u.Email.Contains(keyword!)) ||
                     (u.Phone != null && u.Phone.ToString()!.Contains(keyword!)))
            .WhereIF(input.State != null, u => u.State == input.State);

        if (input.RoleId != null)
        {
            var userIds = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity>()
                .Where(ur => ur.RoleId == input.RoleId.Value)
                .Select(ur => ur.UserId)
                .ToListAsync();
            query = query.Where(u => userIds.Contains(u.Id));
        }

        if (scopeLocationIds is not null)
        {
            if (scopeLocationIds.Count == 0)
            {
                query = query.Where(_ => false);
            }
            else
            {
                var scopeGuidSet = TeamMemberListScopeHelper.ParseGuidHashSet(scopeLocationIds);
                var userLocationLinks = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
                    .Where(x => !x.IsDeleted)
                    .Select(x => new { x.UserId, x.LocationId })
                    .ToListAsync();

                var allowedUserGuids = userLocationLinks
                    .Where(x =>
                        Guid.TryParse(x.LocationId, out var locGuid) && scopeGuidSet.Contains(locGuid))
                    .Select(x => x.UserId)
                    .Select(TeamMemberListScopeHelper.NormalizeScopeKey)
                    .Where(x => !string.IsNullOrEmpty(x))
                    .Select(x => Guid.Parse(x))
                    .Distinct()
                    .ToList();

                if (allowedUserGuids.Count == 0)
                {
                    query = query.Where(_ => false);
                }
                else
                {
                    query = query.Where(u => allowedUserGuids.Contains(u.Id));
                }
            }
        }

        return query;
    }

    private async Task<List<TeamMemberGetListOutputDto>> MapUsersToOutputAsync(
        List<UserAggregateRoot> users,
        List<string>? scopeLocationIds,
        bool restrictAssignedLocationsToFilter)
    {
        if (users.Count == 0)
        {
            return new List<TeamMemberGetListOutputDto>();
        }

        var userIds = users.Select(x => x.Id).ToList();
        var userGuidKeys = userIds.Select(TeamMemberListScopeHelper.UserKey).ToHashSet(StringComparer.Ordinal);

        var userRolePairs = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity, RoleAggregateRoot>((ur, r) => ur.RoleId == r.Id)
            .Where(ur => userIds.Contains(ur.UserId))
            .Select((ur, r) => new { ur.UserId, r.Id, r.RoleName })
            .ToListAsync();

        var roleIdByUser = userRolePairs
            .GroupBy(x => x.UserId)
            .ToDictionary(g => g.Key, g => (Guid?)g.First().Id);

        var allUserLocations = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
            .Where(x => !x.IsDeleted)
            .Select(x => new { x.UserId, x.LocationId })
            .ToListAsync();

        var scopeGuidSet = scopeLocationIds is { Count: > 0 }
            ? TeamMemberListScopeHelper.ParseGuidHashSet(scopeLocationIds)
            : null;

        var userLocations = allUserLocations
            .Where(x => userGuidKeys.Contains(TeamMemberListScopeHelper.NormalizeScopeKey(x.UserId)))
            .Where(x =>
                scopeGuidSet is null ||
                (Guid.TryParse(x.LocationId, out var locGuid) && scopeGuidSet.Contains(locGuid)))
            .ToList();

        var locationIds = userLocations.Select(x => x.LocationId).Distinct().ToList();
        var locationGuidList = TeamMemberListScopeHelper.ParseGuidList(locationIds);
        var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
            .Where(x => !x.IsDeleted)
            .WhereIF(locationGuidList.Count > 0, x => locationGuidList.Contains(x.Id))
            .Select(x => new { x.Id, x.LocationCode, x.LocationName })
            .ToListAsync();
        var locationMap = locations.ToDictionary(
            x => TeamMemberListScopeHelper.UserKey(x.Id),
            x => x);

        var assignedMap = userLocations
            .GroupBy(x => TeamMemberListScopeHelper.NormalizeScopeKey(x.UserId))
            .ToDictionary(
                g => g.Key,
                g => g.Select(x =>
                {
                    var locKey = TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId);
                    if (locationMap.TryGetValue(locKey, out var loc))
                    {
                        return new TeamMemberAssignedLocationDto
                        {
                            Id = loc.Id.ToString(),
                            LocationCode = loc.LocationCode,
                            LocationName = loc.LocationName
                        };
                    }

                    if (locationMap.TryGetValue(x.LocationId, out loc))
                    {
                        return new TeamMemberAssignedLocationDto
                        {
                            Id = loc.Id.ToString(),
                            LocationCode = loc.LocationCode,
                            LocationName = loc.LocationName
                        };
                    }

                    return null;
                }).Where(x => x != null).Cast<TeamMemberAssignedLocationDto>().ToList());

        var scopeIdsMap = await BuildTeamMemberScopeIdsMapAsync(assignedMap, roleIdByUser);

        var items = new List<TeamMemberGetListOutputDto>();
        foreach (var u in users)
        {
            roleIdByUser.TryGetValue(u.Id, out var listRoleId);
            var roleName = userRolePairs.FirstOrDefault(x => x.UserId == u.Id)?.RoleName;
            var userKey = TeamMemberListScopeHelper.UserKey(u.Id);
            assignedMap.TryGetValue(userKey, out var assigned);
            scopeIdsMap.TryGetValue(userKey, out var scopeIds);

            var partnerIds = scopeIds?.PartnerIds ?? new List<string>();
            var regionIds = scopeIds?.RegionIds ?? new List<string>();
            var assignedLocations = assigned ?? new List<TeamMemberAssignedLocationDto>();

            (regionIds, assignedLocations) = await ApplyCompanyAdminDisplayScopeAsync(
                listRoleId, partnerIds, regionIds, assignedLocations);

            var locationIdList = assignedLocations
                .Select(x => x.Id)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            items.Add(new TeamMemberGetListOutputDto
            {
                Id = u.Id,
                FullName = u.Name ?? string.Empty,
                UserName = u.UserName,
                Email = u.Email,
                Phone = u.Phone,
                State = u.State,
                RoleId = listRoleId,
                RoleName = TeamMemberRoleHelper.FormatDisplayRoleName(roleName),
                PartnerIds = partnerIds,
                RegionIds = regionIds,
                LocationIds = locationIdList,
                AssignedLocations = assignedLocations
            });
        }

        return items;
    }

    private async Task<Dictionary<string, TeamMemberScopeIds>> BuildTeamMemberScopeIdsMapAsync(
        Dictionary<string, List<TeamMemberAssignedLocationDto>> assignedMap,
        Dictionary<Guid, Guid?> roleIdByUser)
    {
        var result = new Dictionary<string, TeamMemberScopeIds>(StringComparer.Ordinal);
        foreach (var (userId, assigned) in assignedMap)
        {
            var locationIds = assigned
                .Select(x => x.Id)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Select(x => x.Trim())
                .Distinct(StringComparer.Ordinal)
                .ToList();

            var partnerIds = locationIds.Count == 0
                ? new List<string>()
                : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
                    _dbContext.SqlSugarClient, locationIds);
            var regionIds = locationIds.Count == 0
                ? new List<string>()
                : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
                    _dbContext.SqlSugarClient, locationIds);

            if (Guid.TryParse(userId, out var userGuid) &&
                roleIdByUser.TryGetValue(userGuid, out var roleId) &&
                await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(_dbContext.SqlSugarClient, roleId) &&
                partnerIds.Count > 0)
            {
                var allRegions = await LocationScopeBindingHelper.ResolveGroupIdsFromPartnerIdsAsync(
                    _dbContext.SqlSugarClient, partnerIds);
                if (allRegions.Count > 0)
                {
                    regionIds = allRegions;
                }
            }

            result[userId] = new TeamMemberScopeIds
            {
                PartnerIds = partnerIds,
                RegionIds = regionIds
            };
        }

        return result;
    }

    /// <summary>
    /// Company Admin 列表/详情:展示所选 Company 下全部 Region 与门店。
    /// </summary>
    private async Task<(List<string> RegionIds, List<TeamMemberAssignedLocationDto> AssignedLocations)>
        ApplyCompanyAdminDisplayScopeAsync(
            Guid? roleId,
            List<string> partnerIds,
            List<string> regionIds,
            List<TeamMemberAssignedLocationDto> assigned)
    {
        if (!await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(_dbContext.SqlSugarClient, roleId) ||
            partnerIds.Count == 0)
        {
            return (regionIds, assigned);
        }

        var allRegions = await LocationScopeBindingHelper.ResolveGroupIdsFromPartnerIdsAsync(
            _dbContext.SqlSugarClient, partnerIds);
        var allLocationIds = await LocationScopeBindingHelper.ResolveLocationIdsFromPartnerIdsAsync(
            _dbContext.SqlSugarClient, partnerIds);
        var allAssigned = await BuildAssignedLocationDtosAsync(allLocationIds);

        return (
            allRegions.Count > 0 ? allRegions : regionIds,
            allAssigned.Count > 0 ? allAssigned : assigned);
    }

    private async Task<List<TeamMemberAssignedLocationDto>> BuildAssignedLocationDtosAsync(
        IReadOnlyList<string> locationIds)
    {
        var ids = LocationScopeBindingHelper.NormalizeIds(locationIds);
        if (ids.Count == 0)
        {
            return new List<TeamMemberAssignedLocationDto>();
        }

        var guidList = ids
            .Select(x => Guid.TryParse(x, out var g) ? g : (Guid?)null)
            .Where(x => x.HasValue)
            .Select(x => x!.Value)
            .ToList();
        if (guidList.Count == 0)
        {
            return new List<TeamMemberAssignedLocationDto>();
        }

        var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
            .Where(x => !x.IsDeleted && guidList.Contains(x.Id))
            .Select(x => new { x.Id, x.LocationCode, x.LocationName })
            .ToListAsync();

        return locations
            .OrderBy(x => x.LocationCode)
            .Select(x => new TeamMemberAssignedLocationDto
            {
                Id = x.Id.ToString(),
                LocationCode = x.LocationCode,
                LocationName = x.LocationName
            })
            .ToList();
    }

    private sealed class TeamMemberScopeIds
    {
        public List<string> PartnerIds { get; init; } = new();
        public List<string> RegionIds { get; init; } = new();
    }

    private Task<List<string>> ResolveTeamMemberLocationIdsForSaveAsync(TeamMemberUpdateInputVo input) =>
        ResolveTeamMemberLocationIdsForSaveAsync(new TeamMemberCreateInputVo
        {
            PartnerId = input.PartnerId,
            PartnerIds = input.PartnerIds,
            RegionIds = input.RegionIds,
            GroupIds = input.GroupIds,
            LocationIds = input.LocationIds
        }, input.RoleId);

    private async Task<List<string>> ResolveTeamMemberLocationIdsForSaveAsync(
        TeamMemberCreateInputVo input,
        Guid? roleId)
    {
        var partnerIds = NormalizePartnerIds(input);
        var regionIds = NormalizeRegionIds(input);
        var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds);
        var isCompanyAdmin = await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(
            _dbContext.SqlSugarClient, roleId);

        if (isCompanyAdmin && partnerIds.Count > 0 &&
            regionIds.Count == 0 && explicitLocationIds.Count == 0)
        {
            var fromPartner = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
                _dbContext.SqlSugarClient, partnerIds, null, null);
            if (fromPartner.Count == 0)
            {
                throw new UserFriendlyException("Company Admin 需绑定公司下门店,所选公司下暂无可用门店");
            }

            await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(_dbContext.SqlSugarClient, fromPartner);
            return fromPartner;
        }

        var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
            _dbContext.SqlSugarClient, partnerIds, regionIds, input.LocationIds);

        if (merged.Count == 0)
        {
            throw new UserFriendlyException(
                isCompanyAdmin
                    ? "Company Admin 必须选择 Company,或指定 Region / 门店"
                    : "成员必须至少分配一个门店(公司/区域/门店至少选一项)");
        }

        await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(_dbContext.SqlSugarClient, merged);
        return merged;
    }

    private static List<string> NormalizePartnerIds(TeamMemberCreateInputVo input)
    {
        var merged = new HashSet<string>(StringComparer.Ordinal);
        if (!string.IsNullOrWhiteSpace(input.PartnerId))
        {
            merged.Add(input.PartnerId.Trim());
        }

        foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.PartnerIds))
        {
            merged.Add(id);
        }

        return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
    }

    private static List<string> NormalizeRegionIds(TeamMemberCreateInputVo input)
    {
        var merged = new HashSet<string>(StringComparer.Ordinal);
        foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.RegionIds))
        {
            merged.Add(id);
        }

        foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.GroupIds))
        {
            merged.Add(id);
        }

        return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
    }

    private async Task UpsertUserLocationsAsync(Guid userId, List<string> locationIds)
    {
        var now = DateTime.Now;
        var userIdString = userId.ToString();
        var wanted = locationIds.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().ToList();
        var currentUserId = CurrentUser?.Id?.ToString();

        var validCount = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
            .Where(x => !x.IsDeleted)
            .Where(x => wanted.Contains(x.Id.ToString()))
            .CountAsync();
        if (validCount != wanted.Count)
        {
            throw new UserFriendlyException("存在无效门店,请刷新后重试");
        }

        var existing = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
            .Where(x => x.UserId == userIdString)
            .ToListAsync();

        var existingActive = existing.Where(x => !x.IsDeleted).ToList();
        var existingActiveSet = existingActive.Select(x => x.LocationId).ToHashSet();

        var toDelete = existingActive.Where(x => !wanted.Contains(x.LocationId)).ToList();
        if (toDelete.Count > 0)
        {
            var ids = toDelete.Select(x => x.Id).ToList();
            await _dbContext.SqlSugarClient.Updateable<UserLocationDbEntity>()
                .SetColumns(x => new UserLocationDbEntity
                {
                    IsDeleted = true,
                    LastModificationTime = now,
                    LastModifierId = currentUserId
                })
                .Where(x => ids.Contains(x.Id))
                .ExecuteCommandAsync();
        }

        var toInsert = wanted.Where(x => !existingActiveSet.Contains(x)).ToList();
        if (toInsert.Count > 0)
        {
            var rows = toInsert.Select(locationId => new UserLocationDbEntity
            {
                Id = _guidGenerator.Create().ToString(),
                IsDeleted = false,
                CreationTime = now,
                CreatorId = currentUserId,
                UserId = userIdString,
                LocationId = locationId,
                ConcurrencyStamp = string.Empty
            }).ToList();

            await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
        }
    }
}