UsAppLabelingAppService.cs 38.9 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using FoodLabeling.Application.Contracts.Dtos.Common;
using FoodLabeling.Application.Contracts.Dtos.Label;
using FoodLabeling.Application.Contracts.Dtos.LabelTemplate;
using FoodLabeling.Application.Contracts.Dtos.UsAppLabeling;
using FoodLabeling.Application.Contracts.IServices;
using FoodLabeling.Application.Helpers;
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Guids;
using Volo.Abp.Uow;
using Yi.Framework.SqlSugarCore.Abstractions;

namespace FoodLabeling.Application.Services;

/// <summary>
/// App Labeling:四级列表(标签分类 → 产品分类 → 产品 → 标签种类)
/// </summary>
public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppService
{
    private readonly ISqlSugarDbContext _dbContext;
    private readonly ILabelAppService _labelAppService;
    private readonly IGuidGenerator _guidGenerator;

    public UsAppLabelingAppService(ISqlSugarDbContext dbContext, ILabelAppService labelAppService, IGuidGenerator guidGenerator)
    {
        _dbContext = dbContext;
        _labelAppService = labelAppService;
        _guidGenerator = guidGenerator;
    }

    /// <summary>
    /// 获取当前门店下四级嵌套数据
    /// </summary>
    /// <remarks>
    /// L1 标签分类 fl_label_category;L2 产品分类 fl_product.CategoryId join fl_product_category;
    /// L3 产品;L4 与该门店、该标签分类、该产品关联的标签实例(fl_label + fl_label_type)。
    /// </remarks>
    [Authorize]
    public virtual async Task<List<UsAppLabelCategoryTreeNodeDto>> GetLabelingTreeAsync(UsAppLabelingTreeInputVo input)
    {
        if (string.IsNullOrWhiteSpace(input.LocationId))
        {
            throw new UserFriendlyException("门店Id不能为空");
        }

        var locationId = input.LocationId.Trim();
        var keyword = input.Keyword?.Trim();
        var filterCategoryId = input.LabelCategoryId?.Trim();

        var productIds = await _dbContext.SqlSugarClient.Queryable<FlLocationProductDbEntity>()
            .Where(x => x.LocationId == locationId)
            .Select(x => x.ProductId)
            .ToListAsync();

        if (productIds.Count == 0)
        {
            return new List<UsAppLabelCategoryTreeNodeDto>();
        }

        var query = BuildLabelingJoinQuery(locationId, productIds, filterCategoryId, keyword);

        var raw = await query
            .Select((lp, l, p, c, t, tpl, pc) => new LabelingTreeRow
            {
                LabelCategoryId = c.Id,
                LabelCategoryName = c.CategoryName,
                LabelCategoryPhotoUrl = c.CategoryPhotoUrl,
                LabelCategoryOrderNum = c.OrderNum,
                ProductCategoryId = p.CategoryId,
                ProductCategoryName = pc.CategoryName,
                ProductCategoryPhotoUrl = pc.CategoryPhotoUrl,
                ProductId = p.Id,
                ProductName = p.ProductName,
                ProductCode = p.ProductCode,
                ProductImageUrl = p.ProductImageUrl,
                LabelTypeId = t.Id,
                TypeName = t.TypeName,
                TypeOrderNum = t.OrderNum,
                LabelCode = l.LabelCode,
                TemplateCode = tpl.TemplateCode,
                TemplateWidth = tpl.Width,
                TemplateHeight = tpl.Height,
                TemplateUnit = tpl.Unit
            })
            .ToListAsync();

        if (raw.Count == 0)
        {
            return new List<UsAppLabelCategoryTreeNodeDto>();
        }

        var byL1 = raw.GroupBy(x => new
        {
            x.LabelCategoryId,
            x.LabelCategoryName,
            x.LabelCategoryPhotoUrl,
            x.LabelCategoryOrderNum
        }).OrderBy(g => g.Key.LabelCategoryOrderNum).ThenBy(g => g.Key.LabelCategoryName);

        var result = new List<UsAppLabelCategoryTreeNodeDto>();
        foreach (var g1 in byL1)
        {
            var l1 = new UsAppLabelCategoryTreeNodeDto
            {
                Id = g1.Key.LabelCategoryId,
                CategoryName = g1.Key.LabelCategoryName ?? string.Empty,
                CategoryPhotoUrl = g1.Key.LabelCategoryPhotoUrl,
                OrderNum = g1.Key.LabelCategoryOrderNum,
                ProductCategories = new List<UsAppProductCategoryNodeDto>()
            };

            var byL2 = g1.GroupBy(x =>
                {
                    var categoryId = NormalizeNullableId(x.ProductCategoryId);
                    if (categoryId is null)
                    {
                        return new
                        {
                            CategoryId = (string?)null,
                            CategoryName = "无",
                            CategoryPhotoUrl = (string?)null
                        };
                    }

                    var categoryName = NormalizeCategoryName(x.ProductCategoryName);
                    var categoryPhotoUrl = NormalizeNullableUrl(x.ProductCategoryPhotoUrl);
                    return new
                    {
                        CategoryId = (string?)categoryId,
                        CategoryName = categoryName,
                        CategoryPhotoUrl = categoryPhotoUrl
                    };
                })
                .OrderBy(g => g.Key.CategoryName);

            foreach (var g2 in byL2)
            {
                var productsGrouped = g2.GroupBy(x => x.ProductId).OrderBy(pg => pg.First().ProductName);
                var l2 = new UsAppProductCategoryNodeDto
                {
                    CategoryId = g2.Key.CategoryId,
                    CategoryPhotoUrl = g2.Key.CategoryPhotoUrl,
                    Name = g2.Key.CategoryName,
                    ItemCount = productsGrouped.Count(),
                    Products = new List<UsAppLabelingProductNodeDto>()
                };

                foreach (var g3 in productsGrouped)
                {
                    var first = g3.First();
                    var typeNodes = g3
                        .GroupBy(r => r.LabelCode)
                        .Select(gr => BuildLabelTypeNode(gr.First()))
                        .OrderBy(t => t.OrderNum)
                        .ThenBy(t => t.TypeName)
                        .ToList();

                    var subtitle = string.IsNullOrWhiteSpace(first.ProductCode?.Trim())
                        ? "无"
                        : first.ProductCode!.Trim();

                    l2.Products.Add(new UsAppLabelingProductNodeDto
                    {
                        ProductId = first.ProductId,
                        ProductName = first.ProductName ?? string.Empty,
                        ProductCode = first.ProductCode ?? string.Empty,
                        ProductImageUrl = first.ProductImageUrl,
                        Subtitle = subtitle,
                        LabelTypeCount = typeNodes.Count,
                        LabelTypes = typeNodes
                    });
                }

                l1.ProductCategories.Add(l2);
            }

            result.Add(l1);
        }

        return result;
    }

    /// <summary>
    /// App 打印预览:按标签编码解析模板并返回顶部展示字段 + 预览模板结构
    /// </summary>
    /// <remarks>
    /// 示例请求:
    /// ```json
    /// {
    ///   "locationId": "LOC001",
    ///   "labelCode": "LBL0001",
    ///   "productId": "PROD001",
    ///   "baseTime": "2026-03-26T10:30:00",
    ///   "printInputJson": {
    ///     "price": "12.99"
    ///   }
    /// }
    /// ```
    /// </remarks>
    /// <param name="input">预览入参</param>
    /// <returns>顶部字段 + 预览模板结构</returns>
    /// <response code="200">成功</response>
    /// <response code="400">参数错误/数据不存在</response>
    /// <response code="500">服务器错误</response>
    [Authorize]
    public virtual async Task<UsAppLabelPreviewDto> PreviewAsync(UsAppLabelPreviewInputVo input)
    {
        if (input is null)
        {
            throw new UserFriendlyException("入参不能为空");
        }

        var locationId = input.LocationId?.Trim();
        if (string.IsNullOrWhiteSpace(locationId))
        {
            throw new UserFriendlyException("门店Id不能为空");
        }

        var labelCode = input.LabelCode?.Trim();
        if (string.IsNullOrWhiteSpace(labelCode))
        {
            throw new UserFriendlyException("labelCode不能为空");
        }

        var labelRow = await _dbContext.SqlSugarClient
            .Queryable<FlLabelDbEntity, FlLabelCategoryDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity>(
                (l, c, t, tpl) => l.LabelCategoryId == c.Id && l.LabelTypeId == t.Id && l.TemplateId == tpl.Id)
            .Where((l, c, t, tpl) => !l.IsDeleted && l.State)
            .Where((l, c, t, tpl) => !c.IsDeleted && c.State)
            .Where((l, c, t, tpl) => !t.IsDeleted && t.State)
            .Where((l, c, t, tpl) => !tpl.IsDeleted)
            .Where((l, c, t, tpl) => l.LabelCode == labelCode)
            .Select((l, c, t, tpl) => new
            {
                l.Id,
                l.LabelCode,
                l.LocationId,
                l.LabelTypeId,
                l.TemplateId,
                l.LastModificationTime,
                l.CreationTime,
                LabelCategoryName = c.CategoryName,
                TypeName = t.TypeName,
                TemplateCode = tpl.TemplateCode,
                TemplateWidth = tpl.Width,
                TemplateHeight = tpl.Height,
                TemplateUnit = tpl.Unit
            })
            .FirstAsync();

        if (labelRow is null)
        {
            throw new UserFriendlyException("标签不存在或不可用");
        }

        if (!string.Equals(labelRow.LocationId?.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
        {
            throw new UserFriendlyException("该标签不属于当前门店");
        }

        var previewProductId = await ResolvePreviewProductIdAsync(labelRow.Id, input.ProductId);

        var template = await _labelAppService.PreviewAsync(new LabelPreviewResolveInputVo
        {
            LabelCode = labelCode,
            ProductId = previewProductId,
            BaseTime = input.BaseTime,
            PrintInputJson = input.PrintInputJson?.ToDictionary(x => x.Key, x => (object?)x.Value)
        });

        Dictionary<string, object?>? templateProductDefaultValues = null;
        if (!string.IsNullOrWhiteSpace(previewProductId))
        {
            var productDefault = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateProductDefaultDbEntity>()
                .Where(x => x.TemplateId == labelRow.TemplateId)
                .Where(x => x.ProductId == previewProductId)
                .Where(x => x.LabelTypeId == labelRow.LabelTypeId)
                .OrderBy(x => x.OrderNum)
                .FirstAsync();

            if (!string.IsNullOrWhiteSpace(productDefault?.DefaultValuesJson))
            {
                try
                {
                    templateProductDefaultValues =
                        JsonSerializer.Deserialize<Dictionary<string, object?>>(productDefault.DefaultValuesJson!);
                }
                catch
                {
                    templateProductDefaultValues = null;
                }
            }
        }

        var productName = string.Empty;
        var productCategoryName = "无";
        if (!string.IsNullOrWhiteSpace(previewProductId))
        {
            var p = await _dbContext.SqlSugarClient.Queryable<FlProductDbEntity>()
                .FirstAsync(x => !x.IsDeleted && x.State && x.Id == previewProductId);
            if (p is not null)
            {
                productName = p.ProductName ?? string.Empty;
                if (!string.IsNullOrWhiteSpace(p.CategoryId))
                {
                    var pc = await _dbContext.SqlSugarClient.Queryable<FlProductCategoryDbEntity>()
                        .FirstAsync(x => !x.IsDeleted && x.State && x.Id == p.CategoryId);
                    productCategoryName = NormalizeCategoryName(pc?.CategoryName);
                }
            }
        }

        return new UsAppLabelPreviewDto
        {
            LabelId = labelRow.Id,
            LocationId = locationId,
            LabelCode = labelCode,
            TemplateCode = labelRow.TemplateCode,
            LabelSizeText = FormatLabelSize(labelRow.TemplateWidth, labelRow.TemplateHeight, labelRow.TemplateUnit),
            TypeName = labelRow.TypeName,
            ProductName = string.IsNullOrWhiteSpace(productName) ? null : productName,
            ProductCategoryName = productCategoryName,
            LabelCategoryName = labelRow.LabelCategoryName,
            LabelLastEdited = labelRow.LastModificationTime ?? labelRow.CreationTime,
            PreviewImageBase64Png = null,
            Template = template,
            TemplateProductDefaultValues = templateProductDefaultValues
        };
    }

    /// <summary>
    /// App 打印:创建打印任务并落库打印明细(fl_label_print_task / fl_label_print_data)
    /// </summary>
    /// <param name="input">打印入参</param>
    /// <returns>任务Id</returns>
    [Authorize]
    [UnitOfWork]
    public virtual async Task<UsAppLabelPrintOutputDto> PrintAsync(UsAppLabelPrintInputVo input)
    {
        if (input is null)
        {
            throw new UserFriendlyException("入参不能为空");
        }

        var locationId = input.LocationId?.Trim();
        if (string.IsNullOrWhiteSpace(locationId))
        {
            throw new UserFriendlyException("门店Id不能为空");
        }

        var labelCode = input.LabelCode?.Trim();
        if (string.IsNullOrWhiteSpace(labelCode))
        {
            throw new UserFriendlyException("labelCode不能为空");
        }

        var quantity = input.PrintQuantity <= 0 ? 1 : input.PrintQuantity;

        // 校验 label + location,并补齐一些顶部字段用于任务表落库
        var labelRow = await _dbContext.SqlSugarClient
            .Queryable<FlLabelDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity>(
                (l, t, tpl) => l.LabelTypeId == t.Id && l.TemplateId == tpl.Id)
            .Where((l, t, tpl) => !l.IsDeleted && l.State)
            .Where((l, t, tpl) => !t.IsDeleted && t.State)
            .Where((l, t, tpl) => !tpl.IsDeleted)
            .Where((l, t, tpl) => l.LabelCode == labelCode)
            .Select((l, t, tpl) => new
            {
                l.LocationId,
                l.LabelTypeId,
                TemplateCode = tpl.TemplateCode
            })
            .FirstAsync();

        if (labelRow is null)
        {
            throw new UserFriendlyException("标签不存在或不可用");
        }

        if (!string.Equals(labelRow.LocationId?.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
        {
            throw new UserFriendlyException("该标签不属于当前门店");
        }

        string? printInputJsonStr = null;
        string renderDataJsonStr;
        var templateSnapshotOk = false;

        if (input.PrintInputJson.HasValue)
        {
            var piRoot = input.PrintInputJson.Value;
            if (piRoot.ValueKind == JsonValueKind.Object
                && piRoot.TryGetProperty("elements", out var elArr)
                && elArr.ValueKind == JsonValueKind.Array)
            {
                // App 传入整份合并模板(与 label-template JSON 同构):落库 printInputJson / renderDataJson 均存同一份,供重打
                printInputJsonStr = piRoot.GetRawText();
                renderDataJsonStr = printInputJsonStr;
                templateSnapshotOk = true;
            }
        }

        Dictionary<string, object?>? flatPrintInput = null;
        if (!templateSnapshotOk && input.PrintInputJson.HasValue)
        {
            var piFlat = input.PrintInputJson.Value;
            if (piFlat.ValueKind == JsonValueKind.Object)
            {
                try
                {
                    flatPrintInput = JsonSerializer.Deserialize<Dictionary<string, object?>>(piFlat.GetRawText());
                }
                catch
                {
                    flatPrintInput = null;
                }
            }
        }

        if (!templateSnapshotOk)
        {
            var resolvedTemplate = await _labelAppService.PreviewAsync(new LabelPreviewResolveInputVo
            {
                LabelCode = labelCode,
                ProductId = input.ProductId?.Trim(),
                BaseTime = input.BaseTime,
                PrintInputJson = flatPrintInput
            });
            renderDataJsonStr = JsonSerializer.Serialize(resolvedTemplate);
            printInputJsonStr = input.PrintInputJson.HasValue
                ? input.PrintInputJson.Value.GetRawText()
                : null;
        }

        var now = DateTime.Now;
        var currentUserId = CurrentUser?.Id?.ToString();
        var taskId = _guidGenerator.Create().ToString();

        var task = new FlLabelPrintTaskDbEntity
        {
            Id = taskId,
            IsDeleted = false,
            CreationTime = now,
            CreatorId = currentUserId,
            ConcurrencyStamp = _guidGenerator.Create().ToString("N"),
            LocationId = locationId,
            LabelCode = labelCode,
            ProductId = input.ProductId?.Trim(),
            LabelTypeId = labelRow.LabelTypeId,
            TemplateCode = labelRow.TemplateCode,
            PrintQuantity = quantity,
            BaseTime = input.BaseTime,
            PrinterId = input.PrinterId?.Trim(),
            PrinterMac = input.PrinterMac?.Trim(),
            PrinterAddress = input.PrinterAddress?.Trim()
        };

        await _dbContext.SqlSugarClient.Insertable(task).ExecuteCommandAsync();

        var dataRows = Enumerable.Range(1, quantity).Select(i => new FlLabelPrintDataDbEntity
        {
            Id = _guidGenerator.Create().ToString(),
            IsDeleted = false,
            CreationTime = now,
            CreatorId = currentUserId,
            ConcurrencyStamp = _guidGenerator.Create().ToString("N"),
            TaskId = taskId,
            CopyIndex = i,
            PrintInputJson = printInputJsonStr,
            RenderDataJson = renderDataJsonStr
        }).ToList();

        await _dbContext.SqlSugarClient.Insertable(dataRows).ExecuteCommandAsync();

        return new UsAppLabelPrintOutputDto
        {
            TaskId = taskId,
            PrintQuantity = quantity,
            BatchId = taskId,
            TaskIds = new List<string> { taskId },
            MergedTemplateJson = null
        };
    }

    /// <summary>
    /// 接口 10:分页打印日志(当前用户 + 当前门店)
    /// </summary>
    [Authorize]
    [HttpPost]
    public virtual async Task<PagedResultWithPageDto<PrintLogItemDto>> GetPrintLogListAsync(PrintLogGetListInputVo input)
    {
        if (input == null)
        {
            throw new UserFriendlyException("入参不能为空");
        }

        var locationId = input.LocationId?.Trim();
        if (string.IsNullOrWhiteSpace(locationId))
        {
            throw new UserFriendlyException("门店Id不能为空");
        }

        var userId = CurrentUser.Id?.ToString();
        if (string.IsNullOrWhiteSpace(userId))
        {
            throw new UserFriendlyException("未登录");
        }

        var pageIndex = input.SkipCount <= 0 ? 1 : input.SkipCount;
        var pageSize = input.MaxResultCount <= 0 ? 20 : Math.Min(input.MaxResultCount, 200);

        RefAsync<int> total = 0;
        var dataRows = await _dbContext.SqlSugarClient
            .Queryable<FlLabelPrintDataDbEntity, FlLabelPrintTaskDbEntity>((d, t) => d.TaskId == t.Id)
            .Where((d, t) => !d.IsDeleted && !t.IsDeleted)
            .Where((d, t) => t.CreatorId == userId && t.LocationId == locationId)
            .OrderBy((d, t) => d.CreationTime, OrderByType.Desc)
            .Select((d, t) => d)
            .ToPageListAsync(pageIndex, pageSize, total);

        string? locationDisplayName = null;
        if (Guid.TryParse(locationId, out var locGuid))
        {
            var locRows = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
                .Where(x => x.Id == locGuid && !x.IsDeleted)
                .Select(x => x.LocationName)
                .Take(1)
                .ToListAsync();
            locationDisplayName = locRows.FirstOrDefault();
        }

        var operatorName = CurrentUser.Name?.Trim();
        if (string.IsNullOrWhiteSpace(operatorName))
        {
            operatorName = CurrentUser.UserName?.Trim();
        }
        if (string.IsNullOrWhiteSpace(operatorName))
        {
            operatorName = "无";
        }

        var taskIds = dataRows.Select(x => x.TaskId).Distinct().ToList();
        var tasks = taskIds.Count == 0
            ? new List<FlLabelPrintTaskDbEntity>()
            : await _dbContext.SqlSugarClient.Queryable<FlLabelPrintTaskDbEntity>()
                .Where(t => taskIds.Contains(t.Id))
                .ToListAsync();
        var taskMap = tasks.ToDictionary(x => x.Id, x => x);

        var labelCodes = tasks.Select(t => t.LabelCode).Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();
        var labels = labelCodes.Count == 0
            ? new List<FlLabelDbEntity>()
            : await _dbContext.SqlSugarClient.Queryable<FlLabelDbEntity>()
                .Where(l => !l.IsDeleted && labelCodes.Contains(l.LabelCode))
                .ToListAsync();
        var labelByCode = labels.GroupBy(x => x.LabelCode).ToDictionary(g => g.Key, g => g.First());

        var categoryIds = labels
            .Select(x => x.LabelCategoryId)
            .Where(x => !string.IsNullOrWhiteSpace(x))
            .Select(x => x!.Trim())
            .Distinct()
            .ToList();
        var categories = categoryIds.Count == 0
            ? new List<FlLabelCategoryDbEntity>()
            : await _dbContext.SqlSugarClient.Queryable<FlLabelCategoryDbEntity>()
                .Where(c => !c.IsDeleted && categoryIds.Contains(c.Id))
                .ToListAsync();
        var catMap = categories.ToDictionary(x => x.Id, x => x);

        var templateIds = labels
            .Select(x => x.TemplateId)
            .Where(x => !string.IsNullOrWhiteSpace(x))
            .Select(x => x!.Trim())
            .Distinct()
            .ToList();
        var templates = templateIds.Count == 0
            ? new List<FlLabelTemplateDbEntity>()
            : await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
                .Where(tpl => !tpl.IsDeleted && templateIds.Contains(tpl.Id))
                .ToListAsync();
        var tplMap = templates.ToDictionary(x => x.Id, x => x);

        var labelTypeIds = labels
            .Select(x => x.LabelTypeId)
            .Where(x => !string.IsNullOrWhiteSpace(x))
            .Select(x => x!.Trim())
            .Distinct()
            .ToList();
        var labelTypes = labelTypeIds.Count == 0
            ? new List<FlLabelTypeDbEntity>()
            : await _dbContext.SqlSugarClient.Queryable<FlLabelTypeDbEntity>()
                .Where(lt => !lt.IsDeleted && labelTypeIds.Contains(lt.Id))
                .ToListAsync();
        var typeMap = labelTypes.ToDictionary(x => x.Id, x => x);

        var productIds = tasks
            .Select(t => t.ProductId)
            .Where(x => !string.IsNullOrWhiteSpace(x))
            .Select(x => x!.Trim())
            .Distinct()
            .ToList();
        var products = productIds.Count == 0
            ? new List<FlProductDbEntity>()
            : await _dbContext.SqlSugarClient.Queryable<FlProductDbEntity>()
                .Where(p => !p.IsDeleted && productIds.Contains(p.Id))
                .ToListAsync();
        var prodMap = products.ToDictionary(x => x.Id, x => x);

        var items = dataRows.Select(d =>
        {
            taskMap.TryGetValue(d.TaskId, out var t);
            var lblId = "";
            string? catName = null;
            string? tplSummary = null;
            string? labelSizeText = null;
            string? typeName = null;
            if (t != null && !string.IsNullOrWhiteSpace(t.LabelCode) && labelByCode.TryGetValue(t.LabelCode.Trim(), out var lbl))
            {
                lblId = lbl.Id;
                if (!string.IsNullOrWhiteSpace(lbl.LabelCategoryId) && catMap.TryGetValue(lbl.LabelCategoryId.Trim(), out var c))
                {
                    catName = string.IsNullOrWhiteSpace(c.CategoryName) ? "无" : c.CategoryName.Trim();
                }
                if (!string.IsNullOrWhiteSpace(lbl.LabelTypeId) && typeMap.TryGetValue(lbl.LabelTypeId.Trim(), out var lt))
                {
                    typeName = string.IsNullOrWhiteSpace(lt.TypeName) ? null : lt.TypeName.Trim();
                }
                if (!string.IsNullOrWhiteSpace(lbl.TemplateId) && tplMap.TryGetValue(lbl.TemplateId.Trim(), out var tpl))
                {
                    tplSummary = $"{tpl.Width}x{tpl.Height}{tpl.Unit} {tpl.TemplateName}".Trim();
                    labelSizeText = string.Format(
                        CultureInfo.InvariantCulture,
                        "{0:0.00}x{1:0.00}{2}",
                        tpl.Width,
                        tpl.Height,
                        tpl.Unit);
                }
            }

            var productName = "无";
            if (t != null && !string.IsNullOrWhiteSpace(t.ProductId) && prodMap.TryGetValue(t.ProductId.Trim(), out var p))
            {
                productName = string.IsNullOrWhiteSpace(p.ProductName) ? "无" : p.ProductName.Trim();
            }

            return new PrintLogItemDto
            {
                TaskId = d.TaskId,
                BatchId = d.TaskId,
                CopyIndex = d.CopyIndex ?? 1,
                LabelId = string.IsNullOrWhiteSpace(lblId) ? (t?.LabelCode ?? "") : lblId,
                LabelCode = t?.LabelCode ?? "",
                ProductId = t?.ProductId,
                ProductName = productName,
                PrintedAt = d.CreationTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
                OperatorName = operatorName,
                LocationName = string.IsNullOrWhiteSpace(locationDisplayName) ? "无" : locationDisplayName!,
                LabelCategoryName = catName,
                LabelTemplateSummary = tplSummary,
                LabelSizeText = labelSizeText,
                TypeName = typeName,
                PrintDataList = BuildPrintDataListFromRenderJson(d.RenderDataJson)
            };
        }).ToList();

        var totalCount = total.Value;
        var totalPages = pageSize <= 0 ? 0 : (int)Math.Ceiling(totalCount / (double)pageSize);

        return new PagedResultWithPageDto<PrintLogItemDto>
        {
            PageIndex = pageIndex,
            PageSize = pageSize,
            TotalCount = totalCount,
            TotalPages = totalPages,
            Items = items
        };
    }

    private static List<PrintLogDataItemDto> BuildPrintDataListFromRenderJson(string? renderDataJson)
    {
        var list = new List<PrintLogDataItemDto>();
        if (string.IsNullOrWhiteSpace(renderDataJson))
        {
            return list;
        }

        try
        {
            using var doc = JsonDocument.Parse(renderDataJson);
            var root = doc.RootElement;
            if (root.ValueKind == JsonValueKind.Object
                && root.TryGetProperty("elements", out var elArr)
                && elArr.ValueKind == JsonValueKind.Array)
            {
                foreach (var el in elArr.EnumerateArray())
                {
                    if (el.ValueKind != JsonValueKind.Object)
                    {
                        continue;
                    }

                    var id = el.TryGetProperty("id", out var idEl) ? idEl.GetString() ?? string.Empty : string.Empty;
                    list.Add(new PrintLogDataItemDto
                    {
                        ElementId = id,
                        RenderValue = string.Empty,
                        RenderConfigJson = el.Clone()
                    });
                }

                if (list.Count > 0)
                {
                    return list;
                }
            }
        }
        catch
        {
            // 继续尝试强类型解析
        }

        try
        {
            var preview = JsonSerializer.Deserialize<LabelTemplatePreviewDto>(renderDataJson);
            if (preview?.Elements == null || preview.Elements.Count == 0)
            {
                return list;
            }

            foreach (var el in preview.Elements)
            {
                var elJson = JsonSerializer.SerializeToElement(el);
                list.Add(new PrintLogDataItemDto
                {
                    ElementId = el.Id ?? string.Empty,
                    RenderValue = GetElementRenderValue(el),
                    RenderConfigJson = elJson
                });
            }
        }
        catch
        {
            // 历史数据或非预览结构时忽略
        }

        return list;
    }

    private static string GetElementRenderValue(LabelTemplateElementDto el)
    {
        try
        {
            if (el.ConfigJson is JsonElement je)
            {
                if (je.ValueKind == JsonValueKind.Object)
                {
                    if (je.TryGetProperty("text", out var t))
                    {
                        return t.GetString() ?? string.Empty;
                    }
                    if (je.TryGetProperty("Text", out var t2))
                    {
                        return t2.GetString() ?? string.Empty;
                    }
                }
            }
        }
        catch
        {
            // ignore
        }

        return string.Empty;
    }

    /// <summary>
    /// 接口 11:按历史任务重打并落库,返回可本地打印的合并模板 JSON
    /// </summary>
    [Authorize]
    [UnitOfWork]
    [HttpPost]
    public virtual async Task<UsAppLabelPrintOutputDto> ReprintAsync(UsAppLabelReprintInputVo input)
    {
        if (input == null)
        {
            throw new UserFriendlyException("入参不能为空");
        }

        var locationId = input.LocationId?.Trim();
        if (string.IsNullOrWhiteSpace(locationId))
        {
            throw new UserFriendlyException("门店Id不能为空");
        }

        var histTaskId = input.TaskId?.Trim();
        if (string.IsNullOrWhiteSpace(histTaskId))
        {
            throw new UserFriendlyException("taskId不能为空");
        }

        var userId = CurrentUser.Id?.ToString();
        if (string.IsNullOrWhiteSpace(userId))
        {
            throw new UserFriendlyException("未登录");
        }

        var taskRows = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintTaskDbEntity>()
            .Where(t => t.Id == histTaskId && !t.IsDeleted)
            .Take(1)
            .ToListAsync();
        var task = taskRows.FirstOrDefault();
        if (task == null)
        {
            throw new UserFriendlyException("打印任务不存在");
        }

        if (!string.Equals(task.CreatorId?.Trim(), userId, StringComparison.Ordinal))
        {
            throw new UserFriendlyException("无权操作该打印任务");
        }

        if (!string.Equals(task.LocationId?.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
        {
            throw new UserFriendlyException("该任务不属于当前门店");
        }

        var histDataRows = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintDataDbEntity>()
            .Where(d => d.TaskId == histTaskId && !d.IsDeleted)
            .OrderBy(d => d.CopyIndex)
            .Take(1)
            .ToListAsync();
        var histData = histDataRows.FirstOrDefault();
        if (histData == null)
        {
            throw new UserFriendlyException("打印明细不存在");
        }

        var mergedJson = !string.IsNullOrWhiteSpace(histData.PrintInputJson)
            ? histData.PrintInputJson!
            : histData.RenderDataJson;
        if (string.IsNullOrWhiteSpace(mergedJson))
        {
            throw new UserFriendlyException("无法重打:历史打印数据为空");
        }

        var qty = input.PrintQuantity <= 0 ? 1 : input.PrintQuantity;

        var now = DateTime.Now;
        var newTaskId = _guidGenerator.Create().ToString();
        var newTask = new FlLabelPrintTaskDbEntity
        {
            Id = newTaskId,
            IsDeleted = false,
            CreationTime = now,
            CreatorId = userId,
            ConcurrencyStamp = _guidGenerator.Create().ToString("N"),
            LocationId = locationId,
            LabelCode = task.LabelCode,
            ProductId = task.ProductId,
            LabelTypeId = task.LabelTypeId,
            TemplateCode = task.TemplateCode,
            PrintQuantity = qty,
            BaseTime = task.BaseTime,
            PrinterId = !string.IsNullOrWhiteSpace(input.PrinterId) ? input.PrinterId.Trim() : task.PrinterId,
            PrinterMac = !string.IsNullOrWhiteSpace(input.PrinterMac) ? input.PrinterMac.Trim() : task.PrinterMac,
            PrinterAddress = !string.IsNullOrWhiteSpace(input.PrinterAddress) ? input.PrinterAddress.Trim() : task.PrinterAddress
        };
        await _dbContext.SqlSugarClient.Insertable(newTask).ExecuteCommandAsync();

        var dataRows = Enumerable.Range(1, qty).Select(i => new FlLabelPrintDataDbEntity
        {
            Id = _guidGenerator.Create().ToString(),
            IsDeleted = false,
            CreationTime = now,
            CreatorId = userId,
            ConcurrencyStamp = _guidGenerator.Create().ToString("N"),
            TaskId = newTaskId,
            CopyIndex = i,
            PrintInputJson = histData.PrintInputJson,
            RenderDataJson = histData.RenderDataJson
        }).ToList();

        await _dbContext.SqlSugarClient.Insertable(dataRows).ExecuteCommandAsync();

        return new UsAppLabelPrintOutputDto
        {
            TaskId = newTaskId,
            PrintQuantity = qty,
            BatchId = newTaskId,
            TaskIds = new List<string> { newTaskId },
            MergedTemplateJson = mergedJson
        };
    }

    private ISugarQueryable<FlLabelProductDbEntity, FlLabelDbEntity, FlProductDbEntity, FlLabelCategoryDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity, FlProductCategoryDbEntity> BuildLabelingJoinQuery(
        string locationId,
        List<string> productIds,
        string? filterCategoryId,
        string? keyword)
    {
        var q = _dbContext.SqlSugarClient
            .Queryable<FlLabelProductDbEntity>()
            .InnerJoin<FlLabelDbEntity>((lp, l) => lp.LabelId == l.Id)
            .InnerJoin<FlProductDbEntity>((lp, l, p) => lp.ProductId == p.Id)
            .InnerJoin<FlLabelCategoryDbEntity>((lp, l, p, c) => l.LabelCategoryId == c.Id)
            .InnerJoin<FlLabelTypeDbEntity>((lp, l, p, c, t) => l.LabelTypeId == t.Id)
            .InnerJoin<FlLabelTemplateDbEntity>((lp, l, p, c, t, tpl) => l.TemplateId == tpl.Id)
            .LeftJoin<FlProductCategoryDbEntity>((lp, l, p, c, t, tpl, pc) => p.CategoryId == pc.Id)
            .Where((lp, l, p, c, t, tpl, pc) => productIds.Contains(p.Id))
            .Where((lp, l, p, c, t, tpl, pc) => l.LocationId == locationId)
            .Where((lp, l, p, c, t, tpl, pc) => !l.IsDeleted && l.State)
            .Where((lp, l, p, c, t, tpl, pc) => !p.IsDeleted && p.State)
            .Where((lp, l, p, c, t, tpl, pc) => !c.IsDeleted && c.State)
            .Where((lp, l, p, c, t, tpl, pc) => !t.IsDeleted && t.State)
            .Where((lp, l, p, c, t, tpl, pc) => !tpl.IsDeleted)
            .WhereIF(!string.IsNullOrWhiteSpace(filterCategoryId), (lp, l, p, c, t, tpl, pc) => l.LabelCategoryId == filterCategoryId)
            .WhereIF(!string.IsNullOrWhiteSpace(keyword), (lp, l, p, c, t, tpl, pc) =>
                (l.LabelName != null && l.LabelName.Contains(keyword!)) ||
                (p.ProductName != null && p.ProductName.Contains(keyword!)) ||
                (pc.CategoryName != null && pc.CategoryName.Contains(keyword!)) ||
                (c.CategoryName != null && c.CategoryName.Contains(keyword!)) ||
                (t.TypeName != null && t.TypeName.Contains(keyword!)) ||
                (l.LabelCode != null && l.LabelCode.Contains(keyword!)));

        return q;
    }

    private sealed class LabelingTreeRow
    {
        public string LabelCategoryId { get; set; } = string.Empty;

        public string? LabelCategoryName { get; set; }

        public string? LabelCategoryPhotoUrl { get; set; }

        public int LabelCategoryOrderNum { get; set; }

        public string? ProductCategoryId { get; set; }

        public string? ProductCategoryName { get; set; }

        public string? ProductCategoryPhotoUrl { get; set; }

        public string ProductId { get; set; } = string.Empty;

        public string? ProductName { get; set; }

        public string? ProductCode { get; set; }

        public string? ProductImageUrl { get; set; }

        public string LabelTypeId { get; set; } = string.Empty;

        public string? TypeName { get; set; }

        public int TypeOrderNum { get; set; }

        public string LabelCode { get; set; } = string.Empty;

        public string? TemplateCode { get; set; }

        public decimal TemplateWidth { get; set; }

        public decimal TemplateHeight { get; set; }

        public string TemplateUnit { get; set; } = "inch";
    }

    private static string NormalizeCategoryName(string? categoryName)
    {
        var s = categoryName?.Trim();
        return string.IsNullOrWhiteSpace(s) ? "无" : s;
    }

    private static string? NormalizeNullableId(string? id)
    {
        var s = id?.Trim();
        return string.IsNullOrWhiteSpace(s) ? null : s;
    }

    private static string? NormalizeNullableUrl(string? url)
    {
        var s = url?.Trim();
        return string.IsNullOrWhiteSpace(s) ? null : s;
    }

    private async Task<string?> ResolvePreviewProductIdAsync(string labelId, string? productId)
    {
        var resolvedProductId = productId?.Trim();
        if (!string.IsNullOrWhiteSpace(resolvedProductId))
        {
            return resolvedProductId;
        }

        return await _dbContext.SqlSugarClient.Queryable<FlLabelProductDbEntity>()
            .Where(x => x.LabelId == labelId)
            .Select(x => x.ProductId)
            .FirstAsync();
    }

    private static UsAppLabelTypeNodeDto BuildLabelTypeNode(LabelingTreeRow r)
    {
        return new UsAppLabelTypeNodeDto
        {
            LabelTypeId = r.LabelTypeId,
            TypeName = r.TypeName ?? string.Empty,
            OrderNum = r.TypeOrderNum,
            LabelCode = r.LabelCode ?? string.Empty,
            TemplateCode = r.TemplateCode,
            LabelSizeText = FormatLabelSize(r.TemplateWidth, r.TemplateHeight, r.TemplateUnit)
        };
    }

    private static string? FormatLabelSize(decimal w, decimal h, string unit)
    {
        var u = (unit ?? "inch").Trim().ToLowerInvariant();
        var ws = w.ToString(CultureInfo.InvariantCulture);
        var hs = h.ToString(CultureInfo.InvariantCulture);
        return u is "inch" or "in"
            ? $"{ws}\"x{hs}\""
            : $"{ws}x{hs}{u}";
    }
}