LqAttendanceRestSettlementService.cs 49.4 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 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqAttendanceRecord;
using NCC.Extend.Entitys.Dto.LqAttendanceRestSettlement;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.flow_task;
using NCC.Extend.Entitys.lq_attendance_group;
using NCC.Extend.Entitys.lq_attendance_record;
using NCC.Extend.Entitys.lq_attendance_rest_group;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.wform_leaveapply;
using NCC.Extend.Helpers;
using NCC.Extend.Interfaces.BusinessOperationLog;
using NCC.Extend.Interfaces.LqAttendanceRestSettlement;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using Newtonsoft.Json;
using SqlSugar;
using Yitter.IdGenerator;

namespace NCC.Extend
{
    /// <summary>
    /// 月末应休结算
    /// </summary>
    [ApiDescriptionSettings(Tag = "绿纤应休结算", Name = "LqAttendanceRestSettlement", Order = 201)]
    [Route("api/Extend/[controller]")]
    [ApiController]
    public class LqAttendanceRestSettlementService : ILqAttendanceRestSettlementService, IDynamicApiController, ITransient
    {
        private const string BizModule = "考勤应休结算";
        private const string ActionSettleToPersonal = "应休转事假";
        private const string ActionRevertToOriginal = "回归原始打卡数据";
        private const int FlowTaskStatusAdopt = 2;

        private readonly ISqlSugarClient _db;
        private readonly IUserManager _userManager;
        private readonly IBusinessOperationLogService _businessOperationLogService;
        private readonly ILogger<LqAttendanceRestSettlementService> _logger;

        public LqAttendanceRestSettlementService(
            ISqlSugarClient db,
            IUserManager userManager,
            IBusinessOperationLogService businessOperationLogService,
            ILogger<LqAttendanceRestSettlementService> logger)
        {
            _db = db;
            _userManager = userManager;
            _businessOperationLogService = businessOperationLogService;
            _logger = logger;
        }

        /// <summary>
        /// 预览指定年月应休结算(不落库)
        /// </summary>
        /// <remarks>
        /// 按带薪上班天数÷应休规则 N 计算应得应休,列出将从后往前转事假或改回应休的时段。
        ///
        /// 示例请求:
        /// `GET /api/Extend/LqAttendanceRestSettlement/Preview?year=2026&amp;month=9&amp;userId=`
        ///
        /// 参数说明:
        /// - year: 年
        /// - month: 月
        /// - userId: 可选,仅预览该员工
        /// </remarks>
        /// <param name="year">年</param>
        /// <param name="month">月</param>
        /// <param name="userId">员工ID,可空</param>
        /// <returns>预览结果</returns>
        /// <response code="200">预览成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpGet("Preview")]
        public Task<dynamic> Preview(
            [FromQuery] int year,
            [FromQuery] int month,
            [FromQuery] string userId = null,
            [FromQuery] int? restUnlockCycle = null,
            [FromQuery] int? monthlyRestDays = null)
        {
            return SettleMonthAsync(new AttendanceRestMonthSettlementInput
            {
                year = year,
                month = month,
                userId = userId,
                dryRun = true,
                restUnlockCycle = restUnlockCycle,
                monthlyRestDays = monthlyRestDays
            });
        }

        /// <summary>
        /// 结算指定年月应休(未满月仅预览不落库)
        /// </summary>
        /// <remarks>
        /// 按带薪上班天数计算应得应休;未满月按截至当天已有考勤计算,但<strong>默认只预览不落库</strong>,月末后方可正式结算落库。
        /// 已请应休超过应得的,从该月最后应休时段往前改为事假,并回写已通过休假单(整单改假种或拆单)。
        /// 之后上班天数增加再结算可改回。未来月份不能落库。dryRun 为 true 时始终不落库。
        ///
        /// 示例请求:
        /// ```json
        /// { "year": 2026, "month": 10, "userId": "", "dryRun": true }
        /// ```
        ///
        /// 参数说明:
        /// - year: 年
        /// - month: 月
        /// - userId: 可选
        /// - dryRun: true 只预览
        /// </remarks>
        /// <param name="input">结算入参</param>
        /// <returns>结算结果</returns>
        /// <response code="200">成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("Settle")]
        public Task<dynamic> SettleMonthAsync([FromBody] AttendanceRestMonthSettlementInput input)
        {
            return SettleMonthCoreAsync(input);
        }

        /// <summary>
        /// 回归原始打卡数据
        /// </summary>
        /// <remarks>
        /// 撤销指定年月月末应休结算对请假单与考勤关联的改写:假种回休假、删除拆单 JS 单、考勤 JSON/备注按 original* 还原;不删除原始打卡时刻。
        /// 对该月每人将 desiredConverted 置 0,已 Converted 段全部走改回逻辑;未满月也可落库(dryRun 为 true 时仍只预览)。
        ///
        /// 示例请求:
        /// ```json
        /// { "year": 2026, "month": 10, "userId": "", "dryRun": false }
        /// ```
        ///
        /// 参数说明:
        /// - year: 年
        /// - month: 月
        /// - userId: 可选,仅处理该员工
        /// - dryRun: true 只预览不落库
        /// </remarks>
        /// <param name="input">年月与可选员工、是否预览</param>
        /// <returns>改回段数、涉及人数等汇总</returns>
        /// <response code="200">成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器错误</response>
        [HttpPost("RevertToOriginal")]
        public Task<dynamic> RevertToOriginalAsync([FromBody] AttendanceRestMonthSettlementInput input)
        {
            input ??= new AttendanceRestMonthSettlementInput();
            input.forceRevertConverted = true;
            return SettleMonthCoreAsync(input);
        }

        private async Task<dynamic> SettleMonthCoreAsync(AttendanceRestMonthSettlementInput input)
        {
            input ??= new AttendanceRestMonthSettlementInput();
            if (input.year < 2000 || input.year > 3000)
            {
                throw NCCException.Oh("年份参数无效");
            }

            if (input.month < 1 || input.month > 12)
            {
                throw NCCException.Oh("月份无效");
            }

            var today = DateTime.Today;
            var isFutureMonth = input.year > today.Year
                || (input.year == today.Year && input.month > today.Month);
            if (isFutureMonth && !input.dryRun && !input.forceRevertConverted)
            {
                throw NCCException.Oh("未来月份不能结算应休");
            }

            if (isFutureMonth && !input.dryRun && input.forceRevertConverted)
            {
                throw NCCException.Oh("未来月份不能回归原始打卡数据");
            }

            var monthClosed = AttendanceRestMonthSettlementHelper.IsMonthClosed(input.year, input.month, today);
            var persist = !input.dryRun && !isFutureMonth && (monthClosed || input.forceRevertConverted);
            var batchActionCode = input.forceRevertConverted ? ActionRevertToOriginal : ActionSettleToPersonal;
            var monthStart = new DateTime(input.year, input.month, 1);
            var monthEnd = AttendanceRestMonthSettlementHelper.GetSettleRecordEnd(input.year, input.month, today);
            var batchId = YitIdHelper.NextId().ToString();

            var users = await LoadTargetUsersAsync(input.userId, monthStart, monthEnd);
            if (input.skipUserIds != null && input.skipUserIds.Count > 0)
            {
                var skip = new HashSet<string>(
                    input.skipUserIds.Where(x => !string.IsNullOrWhiteSpace(x)),
                    StringComparer.Ordinal);
                users = users.Where(x => !skip.Contains(x.Id)).ToList();
            }
            var userResults = new List<object>();
            var changedUserCount = 0;
            var convertedCount = 0;
            var revertedCount = 0;

            foreach (var user in users)
            {
                var restGroup = await ResolveRestGroupAsync(user);
                var cycle = restGroup?.RestUnlockCycle ?? 0;
                var monthlyCap = restGroup?.MonthlyRestDays ?? 0;
                if (!string.IsNullOrWhiteSpace(input.userId) && input.restUnlockCycle.GetValueOrDefault() > 0)
                {
                    cycle = input.restUnlockCycle.Value;
                }

                if (!string.IsNullOrWhiteSpace(input.userId) && input.monthlyRestDays.GetValueOrDefault() > 0)
                {
                    monthlyCap = input.monthlyRestDays.Value;
                }

                if (cycle <= 0 || monthlyCap < 0)
                {
                    continue;
                }

                var records = await _db.Queryable<LqAttendanceRecordEntity>()
                    .Where(x => x.UserId == user.Id
                        && x.IsEffective == StatusEnum.有效.GetHashCode()
                        && x.AttendanceDate >= monthStart
                        && x.AttendanceDate < monthEnd)
                    .ToListAsync();
                var perDay = AttendanceSummaryMonthMetricsHelper.CollapseToLatestPerDay(records);
                var paidWork = AttendanceRestMonthSettlementHelper.CalcPaidWorkDays(perDay);
                var entitled = AttendanceRestMonthSettlementHelper.CalcEntitledRestDays(paidWork, cycle, monthlyCap);
                var segments = AttendanceRestMonthSettlementHelper.CollectRestSegments(perDay);
                var currentRest = segments.Where(x => !x.Converted).Sum(x => x.Days);
                var converted = segments.Where(x => x.Converted).Sum(x => x.Days);
                var desiredConverted = input.forceRevertConverted
                    ? 0m
                    : Math.Max(0m, currentRest + converted - entitled);
                var actions = BuildActions(
                    segments,
                    desiredConverted,
                    converted,
                    input.year,
                    input.month,
                    paidWork,
                    cycle,
                    monthlyCap,
                    entitled,
                    currentRest + converted);

                if (actions.Count == 0 && string.IsNullOrWhiteSpace(input.userId))
                {
                    continue;
                }

                foreach (var action in actions)
                {
                    if (action.Revert)
                    {
                        revertedCount += 1;
                    }
                    else
                    {
                        convertedCount += 1;
                    }
                }

                if (persist && actions.Count > 0)
                {
                    foreach (var action in actions)
                    {
                        if (action.Revert)
                        {
                            await RevertSegmentAsync(action, batchId);
                        }
                        else
                        {
                            await ConvertSegmentAsync(action, batchId);
                        }
                    }

                    await WriteUserLogAsync(
                        user,
                        input,
                        batchId,
                        batchActionCode,
                        paidWork,
                        cycle,
                        monthlyCap,
                        entitled,
                        currentRest,
                        actions);
                }

                if (actions.Count > 0)
                {
                    changedUserCount += 1;
                }

                userResults.Add(new
                {
                    userId = user.Id,
                    userName = user.RealName,
                    paidWorkDays = paidWork,
                    restUnlockCycle = cycle,
                    monthlyRestDays = monthlyCap,
                    entitledRestDays = entitled,
                    submittedRestDays = currentRest,
                    alreadyConvertedDays = converted,
                    desiredConvertedDays = desiredConverted,
                    actions = actions.Select(x => new
                    {
                        revert = x.Revert,
                        date = x.Date.ToString("yyyy-MM-dd"),
                        halfPeriod = x.HalfPeriod,
                        days = x.Days,
                        leaveApplyId = x.LeaveApplyId,
                        billNo = x.BillNo,
                        reason = x.Reason
                    }).ToList()
                });
            }

            string summary;
            if (input.forceRevertConverted)
            {
                summary =
                    $"{input.year}年{input.month}月回归原始打卡数据{(persist ? string.Empty : "预览")}:涉及 {changedUserCount} 人," +
                    $"改回 {revertedCount} 段{(input.dryRun ? "(dryRun)" : string.Empty)}";
            }
            else
            {
                summary =
                    $"{input.year}年{input.month}月应休结算{(persist ? string.Empty : "预览")}:涉及 {changedUserCount} 人," +
                    $"转事假 {convertedCount} 段,改回 {revertedCount} 段";
            }

            if (persist)
            {
                await BusinessOperationLogHelper.SafeWriteAsync(
                    _businessOperationLogService,
                    _logger,
                    BizModule,
                    batchActionCode,
                    "lq_attendance_record",
                    batchId,
                    summary,
                    JsonConvert.SerializeObject(new
                    {
                        input.year,
                        input.month,
                        input.userId,
                        input.dryRun,
                        input.forceRevertConverted,
                        batchId,
                        changedUserCount,
                        convertedCount,
                        revertedCount
                    }));
            }

            var message = BuildSettlementMessage(
                summary,
                persist,
                input.dryRun,
                monthClosed,
                input.forceRevertConverted,
                isFutureMonth,
                today);

            return new
            {
                year = input.year,
                month = input.month,
                dryRun = !persist,
                monthClosed,
                forceRevertConverted = input.forceRevertConverted,
                batchId,
                changedUserCount,
                convertedCount,
                revertedCount,
                message,
                users = userResults
            };
        }

        private static string BuildSettlementMessage(
            string summary,
            bool persist,
            bool dryRun,
            bool monthClosed,
            bool forceRevertConverted,
            bool isFutureMonth,
            DateTime today)
        {
            if (isFutureMonth && !dryRun && !persist)
            {
                return forceRevertConverted
                    ? $"{summary}。未来月份不能回归原始打卡数据。"
                    : $"{summary}。未来月份不能结算。";
            }

            if (persist)
            {
                return summary;
            }

            if (dryRun)
            {
                return $"{summary}。dryRun 预览,不落库。";
            }

            if (!monthClosed && !forceRevertConverted)
            {
                return $"{summary}。未满月仅预览,不落库;按截至 {today:yyyy-MM-dd} 已有考勤计算,月末后方可正式结算。";
            }

            return summary;
        }

        private async Task<List<UserEntity>> LoadTargetUsersAsync(string userId, DateTime monthStart, DateTime monthEnd)
        {
            if (!string.IsNullOrWhiteSpace(userId))
            {
                return await _db.Queryable<UserEntity>()
                    .Where(x => x.Id == userId.Trim() && x.DeleteMark == null)
                    .Select(x => new UserEntity
                    {
                        Id = x.Id,
                        RealName = x.RealName,
                        Mdid = x.Mdid,
                        AttendanceRestGroupId = x.AttendanceRestGroupId
                    })
                    .ToListAsync();
            }

            var userIds = await _db.Queryable<LqAttendanceRecordEntity>()
                .Where(x => x.IsEffective == StatusEnum.有效.GetHashCode()
                    && x.AttendanceDate >= monthStart
                    && x.AttendanceDate < monthEnd)
                .Select(x => x.UserId)
                .Distinct()
                .ToListAsync();
            if (userIds.Count == 0)
            {
                return new List<UserEntity>();
            }

            return await _db.Queryable<UserEntity>()
                .Where(x => userIds.Contains(x.Id) && x.DeleteMark == null)
                .Select(x => new UserEntity
                {
                    Id = x.Id,
                    RealName = x.RealName,
                    Mdid = x.Mdid,
                    AttendanceRestGroupId = x.AttendanceRestGroupId
                })
                .ToListAsync();
        }

        private async Task<LqAttendanceRestGroupEntity> ResolveRestGroupAsync(UserEntity user)
        {
            if (!string.IsNullOrWhiteSpace(user.AttendanceRestGroupId))
            {
                var byUser = await _db.Queryable<LqAttendanceRestGroupEntity>()
                    .Where(x => x.Id == user.AttendanceRestGroupId && SqlFunc.IsNull(x.DeleteMark, 0) == 0)
                    .FirstAsync();
                if (byUser != null)
                {
                    return byUser;
                }
            }

            if (string.IsNullOrWhiteSpace(user.Mdid))
            {
                return null;
            }

            var store = await _db.Queryable<LqMdxxEntity>()
                .Where(x => x.Id == user.Mdid)
                .FirstAsync();
            if (string.IsNullOrWhiteSpace(store?.AttendanceGroupId))
            {
                return null;
            }

            var group = await _db.Queryable<LqAttendanceGroupEntity>()
                .Where(x => x.Id == store.AttendanceGroupId && SqlFunc.IsNull(x.DeleteMark, 0) == 0)
                .FirstAsync();
            if (string.IsNullOrWhiteSpace(group?.DefaultRestGroupId))
            {
                return null;
            }

            return await _db.Queryable<LqAttendanceRestGroupEntity>()
                .Where(x => x.Id == group.DefaultRestGroupId && SqlFunc.IsNull(x.DeleteMark, 0) == 0)
                .FirstAsync();
        }

        private static List<SettleAction> BuildActions(
            List<AttendanceRestMonthSettlementHelper.RestSegment> segments,
            decimal desiredConverted,
            decimal alreadyConverted,
            int year,
            int month,
            decimal paidWork,
            int cycle,
            decimal monthlyCap,
            decimal entitled,
            decimal submittedTotal)
        {
            var actions = new List<SettleAction>();
            var currentConverted = alreadyConverted;
            if (currentConverted > desiredConverted)
            {
                var remain = currentConverted - desiredConverted;
                foreach (var seg in AttendanceRestMonthSettlementHelper.OrderForRevert(segments.Where(x => x.Converted)))
                {
                    if (remain <= 0m)
                    {
                        break;
                    }

                    var take = Math.Min(seg.Days, remain);
                    actions.Add(CreateAction(seg, take, true, year, month, paidWork, cycle, monthlyCap, entitled, submittedTotal));
                    remain -= take;
                }
            }
            else if (currentConverted < desiredConverted)
            {
                var remain = desiredConverted - currentConverted;
                foreach (var seg in AttendanceRestMonthSettlementHelper.OrderForConvert(segments.Where(x => !x.Converted)))
                {
                    if (remain <= 0m)
                    {
                        break;
                    }

                    var take = Math.Min(seg.Days, remain);
                    actions.Add(CreateAction(seg, take, false, year, month, paidWork, cycle, monthlyCap, entitled, submittedTotal));
                    remain -= take;
                }
            }

            return actions;
        }

        private static SettleAction CreateAction(
            AttendanceRestMonthSettlementHelper.RestSegment seg,
            decimal days,
            bool revert,
            int year,
            int month,
            decimal paidWork,
            int cycle,
            decimal monthlyCap,
            decimal entitled,
            decimal submittedTotal)
        {
            var half = days < seg.Days && seg.HalfPeriod == "full" ? "pm" : seg.HalfPeriod;
            var excess = Math.Max(0m, submittedTotal - entitled);
            return new SettleAction
            {
                Revert = revert,
                Date = seg.Date,
                HalfPeriod = half,
                Days = days,
                LeaveApplyId = seg.LeaveApplyId,
                BillNo = seg.BillNo,
                Record = seg.Record,
                Workflow = seg.Workflow,
                Reason = AttendanceRestMonthSettlementHelper.BuildReason(
                    year,
                    month,
                    paidWork,
                    cycle,
                    monthlyCap,
                    entitled,
                    submittedTotal,
                    excess,
                    seg.Date,
                    half,
                    days,
                    revert
                        ? AttendanceRestMonthSettlementHelper.SettlementReverted
                        : AttendanceRestMonthSettlementHelper.SettlementToPersonal)
            };
        }

        private async Task ConvertSegmentAsync(SettleAction action, string batchId)
        {
            if (action.Record == null)
            {
                return;
            }

            WformLeaveApplyEntityLite leave = null;
            if (!string.IsNullOrWhiteSpace(action.LeaveApplyId))
            {
                leave = await _db.Queryable<WformLeaveApplyEntityLite>()
                    .Where(x => x.Id == action.LeaveApplyId)
                    .FirstAsync();
            }

            var snapshot = leave == null
                ? null
                : new WformLeaveApplyEntityLite
                {
                    Id = leave.Id,
                    BillNo = leave.BillNo,
                    FlowTitle = leave.FlowTitle,
                    LeaveType = leave.LeaveType,
                    LeaveReason = AttendanceRestMonthSettlementHelper.StripSettlementLines(leave.LeaveReason),
                    LeaveStartTime = leave.LeaveStartTime,
                    LeaveEndTime = leave.LeaveEndTime,
                    LeaveDayCount = leave.LeaveDayCount,
                    LeaveHour = leave.LeaveHour,
                    Description = ParseDays(leave.LeaveDayCount) >= 1m
                        ? AttendanceHalfDayLeaveHelper.StripDayHalfPeriodFromDescription(leave.Description)
                        : leave.Description
                };
            if (snapshot != null && string.IsNullOrWhiteSpace(snapshot.Description))
            {
                snapshot.Description = null;
            }

            var split = false;
            WformLeaveApplyEntityLite newLeave = null;
            if (leave != null)
            {
                var remainDays = ParseDays(leave.LeaveDayCount) - action.Days;
                if (remainDays > 0m)
                {
                    split = true;
                    newLeave = await SplitToPersonalAsync(leave, action, batchId);
                    await ShrinkOriginalLeaveAsync(leave, action, remainDays);
                }
                else
                {
                    await ChangeWholeLeaveToPersonalAsync(leave, action);
                }
            }

            await UpdateAttendanceForConvertAsync(action, batchId, snapshot ?? leave, newLeave, split);
        }

        private async Task RevertSegmentAsync(SettleAction action, string batchId)
        {
            if (action.Record == null || action.Workflow == null)
            {
                return;
            }

            var wf = action.Workflow;
            var originalId = !string.IsNullOrWhiteSpace(wf.originalLeaveId) ? wf.originalLeaveId : action.LeaveApplyId;
            var original = string.IsNullOrWhiteSpace(originalId)
                ? null
                : await _db.Queryable<WformLeaveApplyEntityLite>().Where(x => x.Id == originalId).FirstAsync();
            if (original != null && !string.IsNullOrWhiteSpace(wf.originalLeaveStart))
            {
                original.LeaveType = AttendanceRestMonthSettlementHelper.RestLeaveType;
                original.LeaveStartTime = ParseDateTime(wf.originalLeaveStart) ?? original.LeaveStartTime;
                original.LeaveEndTime = ParseDateTime(wf.originalLeaveEnd) ?? original.LeaveEndTime;
                original.LeaveDayCount = string.IsNullOrWhiteSpace(wf.originalLeaveDayCount)
                    ? original.LeaveDayCount
                    : wf.originalLeaveDayCount;
                original.Description = string.IsNullOrWhiteSpace(wf.originalDescription)
                    ? null
                    : wf.originalDescription;
                original.LeaveReason = string.IsNullOrWhiteSpace(wf.originalLeaveReason)
                    ? AttendanceRestMonthSettlementHelper.StripSettlementLines(original.LeaveReason)
                    : wf.originalLeaveReason;
                original.LeaveHour = string.IsNullOrWhiteSpace(wf.originalLeaveHour)
                    ? original.LeaveHour
                    : wf.originalLeaveHour;
                if (!string.IsNullOrWhiteSpace(wf.originalFlowTitle))
                {
                    original.FlowTitle = wf.originalFlowTitle;
                }

                await _db.Updateable(original).ExecuteCommandAsync();
                await UpdateFlowTitleAsync(original.Id, original.FlowTitle);
            }
            else if (original != null)
            {
                original.LeaveType = AttendanceRestMonthSettlementHelper.RestLeaveType;
                original.FlowTitle = AttendanceRestMonthSettlementHelper.ReplaceTitleLeaveType(
                    original.FlowTitle,
                    AttendanceRestMonthSettlementHelper.PersonalLeaveType,
                    AttendanceRestMonthSettlementHelper.RestLeaveType);
                original.LeaveReason = string.IsNullOrWhiteSpace(wf.originalLeaveReason)
                    ? AttendanceRestMonthSettlementHelper.StripSettlementLines(original.LeaveReason)
                    : wf.originalLeaveReason;
                await _db.Updateable(original).ExecuteCommandAsync();
                await UpdateFlowTitleAsync(original.Id, original.FlowTitle);
            }

            if (!string.IsNullOrWhiteSpace(wf.splitNewLeaveId) && wf.splitNewLeaveId != originalId)
            {
                await _db.Deleteable<WformLeaveApplyEntityLite>()
                    .Where(x => x.Id == wf.splitNewLeaveId)
                    .ExecuteCommandAsync();
                await _db.Deleteable<FlowTaskLiteEntity>()
                    .Where(x => x.Id == wf.splitNewLeaveId)
                    .ExecuteCommandAsync();
            }

            await UpdateAttendanceForRevertAsync(action, batchId, original);
        }

        private async Task ChangeWholeLeaveToPersonalAsync(WformLeaveApplyEntityLite leave, SettleAction action)
        {
            leave.LeaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType;
            leave.FlowTitle = AttendanceRestMonthSettlementHelper.ReplaceTitleLeaveType(
                leave.FlowTitle,
                AttendanceRestMonthSettlementHelper.RestLeaveType,
                AttendanceRestMonthSettlementHelper.PersonalLeaveType);
            leave.LeaveReason = AttendanceRestMonthSettlementHelper.AppendReason(leave.LeaveReason, action.Reason);
            await _db.Updateable(leave).ExecuteCommandAsync();
            await UpdateFlowTitleAsync(leave.Id, leave.FlowTitle);
        }

        private async Task ShrinkOriginalLeaveAsync(WformLeaveApplyEntityLite leave, SettleAction action, decimal remainDays)
        {
            if (leave.LeaveEndTime.HasValue && action.Date == leave.LeaveEndTime.Value.Date)
            {
                if (action.HalfPeriod == "pm" && action.Days < 1m)
                {
                    leave.LeaveEndTime = action.Date.AddHours(12);
                    leave.Description = AttendanceHalfDayLeaveHelper.EmbedDayHalfPeriodInDescription(
                        leave.Description,
                        "am");
                }
                else
                {
                    leave.LeaveEndTime = action.Date.AddDays(-1).AddHours(23).AddMinutes(59);
                    if (remainDays == decimal.Truncate(remainDays))
                    {
                        leave.Description = AttendanceHalfDayLeaveHelper.StripDayHalfPeriodFromDescription(leave.Description);
                    }
                }
            }

            var originalDays = ParseDays(leave.LeaveDayCount);
            leave.LeaveDayCount = AttendanceRestMonthSettlementHelper.FormatDays(remainDays);
            leave.LeaveHour = AttendanceRestMonthSettlementHelper.ScaleLeaveHour(
                leave.LeaveHour,
                originalDays,
                remainDays);
            await _db.Updateable(leave).ExecuteCommandAsync();
        }

        private async Task<WformLeaveApplyEntityLite> SplitToPersonalAsync(
            WformLeaveApplyEntityLite original,
            SettleAction action,
            string batchId)
        {
            var newId = YitIdHelper.NextId().ToString();
            var billNo = BuildSplitBillNo(original.BillNo);
            var start = action.HalfPeriod == "pm"
                ? action.Date.AddHours(13)
                : action.Date;
            var end = action.HalfPeriod == "am"
                ? action.Date.AddHours(12)
                : action.Date.AddHours(23).AddMinutes(59);
            var description = AttendanceHalfDayLeaveHelper.EmbedDayHalfPeriodInDescription(
                $"月末应休结算拆单,原单 {original.BillNo},批次 {batchId}",
                action.Days < 1m ? action.HalfPeriod : null);
            var entity = new WformLeaveApplyEntityLite
            {
                Id = newId,
                FlowId = original.FlowId,
                FlowTitle = AttendanceRestMonthSettlementHelper.ReplaceTitleLeaveType(
                    original.FlowTitle,
                    AttendanceRestMonthSettlementHelper.RestLeaveType,
                    AttendanceRestMonthSettlementHelper.PersonalLeaveType) + "(月末应休结算)",
                FlowUrgent = original.FlowUrgent,
                BillNo = billNo,
                ApplyUser = original.ApplyUser,
                ApplyDate = DateTime.Now,
                ApplyDept = original.ApplyDept,
                ApplyDeptId = original.ApplyDeptId,
                ApplyPost = original.ApplyPost,
                LeaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType,
                LeaveReason = action.Reason,
                LeaveStartTime = start,
                LeaveEndTime = end,
                LeaveDayCount = AttendanceRestMonthSettlementHelper.FormatDays(action.Days),
                LeaveHour = AttendanceRestMonthSettlementHelper.ScaleLeaveHour(
                    original.LeaveHour,
                    ParseDays(original.LeaveDayCount),
                    action.Days),
                FileJson = original.FileJson,
                Description = description
            };
            await _db.Insertable(entity).ExecuteCommandAsync();

            var srcTask = await _db.Queryable<FlowTaskLiteEntity>()
                .Where(x => x.Id == original.Id && x.DeleteMark == null)
                .FirstAsync();
            if (srcTask != null)
            {
                await _db.Insertable(new FlowTaskLiteEntity
                {
                    Id = newId,
                    ProcessId = newId,
                    EnCode = billNo,
                    FullName = entity.FlowTitle,
                    FlowId = srcTask.FlowId,
                    FlowCode = srcTask.FlowCode,
                    FlowName = srcTask.FlowName,
                    ThisStepId = srcTask.ThisStepId,
                    Status = FlowTaskStatusAdopt,
                    EnabledMark = 1,
                    CreatorTime = DateTime.Now,
                    CreatorUserId = srcTask.CreatorUserId,
                    DeleteMark = null
                }).ExecuteCommandAsync();
            }

            return entity;
        }

        private async Task UpdateAttendanceForConvertAsync(
            SettleAction action,
            string batchId,
            WformLeaveApplyEntityLite original,
            WformLeaveApplyEntityLite newLeave,
            bool split)
        {
            var record = action.Record;
            var workflows = AttendanceRestMonthSettlementHelper.ParseRelatedWorkflows(record.RelatedWorkflowsJson);
            if (workflows.Count == 0 && action.Workflow != null)
            {
                workflows.Add(action.Workflow);
            }

            var target = FindWorkflow(workflows, action);
            if (target == null)
            {
                target = new RelatedWorkflowItem
                {
                    type = AttendanceRestMonthSettlementHelper.WorkflowLeaveType,
                    id = original?.Id ?? action.LeaveApplyId,
                    billNo = original?.BillNo ?? action.BillNo,
                    leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType
                };
                workflows.Add(target);
            }

            var splitFullToHalf = split && action.Days < 1m
                && string.Equals(action.HalfPeriod, "pm", StringComparison.Ordinal)
                && (target.leaveFraction == null || target.leaveFraction >= 1m);
            if (splitFullToHalf)
            {
                var converted = BuildConvertedWorkflow(action, batchId, original, newLeave, split, "pm", 0.5m);
                converted.flowId = target.flowId;
                converted.flowCode = target.flowCode;
                converted.formType = target.formType;
                converted.flowStatus = target.flowStatus;
                converted.taskNodeId = target.taskNodeId;
                converted.originalLeaveFraction = target.leaveFraction ?? 1m;
                converted.originalHalfPeriod = target.halfPeriod;
                converted.originalRemark = AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark);
                target.leaveFraction = 0.5m;
                target.halfPeriod = "am";
                target.leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType;
                target.restSettlement = null;
                target.restSettlementBatchId = null;
                target.restSettlementReason = null;
                workflows.Add(converted);
            }
            else
            {
                FillSettlementSnapshot(target, original, action, batchId, newLeave, split);
                ApplyConvertedWorkflowFields(target, action, original, newLeave);
            }

            record.RelatedWorkflowsJson = JsonConvert.SerializeObject(workflows);
            var remark = AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark);
            if (!splitFullToHalf)
            {
                remark = AttendanceRestMonthSettlementHelper.ReplaceLeaveTypeInRemark(
                    remark,
                    AttendanceRestMonthSettlementHelper.RestLeaveType,
                    AttendanceRestMonthSettlementHelper.PersonalLeaveType);
            }

            record.Remark = AttendanceRestMonthSettlementHelper.AppendReason(
                remark,
                AttendanceRestMonthSettlementHelper.ShortAttendanceRemark(action.Reason));
            if (record.Remark != null && record.Remark.Length > 500)
            {
                record.Remark = record.Remark.Substring(0, 500);
            }

            if (record.Status == (int)AttendanceRecordStatusEnum.请假
                || record.Status == (int)AttendanceRecordStatusEnum.休息)
            {
                record.Status = (int)AttendanceRecordStatusEnum.请假;
            }

            record.UpdateTime = DateTime.Now;
            record.UpdateUserId = _userManager.UserId ?? "system";
            await _db.Updateable(record)
                .UpdateColumns(x => new { x.RelatedWorkflowsJson, x.Remark, x.Status, x.UpdateTime, x.UpdateUserId })
                .ExecuteCommandAsync();
        }

        private async Task UpdateAttendanceForRevertAsync(
            SettleAction action,
            string batchId,
            WformLeaveApplyEntityLite original)
        {
            var record = action.Record;
            var workflows = AttendanceRestMonthSettlementHelper.ParseRelatedWorkflows(record.RelatedWorkflowsJson);
            var target = FindWorkflow(workflows, action);
            var originalRemark = target?.originalRemark
                ?? action.Workflow?.originalRemark
                ?? AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark);
            if (target != null)
            {
                MergeRevertedWorkflow(workflows, target, original, action, batchId);
            }

            record.RelatedWorkflowsJson = JsonConvert.SerializeObject(workflows);
            record.Remark = string.IsNullOrWhiteSpace(originalRemark)
                ? AttendanceRestMonthSettlementHelper.ReplaceLeaveTypeInRemark(
                    AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark),
                    AttendanceRestMonthSettlementHelper.PersonalLeaveType,
                    AttendanceRestMonthSettlementHelper.RestLeaveType)
                : originalRemark;
            record.UpdateTime = DateTime.Now;
            record.UpdateUserId = _userManager.UserId ?? "system";
            await _db.Updateable(record)
                .UpdateColumns(x => new { x.RelatedWorkflowsJson, x.Remark, x.UpdateTime, x.UpdateUserId })
                .ExecuteCommandAsync();
        }

        private static void MergeRevertedWorkflow(
            List<RelatedWorkflowItem> workflows,
            RelatedWorkflowItem target,
            WformLeaveApplyEntityLite original,
            SettleAction action,
            string batchId)
        {
            var originalId = original?.Id ?? target.originalLeaveId ?? action.LeaveApplyId;
            var originalBillNo = original?.BillNo ?? target.originalBillNo ?? action.BillNo;
            var sibling = workflows.FirstOrDefault(x =>
                x != null
                && x != target
                && string.Equals(x.type, AttendanceRestMonthSettlementHelper.WorkflowLeaveType, StringComparison.Ordinal)
                && (x.id == originalId || x.billNo == originalBillNo)
                && !string.Equals(x.restSettlement, AttendanceRestMonthSettlementHelper.SettlementToPersonal, StringComparison.Ordinal));

            if (sibling != null)
            {
                sibling.leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType;
                sibling.id = originalId;
                sibling.billNo = originalBillNo;
                sibling.leaveFraction = target.originalLeaveFraction ?? 1m;
                sibling.halfPeriod = string.IsNullOrWhiteSpace(target.originalHalfPeriod)
                    ? null
                    : target.originalHalfPeriod;
                sibling.restSettlement = AttendanceRestMonthSettlementHelper.SettlementReverted;
                sibling.restSettlementBatchId = batchId;
                sibling.restSettlementReason = action.Reason;
                sibling.splitNewLeaveId = null;
                sibling.splitNewBillNo = null;
                sibling.remark = target.originalRemark ?? sibling.remark;
                workflows.Remove(target);
                return;
            }

            target.leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType;
            target.id = originalId;
            target.billNo = originalBillNo;
            target.leaveFraction = target.originalLeaveFraction ?? target.leaveFraction;
            target.halfPeriod = string.IsNullOrWhiteSpace(target.originalHalfPeriod)
                ? (string.Equals(action.HalfPeriod, "full", StringComparison.Ordinal) ? null : target.halfPeriod)
                : target.originalHalfPeriod;
            target.restSettlement = AttendanceRestMonthSettlementHelper.SettlementReverted;
            target.restSettlementBatchId = batchId;
            target.restSettlementReason = action.Reason;
            target.splitNewLeaveId = null;
            target.splitNewBillNo = null;
            target.remark = target.originalRemark ?? target.remark;
        }

        private static RelatedWorkflowItem FindWorkflow(List<RelatedWorkflowItem> workflows, SettleAction action)
        {
            if (action.Workflow != null)
            {
                var byRef = workflows.FirstOrDefault(x => ReferenceEquals(x, action.Workflow));
                if (byRef != null)
                {
                    return byRef;
                }
            }

            return workflows.FirstOrDefault(x =>
                (!string.IsNullOrWhiteSpace(action.LeaveApplyId) && x.id == action.LeaveApplyId)
                || (!string.IsNullOrWhiteSpace(action.BillNo) && x.billNo == action.BillNo));
        }

        private static void FillSettlementSnapshot(
            RelatedWorkflowItem target,
            WformLeaveApplyEntityLite original,
            SettleAction action,
            string batchId,
            WformLeaveApplyEntityLite newLeave,
            bool split)
        {
            target.restSettlement = AttendanceRestMonthSettlementHelper.SettlementToPersonal;
            target.restSettlementBatchId = batchId;
            target.restSettlementReason = action.Reason;
            target.originalLeaveType = AttendanceRestMonthSettlementHelper.RestLeaveType;
            target.originalLeaveId = original?.Id ?? action.LeaveApplyId;
            target.originalBillNo = original?.BillNo ?? action.BillNo;
            target.originalLeaveStart = original?.LeaveStartTime?.ToString("yyyy-MM-dd HH:mm:ss");
            target.originalLeaveEnd = original?.LeaveEndTime?.ToString("yyyy-MM-dd HH:mm:ss");
            target.originalLeaveDayCount = original?.LeaveDayCount;
            target.originalDescription = original?.Description;
            target.originalLeaveReason = original?.LeaveReason;
            target.originalFlowTitle = original?.FlowTitle;
            target.originalLeaveHour = original?.LeaveHour;
            target.originalLeaveFraction = action.Workflow?.leaveFraction ?? target.leaveFraction;
            target.originalHalfPeriod = action.Workflow?.halfPeriod ?? target.halfPeriod;
            target.originalRemark = AttendanceRestMonthSettlementHelper.StripSettlementLines(action.Record?.Remark);
            if (split && newLeave != null)
            {
                target.splitNewLeaveId = newLeave.Id;
                target.splitNewBillNo = newLeave.BillNo;
            }
        }

        private static void ApplyConvertedWorkflowFields(
            RelatedWorkflowItem target,
            SettleAction action,
            WformLeaveApplyEntityLite original,
            WformLeaveApplyEntityLite newLeave)
        {
            target.leaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType;
            target.leaveFraction = action.Days;
            target.halfPeriod = action.HalfPeriod == "full" ? null : action.HalfPeriod;
            target.remark = action.Reason;
            if (newLeave != null)
            {
                target.id = newLeave.Id;
                target.billNo = newLeave.BillNo;
            }
            else if (original != null)
            {
                target.id = original.Id;
                target.billNo = original.BillNo;
            }
        }

        private static RelatedWorkflowItem BuildConvertedWorkflow(
            SettleAction action,
            string batchId,
            WformLeaveApplyEntityLite original,
            WformLeaveApplyEntityLite newLeave,
            bool split,
            string halfPeriod,
            decimal days)
        {
            var item = new RelatedWorkflowItem
            {
                type = AttendanceRestMonthSettlementHelper.WorkflowLeaveType,
                leaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType,
                leaveFraction = days,
                halfPeriod = halfPeriod,
                remark = action.Reason,
                time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                id = newLeave?.Id ?? original?.Id,
                billNo = newLeave?.BillNo ?? original?.BillNo
            };
            FillSettlementSnapshot(item, original, action, batchId, newLeave, split);
            return item;
        }

        private async Task UpdateFlowTitleAsync(string taskId, string title)
        {
            if (string.IsNullOrWhiteSpace(taskId) || string.IsNullOrWhiteSpace(title))
            {
                return;
            }

            await _db.Updateable<FlowTaskLiteEntity>()
                .SetColumns(x => x.FullName == title)
                .Where(x => x.Id == taskId)
                .ExecuteCommandAsync();
        }

        private async Task WriteUserLogAsync(
            UserEntity user,
            AttendanceRestMonthSettlementInput input,
            string batchId,
            string actionCode,
            decimal paidWork,
            int cycle,
            decimal monthlyCap,
            decimal entitled,
            decimal submitted,
            List<SettleAction> actions)
        {
            var perUserSummary = input.forceRevertConverted
                ? $"{user.RealName} {input.year}年{input.month}月回归原始打卡数据,改回 {actions.Count(x => x.Revert)} 段"
                : $"{user.RealName} {input.year}年{input.month}月应休结算,带薪上班 {AttendanceRestMonthSettlementHelper.FormatDays(paidWork)} 天,应得 {AttendanceRestMonthSettlementHelper.FormatDays(entitled)} 天";
            await BusinessOperationLogHelper.SafeWriteAsync(
                _businessOperationLogService,
                _logger,
                BizModule,
                actionCode,
                "WFORM_LEAVEAPPLY",
                user.Id,
                perUserSummary,
                JsonConvert.SerializeObject(new
                {
                    batchId,
                    userId = user.Id,
                    userName = user.RealName,
                    input.year,
                    input.month,
                    input.forceRevertConverted,
                    paidWork,
                    cycle,
                    monthlyCap,
                    entitled,
                    submitted,
                    actions = actions.Select(x => new
                    {
                        x.Revert,
                        date = x.Date.ToString("yyyy-MM-dd"),
                        x.HalfPeriod,
                        x.Days,
                        x.LeaveApplyId,
                        x.BillNo,
                        x.Reason
                    })
                }));
        }

        private static string BuildSplitBillNo(string originalBillNo)
        {
            var prefix = string.IsNullOrWhiteSpace(originalBillNo) ? "REST" : originalBillNo.Trim();
            return $"{prefix}-JS{DateTime.Now:MMddHHmmss}";
        }

        private static decimal ParseDays(string value)
        {
            if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var days)
                || decimal.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out days))
            {
                return days;
            }

            return 0m;
        }

        private static DateTime? ParseDateTime(string value)
        {
            if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt)
                || DateTime.TryParse(value, out dt))
            {
                return dt;
            }

            return null;
        }

        private sealed class SettleAction
        {
            public bool Revert { get; set; }

            public DateTime Date { get; set; }

            public string HalfPeriod { get; set; }

            public decimal Days { get; set; }

            public string LeaveApplyId { get; set; }

            public string BillNo { get; set; }

            public string Reason { get; set; }

            public LqAttendanceRecordEntity Record { get; set; }

            public RelatedWorkflowItem Workflow { get; set; }
        }
    }
}