LqReimbursementApplicationService.cs 53.8 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 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Interfaces.LqReimbursementApplication;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys;
using NCC.Extend.Entitys.Dto.LqReimbursementApplication;
using NCC.Extend.Entitys.lq_reimbursement_application_node;
using NCC.Extend.Entitys.lq_reimbursement_application_node_user;
using NCC.Extend.Entitys.lq_reimbursement_approval_record;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;

namespace NCC.Extend.LqReimbursementApplication
{
    /// <summary>
    /// 报销申请表服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Extend", Name = "LqReimbursementApplication", Order = 200)]
    [Route("api/Extend/[controller]")]
    public class LqReimbursementApplicationService : ILqReimbursementApplicationService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<LqReimbursementApplicationEntity> _lqReimbursementApplicationRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="LqReimbursementApplicationService"/>类型的新实例
        /// </summary>
        public LqReimbursementApplicationService(
            ISqlSugarRepository<LqReimbursementApplicationEntity> lqReimbursementApplicationRepository,
            IUserManager userManager)
        {
            _lqReimbursementApplicationRepository = lqReimbursementApplicationRepository;
            _db = _lqReimbursementApplicationRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取报销申请表详情(包含表单和流程信息)
        /// </summary>
        /// <param name="id">申请编号</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);

            var output = entity.Adapt<LqReimbursementApplicationInfoOutput>();

            // 获取节点配置
            var nodes = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
                .Where(x => x.ApplicationId == id)
                .OrderBy(x => x.NodeOrder)
                .ToListAsync();

            // 获取每个节点的审批人
            var nodeUsers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                .Where(x => x.ApplicationId == id)
                .OrderBy(x => x.NodeOrder)
                .OrderBy(x => x.SortOrder)
                .ToListAsync();

            // 获取审批历史
            var approvalRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
                .Where(x => x.ApplicationId == id)
                .OrderBy(x => x.NodeOrder)
                .OrderBy(x => x.ApprovalTime)
                .ToListAsync();

            // 组装节点信息
            var nodeList = nodes.Select(n => new
            {
                nodeId = n.Id,
                nodeOrder = n.NodeOrder,
                nodeName = n.NodeName,
                approvalType = n.ApprovalType,
                isRequired = n.IsRequired,
                approvers = nodeUsers.Where(u => u.NodeId == n.Id).Select(u => new
                {
                    userId = u.UserId,
                    userName = u.UserName,
                    sortOrder = u.SortOrder
                }).ToList(),
                approvalRecords = approvalRecords.Where(r => r.NodeId == n.Id).Select(r => new
                {
                    approverName = r.ApproverName,
                    approvalResult = r.ApprovalResult,
                    approvalOpinion = r.ApprovalOpinion,
                    approvalTime = r.ApprovalTime
                }).ToList()
            }).ToList();

            // 获取当前节点审批人
            var currentApprovers = new List<object>();
            if (entity.CurrentNodeOrder.HasValue && entity.CurrentNodeOrder > 0)
            {
                currentApprovers = nodeUsers
                    .Where(u => u.NodeOrder == entity.CurrentNodeOrder.Value)
                    .Select(u => new
                    {
                        userId = u.UserId,
                        userName = u.UserName
                    })
                    .Cast<object>()
                    .ToList();
            }

            return new
            {
                form = output,
                nodes = nodeList,
                currentApprovers = currentApprovers,
                currentNodeOrder = entity.CurrentNodeOrder,
                approvalStatus = entity.ApprovalStatus ?? entity.ApproveStatus,
                returnedReason = entity.ReturnedReason
            };
        }

        /// <summary>
		/// 获取报销申请表列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] LqReimbursementApplicationListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            List<string> queryApplicationTime = input.applicationTime != null ? input.applicationTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.First()) : null;
            DateTime? endApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.Last()) : null;
            List<string> queryApproveTime = input.approveTime != null ? input.approveTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.First()) : null;
            DateTime? endApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.Last()) : null;
            var query = _db.Queryable<LqReimbursementApplicationEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
                .WhereIF(!string.IsNullOrEmpty(input.applicationUserId), p => p.ApplicationUserId.Contains(input.applicationUserId))
                .WhereIF(!string.IsNullOrEmpty(input.applicationUserName), p => p.ApplicationUserName.Contains(input.applicationUserName))
                .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
                .WhereIF(queryApplicationTime != null, p => p.ApplicationTime >= new DateTime(startApplicationTime.ToDate().Year, startApplicationTime.ToDate().Month, startApplicationTime.ToDate().Day, 0, 0, 0))
                .WhereIF(queryApplicationTime != null, p => p.ApplicationTime <= new DateTime(endApplicationTime.ToDate().Year, endApplicationTime.ToDate().Month, endApplicationTime.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.amount), p => p.Amount.Contains(input.amount))
                .WhereIF(!string.IsNullOrEmpty(input.approveUser), p => p.ApproveUser.Equals(input.approveUser))
                .WhereIF(!string.IsNullOrEmpty(input.approveStatus), p => (p.ApprovalStatus ?? p.ApproveStatus).Contains(input.approveStatus))
                // .WhereIF(queryApproveTime != null, p => p.ApproveTime >= new DateTime(startApproveTime.ToDate().Year, startApproveTime.ToDate().Month, startApproveTime.ToDate().Day, 0, 0, 0))
                //.WhereIF(queryApproveTime != null, p => p.ApproveTime <= new DateTime(endApproveTime.ToDate().Year, endApproveTime.ToDate().Month, endApproveTime.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.purchaseRecordsId), p => p.PurchaseRecordsId.Contains(input.purchaseRecordsId))
                .OrderBy(sidx + " " + input.sort);

            var total = await query.CountAsync();
            var entities = await query.ToPageListAsync(input.currentPage, input.pageSize);

            // 获取当前审批人信息
            var applicationIds = entities.Select(x => x.Id).ToList();
            var currentApprovers = new List<dynamic>();
            if (applicationIds.Any())
            {
                var approverList = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                    .Where(x => applicationIds.Contains(x.ApplicationId))
                    .InnerJoin<LqReimbursementApplicationEntity>((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder)
                    .Select((u, a) => new
                    {
                        applicationId = a.Id,
                        approverName = u.UserName
                    })
                    .ToListAsync();
                currentApprovers = approverList.Cast<dynamic>().ToList();
            }

            var approverDict = currentApprovers
                .GroupBy(x => (string)x.applicationId)
                .ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName)));

            // 组装返回数据
            var result = entities.Select(item => new LqReimbursementApplicationListOutput
            {
                id = item.Id,
                applicationUserId = item.ApplicationUserId,
                applicationUserName = item.ApplicationUserName,
                applicationStoreId = item.ApplicationStoreId,
                applicationTime = item.ApplicationTime,
                amount = item.Amount,
                approveUser = item.ApproveUser,
                approveStatus = item.ApprovalStatus ?? item.ApproveStatus,
                approveTime = item.ApproveTime,
                purchaseRecordsId = item.PurchaseRecordsId,
                currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null,
                currentNodeOrder = item.CurrentNodeOrder,
                nodeCount = item.NodeCount
            }).ToList();

            return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<LqReimbursementApplicationListOutput>
                {
                    list = result,
                    pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total }
                });
        }

        /// <summary>
        /// 新建报销申请表
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] LqReimbursementApplicationCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<LqReimbursementApplicationEntity>();
            entity.Id = YitIdHelper.NextId().ToString();

            try
            {
                //开启事务
                _db.BeginTran();

                // 1. 验证节点配置
                if (input.nodes == null || input.nodes.Count < 3 || input.nodes.Count > 5)
                {
                    throw new Exception("节点数量必须在3-5个之间");
                }

                // 验证节点顺序是否连续(1, 2, 3, ...)
                var nodeOrders = input.nodes.Select(n => n.nodeOrder).OrderBy(x => x).ToList();
                for (int i = 0; i < nodeOrders.Count; i++)
                {
                    if (nodeOrders[i] != i + 1)
                    {
                        throw new Exception($"节点顺序必须连续,从1开始");
                    }
                }

                // 验证每个节点至少有一个审批人
                foreach (var node in input.nodes)
                {
                    if (node.approverIds == null || node.approverIds.Count == 0)
                    {
                        throw new Exception($"节点{node.nodeOrder}({node.nodeName})必须至少指定一个审批人");
                    }
                }

                // 2. 设置报销申请初始状态
                entity.NodeCount = input.nodes.Count;
                entity.CurrentNodeOrder = 0;
                entity.ApprovalStatus = "待审批";
                entity.ApplicationTime = DateTime.Now;
                if (string.IsNullOrEmpty(entity.ApplicationUserId))
                {
                    entity.ApplicationUserId = userInfo.userId;
                }
                if (string.IsNullOrEmpty(entity.ApplicationUserName))
                {
                    entity.ApplicationUserName = userInfo.userName;
                }

                // 3. 保存报销申请表(不使用IgnoreColumns,确保新字段被保存)
                var isOk = await _db.Insertable(entity).ExecuteCommandAsync();
                if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);

                // 4. 创建节点配置
                if (input.nodes != null && input.nodes.Count > 0)
                {
                    foreach (var nodeConfig in input.nodes)
                    {
                        var node = new LqReimbursementApplicationNodeEntity
                        {
                            Id = YitIdHelper.NextId().ToString(),
                            ApplicationId = entity.Id,
                            NodeOrder = nodeConfig.nodeOrder,
                            NodeName = nodeConfig.nodeName,
                            ApprovalType = nodeConfig.approvalType ?? "会签",
                            IsRequired = 1,
                            CreateTime = DateTime.Now
                        };
                        var nodeResult = await _db.Insertable(node).ExecuteCommandAsync();
                        if (nodeResult <= 0)
                        {
                            throw new Exception($"创建节点{nodeConfig.nodeOrder}失败");
                        }

                        // 5. 创建节点审批人
                        if (nodeConfig.approverIds != null && nodeConfig.approverIds.Count > 0)
                        {
                            for (int i = 0; i < nodeConfig.approverIds.Count; i++)
                            {
                                var nodeUser = new LqReimbursementApplicationNodeUserEntity
                                {
                                    Id = YitIdHelper.NextId().ToString(),
                                    ApplicationId = entity.Id,
                                    NodeId = node.Id,
                                    NodeOrder = nodeConfig.nodeOrder,
                                    UserId = nodeConfig.approverIds[i],
                                    UserName = nodeConfig.approverNames != null && i < nodeConfig.approverNames.Count
                                        ? nodeConfig.approverNames[i]
                                        : null,
                                    SortOrder = i + 1,
                                    CreateTime = DateTime.Now
                                };
                                var userResult = await _db.Insertable(nodeUser).ExecuteCommandAsync();
                                if (userResult <= 0)
                                {
                                    throw new Exception($"创建节点{nodeConfig.nodeOrder}的审批人{nodeConfig.approverIds[i]}失败");
                                }
                            }
                        }
                    }
                }

                // 6. 更新购买记录的审批单编号和审批状态为"待审批"
                if (input.selectedPurchaseRecordIds != null && input.selectedPurchaseRecordIds.Count > 0)
                {
                    // 先更新ApplicationId
                    await _db.Updateable<LqPurchaseRecordsEntity>()
                        .SetColumns(it => it.ApplicationId == entity.Id)
                        .Where(it => input.selectedPurchaseRecordIds.Contains(it.Id))
                        .ExecuteCommandAsync();

                    // 再更新ApproveStatus(分开更新确保都能执行)
                    await _db.Updateable<LqPurchaseRecordsEntity>()
                        .SetColumns(it => it.ApproveStatus == "待审批")
                        .Where(it => input.selectedPurchaseRecordIds.Contains(it.Id))
                        .ExecuteCommandAsync();
                }

                //关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                //回滚事务
                _db.RollbackTran();
                throw;
            }
        }

        /// <summary>
		/// 获取报销申请表无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] LqReimbursementApplicationListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            List<string> queryApplicationTime = input.applicationTime != null ? input.applicationTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.First()) : null;
            DateTime? endApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.Last()) : null;
            List<string> queryApproveTime = input.approveTime != null ? input.approveTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.First()) : null;
            DateTime? endApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.Last()) : null;
            var data = await _db.Queryable<LqReimbursementApplicationEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
                .WhereIF(!string.IsNullOrEmpty(input.applicationUserId), p => p.ApplicationUserId.Contains(input.applicationUserId))
                .WhereIF(!string.IsNullOrEmpty(input.applicationUserName), p => p.ApplicationUserName.Contains(input.applicationUserName))
                .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
                .WhereIF(queryApplicationTime != null, p => p.ApplicationTime >= new DateTime(startApplicationTime.ToDate().Year, startApplicationTime.ToDate().Month, startApplicationTime.ToDate().Day, 0, 0, 0))
                .WhereIF(queryApplicationTime != null, p => p.ApplicationTime <= new DateTime(endApplicationTime.ToDate().Year, endApplicationTime.ToDate().Month, endApplicationTime.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.amount), p => p.Amount.Contains(input.amount))
                .WhereIF(!string.IsNullOrEmpty(input.approveUser), p => p.ApproveUser.Equals(input.approveUser))
                .WhereIF(!string.IsNullOrEmpty(input.approveStatus), p => p.ApproveStatus.Contains(input.approveStatus))
                //    .WhereIF(queryApproveTime != null, p => p.ApproveTime >= new DateTime(startApproveTime.ToDate().Year, startApproveTime.ToDate().Month, startApproveTime.ToDate().Day, 0, 0, 0))
                //      .WhereIF(queryApproveTime != null, p => p.ApproveTime <= new DateTime(endApproveTime.ToDate().Year, endApproveTime.ToDate().Month, endApproveTime.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.purchaseRecordsId), p => p.PurchaseRecordsId.Contains(input.purchaseRecordsId))
                .Select(it => new LqReimbursementApplicationListOutput
                {
                    id = it.Id,
                    applicationUserId = it.ApplicationUserId,
                    applicationUserName = it.ApplicationUserName,
                    applicationStoreId = it.ApplicationStoreId,
                    applicationTime = it.ApplicationTime,
                    amount = it.Amount,
                    approveUser = it.ApproveUser,
                    approveStatus = it.ApproveStatus,
                    approveTime = it.ApproveTime,
                    purchaseRecordsId = it.PurchaseRecordsId,
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToListAsync();
            return data;
        }

        /// <summary>
		/// 导出报销申请表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] LqReimbursementApplicationListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<LqReimbursementApplicationListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<PageResult<LqReimbursementApplicationListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"申请编号\",\"field\":\"id\"},{\"value\":\"申请人编号\",\"field\":\"applicationUserId\"},{\"value\":\"申请人姓名\",\"field\":\"applicationUserName\"},{\"value\":\"申请门店\",\"field\":\"applicationStoreId\"},{\"value\":\"申请时间\",\"field\":\"applicationTime\"},{\"value\":\"总金额\",\"field\":\"amount\"},{\"value\":\"审批人\",\"field\":\"approveUser\"},{\"value\":\"审批结果\",\"field\":\"approveStatus\"},{\"value\":\"审批时间\",\"field\":\"approveTime\"},{\"value\":\"关联购买编号\",\"field\":\"purchaseRecordsId\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "报销申请表.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<LqReimbursementApplicationListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
            };
            return output;
        }

        /// <summary>
        /// 批量删除报销申请表
        /// </summary>
        /// <param name="ids">主键数组</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _db.Queryable<LqReimbursementApplicationEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //批量删除报销申请表
                    await _db.Deleteable<LqReimbursementApplicationEntity>().In(d => d.Id, ids).ExecuteCommandAsync();
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw NCCException.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新报销申请表
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] LqReimbursementApplicationUpInput input)
        {
            try
            {
                //开启事务
                _db.BeginTran();

                // 获取原有的关联购买记录ID
                var oldEntity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
                var oldIds = new List<string>();
                if (oldEntity != null && !string.IsNullOrEmpty(oldEntity.PurchaseRecordsId))
                {
                    // 获取原有购买记录ID列表
                    oldIds = oldEntity.PurchaseRecordsId.Split(',').Where(x => !string.IsNullOrEmpty(x)).ToList();
                }

                // 获取新的购买记录ID列表
                var newIds = input.selectedPurchaseRecordIds ?? new List<string>();

                // 确保 purchaseRecordsId 字段包含所有选中的记录ID(逗号分隔)
                if (newIds.Count > 0)
                {
                    input.purchaseRecordsId = string.Join(",", newIds);
                }
                else
                {
                    input.purchaseRecordsId = null;
                }

                // 找出需要移除关联的记录(在旧列表中但不在新列表中)
                var idsToRemove = oldIds.Where(x => !newIds.Contains(x)).ToList();
                if (idsToRemove.Count > 0)
                {
                    // 清除这些购买记录的审批单编号和审批状态
                    await _db.Updateable<LqPurchaseRecordsEntity>()
                        .SetColumns(it => new LqPurchaseRecordsEntity
                        {
                            ApplicationId = null,
                            ApproveStatus = "未审批"
                        })
                        .Where(it => idsToRemove.Contains(it.Id))
                        .ExecuteCommandAsync();
                }

                // 更新报销申请表(确保 purchaseRecordsId 字段被正确更新)
                var entity = input.Adapt<LqReimbursementApplicationEntity>();
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);

                // 更新所有选中的购买记录的审批单编号和审批状态为"待审批"
                // 包括新追加的记录和已存在的记录(确保状态正确)
                if (newIds.Count > 0)
                {
                    // 先更新ApplicationId
                    await _db.Updateable<LqPurchaseRecordsEntity>()
                        .SetColumns(it => it.ApplicationId == id)
                        .Where(it => newIds.Contains(it.Id))
                        .ExecuteCommandAsync();

                    // 再更新ApproveStatus(分开更新确保都能执行)
                    await _db.Updateable<LqPurchaseRecordsEntity>()
                        .SetColumns(it => it.ApproveStatus == "待审批")
                        .Where(it => newIds.Contains(it.Id))
                        .ExecuteCommandAsync();
                }

                //关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                //回滚事务
                _db.RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 删除报销申请表
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<LqReimbursementApplicationEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
        }

        /// <summary>
        /// 提交审批(进入第一个节点)
        /// </summary>
        /// <param name="id">申请编号</param>
        /// <returns></returns>
        [HttpPost("{id}/Actions/SubmitApproval")]
        public async Task SubmitApproval(string id)
        {
            var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);

            // 允许"待审批"和"已退回"状态的申请提交审批
            if (entity.CurrentNodeOrder != 0 && entity.ApprovalStatus != "已退回")
            {
                throw new Exception("该申请已经提交审批,不能重复提交");
            }

            if (entity.NodeCount == null || entity.NodeCount < 3 || entity.NodeCount > 5)
            {
                throw new Exception("节点配置异常,无法提交审批");
            }

            try
            {
                _db.BeginTran();

                // 获取第一个节点
                var firstNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
                    .Where(x => x.ApplicationId == id && x.NodeOrder == 1)
                    .FirstAsync();

                if (firstNode == null)
                {
                    throw new Exception("未找到第一个审批节点配置");
                }

                // 更新报销申请状态
                entity.CurrentNodeOrder = 1;
                entity.CurrentNodeId = firstNode.Id;
                entity.ApprovalStatus = "审批中";
                await _db.Updateable(entity).ExecuteCommandAsync();

                // 为第一个节点的每个审批人创建待审批记录
                var firstNodeApprovers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                    .Where(x => x.ApplicationId == id && x.NodeOrder == 1)
                    .ToListAsync();

                foreach (var approver in firstNodeApprovers)
                {
                    var record = new LqReimbursementApprovalRecordEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        ApplicationId = id,
                        NodeId = firstNode.Id,
                        NodeOrder = 1,
                        ApproverId = approver.UserId,
                        ApproverName = approver.UserName,
                        ApprovalResult = "待审批",
                        IsCurrentNode = 1,
                        ApprovalTime = null
                    };
                    await _db.Insertable(record).ExecuteCommandAsync();
                }

                _db.CommitTran();
            }
            catch (Exception)
            {
                _db.RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 审批操作(通过/不通过/退回)
        /// </summary>
        /// <param name="id">申请编号</param>
        /// <param name="result">审批结果:通过/不通过/退回</param>
        /// <param name="opinion">审批意见</param>
        /// <returns></returns>
        [HttpPost("{id}/Actions/Approve")]
        public async Task Approve(string id, [FromQuery] string result, [FromQuery] string opinion = "")
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);

            if (entity.CurrentNodeOrder == null || entity.CurrentNodeOrder == 0)
            {
                throw new Exception("该申请尚未提交审批");
            }

            if (entity.ApprovalStatus != "审批中")
            {
                throw new Exception($"该申请当前状态为{entity.ApprovalStatus},无法进行审批操作");
            }

            // 验证当前用户是否有审批权限(管理员可以审批所有节点)
            var isAdmin = userInfo.isAdministrator;
            if (!isAdmin)
            {
                var hasPermission = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                    .Where(x => x.ApplicationId == id
                        && x.NodeOrder == entity.CurrentNodeOrder
                        && x.UserId == userInfo.userId)
                    .AnyAsync();

                if (!hasPermission)
                {
                    throw new Exception("您没有当前节点的审批权限");
                }
            }

            // 检查是否已经审批过
            var hasApproved = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
                .Where(x => x.ApplicationId == id
                    && x.NodeOrder == entity.CurrentNodeOrder
                    && x.ApproverId == userInfo.userId
                    && x.ApprovalResult != "待审批")
                .AnyAsync();

            if (hasApproved)
            {
                throw new Exception("您已经审批过该节点");
            }

            try
            {
                _db.BeginTran();

                // 获取当前节点信息
                var currentNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
                    .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
                    .FirstAsync();

                if (currentNode == null)
                {
                    throw new Exception("未找到当前节点配置");
                }

                // 更新待审批记录为已审批(如果存在待审批记录)
                var existingRecord = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
                    .Where(x => x.ApplicationId == id
                        && x.NodeOrder == entity.CurrentNodeOrder
                        && x.ApproverId == userInfo.userId
                        && x.ApprovalResult == "待审批")
                    .FirstAsync();

                if (existingRecord != null)
                {
                    // 更新现有记录
                    existingRecord.ApprovalResult = result;
                    existingRecord.ApprovalOpinion = opinion;
                    existingRecord.ApprovalTime = DateTime.Now;
                    await _db.Updateable(existingRecord).ExecuteCommandAsync();
                }
                else
                {
                    // 创建新记录(如果不存在)
                    var approvalRecord = new LqReimbursementApprovalRecordEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        ApplicationId = id,
                        NodeId = currentNode.Id,
                        NodeOrder = entity.CurrentNodeOrder.Value,
                        ApproverId = userInfo.userId,
                        ApproverName = userInfo.userName,
                        ApprovalResult = result,
                        ApprovalOpinion = opinion,
                        ApprovalTime = DateTime.Now,
                        IsCurrentNode = 1
                    };
                    await _db.Insertable(approvalRecord).ExecuteCommandAsync();
                }

                // 根据审批结果处理
                if (result == "不通过")
                {
                    // 不通过:审批结束
                    entity.ApprovalStatus = "未通过";
                    await _db.Updateable(entity).ExecuteCommandAsync();

                    // 更新所有购买记录状态为"未通过"(通过ApplicationId关联更新)
                    await _db.Updateable<LqPurchaseRecordsEntity>()
                        .SetColumns(it => new LqPurchaseRecordsEntity
                        {
                            ApproveStatus = "未通过",
                            ApproveTime = DateTime.Now,
                            ApproveUser = userInfo.userId
                        })
                        .Where(it => it.ApplicationId == id)
                        .ExecuteCommandAsync();
                }
                else if (result == "退回")
                {
                    // 退回:退回到上一节点
                    if (entity.CurrentNodeOrder == 1)
                    {
                        // 退回到申请人
                        entity.CurrentNodeOrder = 0;
                        entity.ApprovalStatus = "已退回";
                        entity.ReturnedNodeOrder = 0;
                        entity.ReturnedReason = opinion;
                        entity.CurrentNodeId = null;
                    }
                    else
                    {
                        // 退回到上一节点
                        entity.CurrentNodeOrder -= 1;
                        entity.ReturnedNodeOrder = entity.CurrentNodeOrder;
                        entity.ReturnedReason = opinion;

                        // 获取上一节点信息
                        var prevNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
                            .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
                            .FirstAsync();

                        if (prevNode != null)
                        {
                            entity.CurrentNodeId = prevNode.Id;
                        }

                        // 清除上一节点的所有审批记录(重新审批)
                        await _db.Deleteable<LqReimbursementApprovalRecordEntity>()
                            .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
                            .ExecuteCommandAsync();

                        // 为上一节点的每个审批人创建新的待审批记录
                        var prevNodeApprovers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                            .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
                            .ToListAsync();

                        foreach (var approver in prevNodeApprovers)
                        {
                            var record = new LqReimbursementApprovalRecordEntity
                            {
                                Id = YitIdHelper.NextId().ToString(),
                                ApplicationId = id,
                                NodeId = prevNode.Id,
                                NodeOrder = entity.CurrentNodeOrder.Value,
                                ApproverId = approver.UserId,
                                ApproverName = approver.UserName,
                                ApprovalResult = "待审批",
                                IsCurrentNode = 1,
                                ApprovalTime = null
                            };
                            await _db.Insertable(record).ExecuteCommandAsync();
                        }
                    }

                    await _db.Updateable(entity).ExecuteCommandAsync();
                }
                else if (result == "通过")
                {
                    // 通过:判断是否需要进入下一个节点
                    bool shouldMoveToNext = false;

                    if (currentNode.ApprovalType == "或签")
                    {
                        // 或签:任意一个审批人通过,立即进入下一个节点
                        shouldMoveToNext = true;
                    }
                    else // 会签
                    {
                        // 会签:检查是否所有审批人都已通过
                        var approvers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                            .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
                            .Select(x => x.UserId)
                            .ToListAsync();

                        var approvedUsers = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
                            .Where(x => x.ApplicationId == id
                                && x.NodeOrder == entity.CurrentNodeOrder
                                && x.ApprovalResult == "通过")
                            .Select(x => x.ApproverId)
                            .Distinct()
                            .ToListAsync();

                        if (approvers.Count == approvedUsers.Count)
                        {
                            // 所有人都已通过
                            shouldMoveToNext = true;
                        }
                    }

                    if (shouldMoveToNext)
                    {
                        // 进入下一个节点或完成审批
                        await MoveToNextNode(id, userInfo.userId);
                    }
                }

                _db.CommitTran();
            }
            catch (Exception)
            {
                _db.RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 进入下一个节点
        /// </summary>
        private async Task MoveToNextNode(string applicationId, string approveUserId)
        {
            var entity = await _db.Queryable<LqReimbursementApplicationEntity>()
                .FirstAsync(x => x.Id == applicationId);

            // 判断是否是最后一个节点
            if (entity.CurrentNodeOrder >= entity.NodeCount)
            {
                // 审批完成
                entity.CurrentNodeOrder = entity.NodeCount + 1;
                entity.ApprovalStatus = "已通过";
                entity.CurrentNodeId = null;
                await _db.Updateable(entity).ExecuteCommandAsync();

                // 更新所有购买记录状态为"已审批"
                // 通过ApplicationId关联更新,因为PurchaseRecordsId可能为空
                await _db.Updateable<LqPurchaseRecordsEntity>()
                    .SetColumns(it => new LqPurchaseRecordsEntity
                    {
                        ApproveStatus = "已审批",
                        ApproveTime = DateTime.Now,
                        ApproveUser = approveUserId
                    })
                    .Where(it => it.ApplicationId == applicationId)
                    .ExecuteCommandAsync();
            }
            else
            {
                // 进入下一个节点
                entity.CurrentNodeOrder += 1;

                // 获取下一个节点信息
                var nextNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
                    .Where(x => x.ApplicationId == applicationId && x.NodeOrder == entity.CurrentNodeOrder)
                    .FirstAsync();

                if (nextNode == null)
                {
                    throw new Exception($"未找到节点{entity.CurrentNodeOrder}的配置");
                }

                entity.CurrentNodeId = nextNode.Id;
                entity.ApprovalStatus = "审批中";
                await _db.Updateable(entity).ExecuteCommandAsync();

                // 清除之前的当前节点标记
                await _db.Updateable<LqReimbursementApprovalRecordEntity>()
                    .SetColumns(it => new LqReimbursementApprovalRecordEntity { IsCurrentNode = 0 })
                    .Where(it => it.ApplicationId == applicationId)
                    .ExecuteCommandAsync();

                // 为下一个节点的每个审批人创建待审批记录
                var nextNodeApprovers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                    .Where(x => x.ApplicationId == applicationId && x.NodeOrder == entity.CurrentNodeOrder)
                    .ToListAsync();

                foreach (var approver in nextNodeApprovers)
                {
                    var record = new LqReimbursementApprovalRecordEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        ApplicationId = applicationId,
                        NodeId = nextNode.Id,
                        NodeOrder = entity.CurrentNodeOrder.Value,
                        ApproverId = approver.UserId,
                        ApproverName = approver.UserName,
                        ApprovalResult = "待审批",
                        IsCurrentNode = 1,
                        ApprovalTime = null
                    };
                    await _db.Insertable(record).ExecuteCommandAsync();
                }
            }
        }

        /// <summary>
        /// 获取所有待办列表(管理员用,所有待审批的申请)
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns></returns>
        [HttpGet("Actions/AllPendingApproval")]
        public async Task<dynamic> GetAllPendingApprovalList([FromQuery] LqReimbursementApplicationListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;

            // 管理员可以查看所有待审批的申请
            var query = _db.Queryable<LqReimbursementApplicationEntity>()
                .Where(x => x.ApprovalStatus == "审批中")
                .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
                .OrderBy(sidx + " " + input.sort);

            var total = await query.CountAsync();
            var entities = await query.ToPageListAsync(input.currentPage, input.pageSize);

            // 获取当前审批人信息
            var applicationIds = entities.Select(x => x.Id).ToList();
            var currentApprovers = new List<dynamic>();
            if (applicationIds.Any())
            {
                var approverList = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                    .Where(x => applicationIds.Contains(x.ApplicationId))
                    .InnerJoin<LqReimbursementApplicationEntity>((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder)
                    .Select((u, a) => new
                    {
                        applicationId = a.Id,
                        approverName = u.UserName
                    })
                    .ToListAsync();
                currentApprovers = approverList.Cast<dynamic>().ToList();
            }

            var approverDict = currentApprovers
                .GroupBy(x => (string)x.applicationId)
                .ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName)));

            // 组装返回数据
            var result = entities.Select(item => new LqReimbursementApplicationListOutput
            {
                id = item.Id,
                applicationUserId = item.ApplicationUserId,
                applicationUserName = item.ApplicationUserName,
                applicationStoreId = item.ApplicationStoreId,
                applicationTime = item.ApplicationTime,
                amount = item.Amount,
                approveUser = item.ApproveUser,
                approveStatus = item.ApprovalStatus ?? item.ApproveStatus,
                approveTime = item.ApproveTime,
                purchaseRecordsId = item.PurchaseRecordsId,
                currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null,
                currentNodeOrder = item.CurrentNodeOrder,
                nodeCount = item.NodeCount
            }).ToList();

            return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<LqReimbursementApplicationListOutput>
                {
                    list = result,
                    pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total }
                });
        }

        /// <summary>
        /// 获取待审批列表(当前用户作为审批人的申请)
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns></returns>
        [HttpGet("Actions/PendingApproval")]
        public async Task<dynamic> GetPendingApprovalList([FromQuery] LqReimbursementApplicationListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var sidx = input.sidx == null ? "id" : input.sidx;

            // 查询当前用户作为审批人的节点
            var userNodeOrders = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                .Where(x => x.UserId == userInfo.userId)
                .Select(x => new { x.ApplicationId, x.NodeOrder })
                .ToListAsync();

            if (!userNodeOrders.Any())
            {
                return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
                    new SqlSugarPagedList<LqReimbursementApplicationListOutput>
                    {
                        list = new List<LqReimbursementApplicationListOutput>(),
                        pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = 0 }
                    });
            }

            // 获取用户有权限的申请ID和节点顺序
            var userApplications = userNodeOrders
                .GroupBy(x => x.ApplicationId)
                .ToDictionary(g => g.Key, g => g.Select(x => x.NodeOrder).ToList());

            var applicationIds = userApplications.Keys.ToList();

            // 查询这些申请中,当前节点是用户有权限的节点,且状态为"审批中"的申请
            var query = _db.Queryable<LqReimbursementApplicationEntity>()
                .Where(x => applicationIds.Contains(x.Id) && x.ApprovalStatus == "审批中")
                .Where(x => userApplications.ContainsKey(x.Id)
                    && userApplications[x.Id].Contains(x.CurrentNodeOrder ?? 0))
                .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
                .OrderBy(sidx + " " + input.sort);

            var total = await query.CountAsync();
            var entities = await query.ToPageListAsync(input.currentPage, input.pageSize);

            // 获取当前审批人信息
            var resultApplicationIds = entities.Select(x => x.Id).ToList();
            var currentApprovers = new List<dynamic>();
            if (resultApplicationIds.Any())
            {
                var approverList = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
                    .Where(x => resultApplicationIds.Contains(x.ApplicationId))
                    .InnerJoin<LqReimbursementApplicationEntity>((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder)
                    .Select((u, a) => new
                    {
                        applicationId = a.Id,
                        approverName = u.UserName
                    })
                    .ToListAsync();
                currentApprovers = approverList.Cast<dynamic>().ToList();
            }

            var approverDict = currentApprovers
                .GroupBy(x => (string)x.applicationId)
                .ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName)));

            // 组装返回数据
            var result = entities.Select(item => new LqReimbursementApplicationListOutput
            {
                id = item.Id,
                applicationUserId = item.ApplicationUserId,
                applicationUserName = item.ApplicationUserName,
                applicationStoreId = item.ApplicationStoreId,
                applicationTime = item.ApplicationTime,
                amount = item.Amount,
                approveUser = item.ApproveUser,
                approveStatus = item.ApprovalStatus ?? item.ApproveStatus,
                approveTime = item.ApproveTime,
                purchaseRecordsId = item.PurchaseRecordsId,
                currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null,
                currentNodeOrder = item.CurrentNodeOrder,
                nodeCount = item.NodeCount
            }).ToList();

            return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<LqReimbursementApplicationListOutput>
                {
                    list = result,
                    pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total }
                });
        }

        /// <summary>
        /// 获取审批历史
        /// </summary>
        /// <param name="id">申请编号</param>
        /// <returns></returns>
        [HttpGet("{id}/Actions/ApprovalHistory")]
        public async Task<dynamic> GetApprovalHistory(string id)
        {
            // 先查询审批记录
            var approvalRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
                .Where(x => x.ApplicationId == id)
                .OrderBy(x => x.NodeOrder)
                .OrderBy(x => x.ApprovalTime)
                .ToListAsync();

            // 获取节点信息
            if (approvalRecords.Any())
            {
                var nodeIds = approvalRecords.Select(x => x.NodeId).Distinct().ToList();
                var nodes = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
                    .Where(x => nodeIds.Contains(x.Id))
                    .ToListAsync();

                var nodeDict = nodes.ToDictionary(x => x.Id, x => x.NodeName);

                // 组装结果
                var records = approvalRecords.Select(r => new
                {
                    nodeOrder = r.NodeOrder,
                    nodeName = nodeDict.ContainsKey(r.NodeId) ? nodeDict[r.NodeId] : null,
                    approverName = r.ApproverName,
                    approvalResult = r.ApprovalResult,
                    approvalOpinion = r.ApprovalOpinion,
                    approvalTime = r.ApprovalTime
                }).ToList();

                return records;
            }

            return new List<object>();
        }
    }
}