using OASystem.API.OAMethodLib.QiYeWeChatAPI;
using OASystem.Domain.Entities.PersonnelModule;
using OASystem.Domain.ViewModels.PersonnelModule;
using OASystem.Domain.ViewModels.QiYeWeChat;

namespace OASystem.API.OAMethodLib
{
    /// <summary>
    /// 工资计算
    /// </summary>
    public static class PayrollComputation
    {
        private static Result _result = new Result();
        private static readonly IQiYeWeChatApiService _qiYeWeChatApiService = AutofacIocManager.Instance.GetService<IQiYeWeChatApiService>();
        private static readonly UsersRepository _usersRep = AutofacIocManager.Instance.GetService<UsersRepository>();
        private static readonly IMapper _mapper = AutofacIocManager.Instance.GetService<IMapper>();
        private static readonly decimal _chengDuMinimumWage = 2100.00M * 0.80M; //员工在病假医疗期限内的病假工资按照成都市最低工资标准的 80%发放 

        /// <summary>
        /// 计算工资
        /// </summary>
        /// <param name="pm_WageSheetDattaSources"></param>
        /// <param name="userNames"></param>
        /// <param name="userId"></param>
        /// <param name="thisYearMonth"></param>
        /// <param name="startDt"></param>
        /// <param name="endDt"></param>
        /// <returns></returns>
        public static async Task<Result> SalaryCalculatorAsync(
            List<Pm_WageSheet> pm_WageSheetDattaSources, List<UserNameView> userNames, int userId, string thisYearMonth, DateTime startDt, DateTime endDt)
        {
            if (pm_WageSheetDattaSources.Count <= 0)
            {
                _result.Msg = "计算工资传入数据为空!";
                return _result;
            }

            //计算时间段内工作日
            int work_days = await GetWorkDays(thisYearMonth);
            if (work_days <= 0)
            {
                _result.Msg = $"{thisYearMonth} 工作日未设置,请前往《工作日管理页面》设置!";
                return _result;
            }

            UserIdListView userIdListView = await _qiYeWeChatApiService.GetUserIdListAsync();
            if (userIdListView.errcode != 0)
            {
                _result.Msg = $"【企业微信】【打卡】【获取员工ID】【Msg】{userIdListView.errmsg}";
                return _result;
            }

            //Task<QYWX_UserInfosView> GetUserInfosAsync()
            //QYWX_UserInfosView usersView = await _qiYeWeChatApiService.GetUserInfosAsync();
            //if (usersView.errcode != 0)
            //{
            //    _result.Msg = $"【企业微信】【打卡】【获取员工基础信息】【Msg】{userIdListView.errmsg}";
            //    return _result;
            //}


            List<string> qyWhchatIdList = new List<string>();
            qyWhchatIdList = userIdListView.dept_user.Select(it => it.userid ?? "").ToList();
            CheckInDayDataView checkInDayDataView = await _qiYeWeChatApiService.GetCheckInDayDataAsync(qyWhchatIdList, startDt, endDt);
            if (checkInDayDataView.errcode != 0)
            {
                _result.Msg = $"【企业微信】【打卡】【获取时间段内所有日打卡】【Msg】{checkInDayDataView.errmsg}";
                return _result;
            }

            //获取所有打卡记录 外出
            CheckInDataView checkInDataView = new CheckInDataView();
            checkInDataView = await _qiYeWeChatApiService.GetCheckinDataAsync(qyWhchatIdList, 3, startDt, endDt);
            if (checkInDataView.errcode != 0)
            {
                _result.Msg = $"【企业微信】【打卡】【获取时间段内所有日打卡记录】【Msg】{checkInDataView.errmsg}";
                return _result;
            }

            //查询工作日
            List<Sys_Calendar> sys_Calendars = new List<Sys_Calendar>();
            string sys_sql = string.Format("Select * From Sys_Calendar Where Isdel = 0 And Dt between '{0}' And '{1}'",
                startDt.ToString("yyyy-MM-dd"), endDt.ToString("yyyy-MM-dd"));
            sys_Calendars = await _usersRep._sqlSugar.SqlQueryable<Sys_Calendar>(sys_sql).ToListAsync();

            //筛选出工作日日报
            List<Root> workday_userRoots = checkInDayDataView.datas.Where(it => it.base_info.day_type == 0 && it.base_info.record_type == 1).ToList();

            //工作日日报
            workday_userRoots = workday_userRoots.OrderBy(it => it.base_info.date).ToList();


            #region 特殊日期-不用打卡日期信息

            //获取企业打卡规则
            CorpCheckInRuleView corpCheckInRole = await _qiYeWeChatApiService.GetCheckIn_CorpCheckInOptionAsync();
            if (corpCheckInRole.errcode != 0)
            {
                _result.Msg = $"【企业微信】【打卡】【获取企业打卡规则】【Msg】{corpCheckInRole.errmsg}";
                return _result;
            }

            int spe_offdays = 0;

            GroupItem group = corpCheckInRole.group.Where(it => it.groupid == 4).FirstOrDefault();
            if (group != null)
            {
                foreach (var item in group.spe_offdays)
                {
                    if (item.begtime_dt >= startDt && item.endtime_dt <= endDt)
                    {
                        if (item.endtime_dt > startDt)
                        {
                            TimeSpan ts = item.endtime_dt - item.begtime_dt;
                            spe_offdays = (ts.Days + 1);
                        }
                    }
                }
            }
            #endregion



            //获取 请假类型 Sp_Detail.template_id
            string leave_template_id = "C4NzTJCh1onCUK915rRkvy7Fh5Vqz4YbiEV9jrBY1";
            List<VacationLeaveTypeView> vacationLeaveTypes = await GetVacationLeaveTypes(leave_template_id);
            if (vacationLeaveTypes.Count <= 0)
            {
                _result.Msg = $"【企业微信】【审批】【获取审批类型】【Msg】{startDt} - {endDt}请假 类型数据 获取失败!";
                return _result;
            }

            string _name = "";
            try
            {
                #region 手动配置企业员工userid,通过userid 去匹配打卡数据
                //Dictionary<string, string> wx_useridDic = new Dictionary<string, string>();
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("罗诗怡", "lsyyyy");
                //wx_useridDic.Add("赖红燕", "LaiHongYan");
                //wx_useridDic.Add("刘一茹", "liuyiru");
                //wx_useridDic.Add("李雯琪", "LiWenQi");
                //wx_useridDic.Add("罗聪惠", "LuoCongHui");
                //wx_useridDic.Add("肖俊杰", "20230410");
                //wx_useridDic.Add("朱成梅", "amy.zhu@pan-american-intl.com");
                //wx_useridDic.Add("伏虹瑾", "FuHongJin");
                //wx_useridDic.Add("曾艳", "judy.zeng@pan-american-intl.com");
                //wx_useridDic.Add("舒庆", "cilina.shu@pan-american-intl.com");
                //wx_useridDic.Add("高媛媛", "GaoYuanYuan");
                //wx_useridDic.Add("龙畑恬", "longtiantian");
                //wx_useridDic.Add("叶琪琪", "YeQiQi");
                //wx_useridDic.Add("王鸽", "ellisa.wang@pan-american-intl.com");
                //wx_useridDic.Add("赵雅琪", "ZhaoYaQi");
                //wx_useridDic.Add("陈思帆", "ChenSiFan");
                //wx_useridDic.Add("廖文雅", "LiaoWenYa");
                //wx_useridDic.Add("李敏", "annie.li@pan-american-intl.com");
                //wx_useridDic.Add("李明华", "LiMingHua");
                //wx_useridDic.Add("李文婷", "LiWenTing");
                //wx_useridDic.Add("仇久龙", "rf");
                //wx_useridDic.Add("宋夏雨", "songxiayu");
                //wx_useridDic.Add("王思雨", "ysw");
                //wx_useridDic.Add("汪燕平", "yime");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");
                //wx_useridDic.Add("张海麟", "fred.chang@pan-american-intl.com");


                #endregion

                foreach (var pm_wsInfo in pm_WageSheetDattaSources)
                {
                    _name = userNames.Find(it => it.Id == pm_wsInfo.UserId)?.CnName ?? "Unknown";

                    //补贴 金额
                    decimal meal_subsidy = 0.00M;  // 午餐(午餐10元/天)  补贴 * 计算方式:单日上午请假时长(小时)大于或者等于三小时 没有餐补

                    //事假 病假 总金额
                    decimal personalLeaveTotal = 0.00M,  // 事假 日薪 *计算方式:日平均工资 = 月工资/当月应出勤天数。
                            sickLeaveTotal = 0.00M;      // 病假 日薪 *计算方式:日平均工资 = 成都市最低工资标准的80%/当月应出勤天数。 短期病假=当月15天内  

                    //扣款金额
                    decimal beLate_deduction = 0.00M,         // 迟到 扣款金额 *计算方式:
                                                              // 一个自然月内,不足 10 分钟的迟到/早退,不超过 2 次的部分,不做处罚;3 次及以上,按50元 / 次处罚;
                                                              // 超过 10 分钟(含 10 分钟),不足 60 分钟的迟到/早退,按 50 元/次处罚;
                                                              // 超过 60 分钟(含 60 分钟),不足 3 小时的迟到/早退,且无请假者,按旷工半日处理;超过3 小时的迟到 / 早退,且无请假者,按旷工一日处理。
                            early_deduction = 0.00M,          // 早退 扣款金额
                            absenteeism_deduction = 0.00M,    // 旷工 扣款金额 *计算方式:旷工扣发当日工资
                            unprinted_deduction = 0.00M,      // 未打卡 扣款金额 *计算方式:
                                                              // 试用期员工每月有 2 次 补卡机会,超过 2 次不足 5 次的部分,按 10 元 / 次处罚,5 次及以上的漏卡,按 50 元 / 次处罚;
                                                              // 正式员工每月 3 次以内的补卡,按 10 元 / 次处罚,3 次及以上的漏卡,按 50 元 / 次处罚。
                            sickLeave_deduction = 0.00M,      // 病假
                            other_deduction = 0.00M;          // 其他 扣款金额

                    decimal meal_deduction = 0.00M;           // 餐补 扣款金额
                    //decimal reissuecard_deduction = 0.00M;    // 补卡 扣款金额

                    #region 计算日工资 正常日薪 事假日薪 病假日薪

                    //月 - 应发工资
                    decimal amountPayable = pm_wsInfo.Basic + pm_wsInfo.Floats + pm_wsInfo.PostAllowance + pm_wsInfo.InformationSecurityFee +
                                            pm_wsInfo.OtherSubsidies;

                    // 日薪 = *计算方式:日平均工资 = 月工资/当月应出勤天数。
                    decimal dailyWage = amountPayable / work_days;

                    // 病假日薪 *计算方式:日平均工资 = 成都市最低工资标准的80%/当月应出勤天数。 短期病假=当月15天内 
                    decimal sickLeave_dailywage = _chengDuMinimumWage / work_days;

                    //病假 一天扣款  
                    sickLeave_deduction = dailyWage - sickLeave_dailywage;

                    List<Ex_Items> ex_Items = new List<Ex_Items>();//假勤 And 打卡备注集合
                    Ex_Items ex_Items_dk = new Ex_Items() { Type = "打卡" };    //打卡
                    Ex_Items ex_Items_jq = new Ex_Items() { Type = "假勤" };   //假勤
                    Ex_Items ex_Items_cc = new Ex_Items() { Type = "出差" };   //出差
                    #endregion


                    List<Root> userRoots = new List<Root>();

                    //string wx_userid = "";


                    if (_name == "蔡雯")
                    {
                        userRoots = workday_userRoots.Where(it => it.base_info.name == "蔡蔡" || it.base_info.name == "蔡雯").ToList(); //工作日日报 1-固定上下班;
                    }
                    else
                    {
                        userRoots = workday_userRoots.Where(it => it.base_info.name == _name || it.base_info.name.Contains(_name)).ToList(); //工作日日报 1-固定上下班;
                    }

                    //userRoots = userRoots.Distinct().ToList();
                    userRoots = userRoots.OrderBy(it => it.base_info.date).ToList();

                    int dk_work_days = userRoots.Count;   //应出勤天数 

                    if (dk_work_days > work_days)
                    {
                        dk_work_days = work_days;
                    }
                    meal_subsidy = dk_work_days * 10; //应发放餐补


                    if (!_name.Equals("张海麟"))
                    {
                        if (userRoots.Count <= 0)
                        {
                            _result.Msg = $"【{_name}】【企业微信】【打卡】【获取打卡数据】【Msg】{startDt} - {endDt} 打卡日数据 获取失败!";
                            continue;
                        }

                        string acctid = userRoots[0].base_info.acctid;
                        List<Ex_Item> ex_reissuecard_Items = new List<Ex_Item>(); //打卡类型 数据
                        List<Sp_items> acc_sp_items = new List<Sp_items>(); //审批数据

                        //int user_probationary_bk_num = 0;

                        decimal user_probationary_bk_decimal = pm_wsInfo.Floats; //绩效工资为0 则为试用员工

                        //处理外出打卡记录
                        List<CheckInDataInfo> checkInData1 = new List<CheckInDataInfo>();
                        checkInData1 = checkInDataView.checkindata;
                        List<CheckInDataInfo> checkInDatas = new List<CheckInDataInfo>();
                        checkInDatas = checkInData1.Where(it => it.userid == acctid).ToList();
                        //找出外出的打卡记录
                        List<CheckInDataInfo> checkInData2 = new List<CheckInDataInfo>();
                        checkInData2 = checkInDatas.Where(it => it.exception_type.Equals("未打卡")).ToList();

                        //外出打卡
                        List<CheckInDataInfo> checkInData_outPunch = new List<CheckInDataInfo>();
                        checkInData_outPunch = checkInDatas.Where(it => it.checkin_type.Equals("外出打卡")).ToList();

                        #region 迟到 早退 旷工

                        int user_cd_zt_num = 0; //早退/迟到 次数 10分钟内 2次以内不记处罚 三次及以上50一次

                        foreach (var root in userRoots)
                        {
                            List<Holiday_infos> holiday_Infos = root.holiday_infos; //当天假勤信息
                            List<Exception_infos> exception_infos = root.exception_infos; //当天校准状态信息
                            List<Sp_items> sp_Items = root.sp_items;//当天假勤统计信息
                            if (sp_Items.Count > 0)
                            {
                                sp_Items = sp_Items.Where(it => it.count > 0).ToList();
                                acc_sp_items.AddRange(sp_Items);
                            }

                            foreach (var exception_info in exception_infos)
                            {
                                decimal timelength = ConvertToDecimal((Convert.ToDecimal(exception_info.duration) / 3600.00M) * 60.00M);  //时长 分钟

                                if (timelength == 9) timelength = 7.50M;

                                int exception = exception_info.exception; //异常类型
                                decimal day_miner_unit = dailyWage / 15;  //以0.5小时为单位 

                                //1:一个自然月内,不足 10 分钟的迟到/早退,不超过 2 次的部分,不做处罚;3 次及以上,按50 元 / 次处罚;
                                //2:超过 10 分钟(含 10 分钟),不足 60 分钟的迟到 / 早退,按 50 元 / 次处罚;
                                //3:超过 60 分钟(含 60 分钟),不足 3 小时的迟到 / 早退,且无请假者,按旷工半日处理;超过 3 小时的迟到 / 早退,且无请假者,按旷工一日处理。

                                long date = root.base_info.date; //当日工作日期
                                long earliest_time = root.summary_info.earliest_time; //最早打卡时间
                                long lastest_time = root.summary_info.lastest_time; //最晚打卡时间
                                long this_date = date + earliest_time;
                                //DateTime thisDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks(this_date * 10000000);
                                DateTime thisDt = DateTime.MinValue.AddTicks(this_date * 10000000);

                                string thisDtStr = thisDt.ToString("yyyy-MM-dd");

                                Ex_Item beLate_belate_ex = new Ex_Item()
                                {
                                    SubTypeId = 4,
                                    SubType = "旷工",
                                    Duration = timelength,
                                    StartTimeDt = Convert.ToDateTime(root.base_info.dateDt.ToString("yyyy-MM-dd HH:mm:ss")),
                                    Unit = "分钟",
                                };

                                decimal day_deduction = 0.00M;
                                //1 - 迟到;2 - 早退;3 - 缺卡;4 - 旷工;5 - 地点异常;6 - 设备异常
                                if (exception == 1)   //迟到
                                {
                                    if (timelength < 10)
                                    {
                                        user_cd_zt_num++;
                                        beLate_belate_ex.SubTypeId = 1;
                                        beLate_belate_ex.SubType = "迟到";

                                        //string thisStartDt = (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + earliest_time) * 10000000)).ToString("yyyy-MM-dd HH:mm:ss");
                                        string thisStartDt = DateTime.MinValue.AddTicks((date + earliest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                        beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisStartDt);

                                        if (user_cd_zt_num >= 3)
                                        {
                                            day_deduction = 50.00M;
                                        }
                                        else
                                        {
                                            day_deduction = 0.00M;
                                        }
                                        beLate_deduction += day_deduction; //迟到扣款 总额
                                    }
                                    else if (timelength >= 10 && timelength < 60)
                                    {
                                        //string thisStartDt = (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + earliest_time) * 10000000)).ToString("yyyy-MM-dd HH:mm:ss");
                                        string thisStartDt = DateTime.MinValue.AddTicks((date + earliest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                        beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisStartDt);

                                        day_deduction = 50.00M;
                                        beLate_deduction += day_deduction; //迟到扣款 总额
                                        beLate_belate_ex.SubTypeId = 1;
                                        beLate_belate_ex.SubType = "迟到";
                                    }
                                    else if (timelength >= 60 && timelength <= 180)
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage / 2); //3小时 按半天计算
                                        meal_deduction += 10.00M;  //餐补扣款
                                        absenteeism_deduction += day_deduction; //矿工半日
                                        beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)缺卡/未打卡视为旷工半天";
                                    }
                                    else
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage);
                                        absenteeism_deduction += day_deduction; //矿工一日
                                        meal_deduction += 10.00M;
                                        beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)-下午(18:00) 缺卡/未打视为旷工一天(7.5小时)";
                                    }

                                    beLate_belate_ex.Deduction = day_deduction;
                                    ex_reissuecard_Items.Add(beLate_belate_ex);
                                }
                                else if (exception == 2)  //早退
                                {
                                    if (timelength < 10)
                                    {
                                        user_cd_zt_num++;
                                        beLate_belate_ex.SubTypeId = 2;
                                        beLate_belate_ex.SubType = "早退";
                                        //string thisEndDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                        string thisEndDt = DateTime.MinValue.AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                        beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisEndDt);

                                        if (user_cd_zt_num >= 3)
                                        {
                                            day_deduction = 50.00M;
                                        }
                                        else
                                        {
                                            day_deduction = 0.00M;
                                        }
                                        early_deduction += day_deduction;  //早退扣款 总计
                                    }
                                    else if (timelength >= 10 && timelength < 60)
                                    {
                                        day_deduction = 50.00M;
                                        early_deduction += day_deduction;  //早退扣款 总计
                                        beLate_belate_ex.SubTypeId = 2;
                                        beLate_belate_ex.SubType = "早退";
                                        //string thisEndDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                        string thisEndDt = DateTime.MinValue.AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                        beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisEndDt);
                                    }
                                    else if (timelength >= 60 && timelength <= 180)
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage / 2); //3小时 按半天计算
                                        meal_deduction += 10.00M;
                                        absenteeism_deduction += day_deduction; //矿工半日
                                    }
                                    else
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage);
                                        meal_deduction += 10.00M;
                                        absenteeism_deduction += day_deduction; //矿工一日
                                    }

                                    beLate_belate_ex.Deduction = day_deduction;
                                    ex_reissuecard_Items.Add(beLate_belate_ex);
                                }
                                else if (exception == 3) //缺卡
                                {
                                    if (root.exception_infos.Count == 2)
                                    {
                                        if (ex_reissuecard_Items.Where(it => it.StartTimeDt.ToString("yyyy-MM-dd").Equals(thisDtStr)).Count() > 0)
                                        {
                                            if (earliest_time == lastest_time)
                                            {
                                                DateTime thisDt1 = Convert.ToDateTime(thisDtStr + " 12:00");


                                                if (thisDt >= thisDt1)  //旷工 下午
                                                {
                                                    day_deduction = ConvertToDecimal(dailyWage / 2); //4.5小时 按半天计算
                                                    meal_deduction += 10.00M;

                                                    beLate_belate_ex.Duration = 270;
                                                    absenteeism_deduction += day_deduction; //矿工半日
                                                    beLate_belate_ex.Reason = thisDtStr + " 下午(18:00)缺卡/未打卡视为旷工半天";

                                                    beLate_belate_ex.Deduction = day_deduction;
                                                    ex_reissuecard_Items.Add(beLate_belate_ex);
                                                }
                                                else if (thisDt <= thisDt1) //旷工 上午
                                                {
                                                    day_deduction = ConvertToDecimal(dailyWage / 2); //3小时 按半天计算
                                                    meal_deduction += 10.00M;
                                                    absenteeism_deduction += day_deduction; //矿工半日
                                                    beLate_belate_ex.Duration = 180;
                                                    beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)缺卡/未打卡视为旷工半天";

                                                    beLate_belate_ex.Deduction = day_deduction;
                                                    ex_reissuecard_Items.Add(beLate_belate_ex);
                                                }
                                                else //矿工一日
                                                {

                                                    day_deduction = ConvertToDecimal(dailyWage);
                                                    meal_deduction += 10.00M;
                                                    absenteeism_deduction += day_deduction;
                                                    beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)-下午(18:00) 缺卡/未打视为旷工一天(7.5小时)";

                                                    beLate_belate_ex.Deduction = day_deduction;
                                                    ex_reissuecard_Items.Add(beLate_belate_ex);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            day_deduction = dailyWage;
                                            meal_deduction += 10.00M;
                                            absenteeism_deduction += day_deduction;
                                            beLate_belate_ex.Reason = "上午-下午 缺卡/未打卡为旷工一天";
                                            beLate_belate_ex.Deduction = day_deduction;
                                            ex_reissuecard_Items.Add(beLate_belate_ex);
                                        }
                                    }
                                    else if (root.exception_infos.Count == 1)
                                    {

                                        if (earliest_time == lastest_time)
                                        {
                                            DateTime thisDt1 = Convert.ToDateTime(thisDtStr + " 12:00");


                                            if (thisDt <= thisDt1)  //旷工 下午
                                            {
                                                day_deduction = ConvertToDecimal(dailyWage / 2); //4.5小时
                                                meal_deduction += 10.00M;

                                                beLate_belate_ex.Duration = 270;
                                                absenteeism_deduction += day_deduction; //矿工半日
                                                beLate_belate_ex.Reason = thisDtStr + " 下午(18:00)缺卡/未打卡视为下午旷工(4.5小时)";

                                                beLate_belate_ex.Deduction = day_deduction;
                                                ex_reissuecard_Items.Add(beLate_belate_ex);
                                            }
                                            else if (thisDt >= thisDt1) //旷工 上午
                                            {
                                                day_deduction = ConvertToDecimal(dailyWage / 2); //3小时
                                                meal_deduction += 10.00M;
                                                absenteeism_deduction += day_deduction; //矿工半日
                                                beLate_belate_ex.Duration = 180;
                                                beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)缺卡/未打卡视为上午旷工(3小时)";

                                                beLate_belate_ex.Deduction = day_deduction;
                                                ex_reissuecard_Items.Add(beLate_belate_ex);
                                            }
                                            else //矿工一日
                                            {

                                                day_deduction = ConvertToDecimal(dailyWage);
                                                meal_deduction += 10.00M;
                                                absenteeism_deduction += day_deduction;
                                                beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)-下午(18:00) 缺卡/未打视为旷工一天(7.5小时)";

                                                beLate_belate_ex.Deduction = day_deduction;
                                                ex_reissuecard_Items.Add(beLate_belate_ex);
                                            }
                                        }
                                    }
                                }
                                else if (exception == 4) //旷工
                                {
                                    if (timelength >= 60 && timelength <= 180)
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage / 2); //3小时
                                        beLate_belate_ex.Reason = thisDtStr + " 缺卡/未打视为旷工半天";
                                        meal_deduction += 10.00M;
                                        absenteeism_deduction += day_deduction; //矿工半日
                                    }
                                    else if (timelength > 180 && timelength <= 270)
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage / 2); //3小时
                                        beLate_belate_ex.Reason = thisDtStr + " 缺卡/未打视为旷工半天";
                                        meal_deduction += 10.00M;
                                        absenteeism_deduction += day_deduction; //矿工半日
                                    }
                                    else
                                    {
                                        day_deduction = ConvertToDecimal(dailyWage);
                                        beLate_belate_ex.Reason = thisDtStr + " 上午(09:00)-下午(18:00) 缺卡/未打视为旷工一天(7.5小时)";
                                        meal_deduction += 10.00M;
                                        absenteeism_deduction += day_deduction; //矿工一日
                                    }

                                    beLate_belate_ex.Deduction = day_deduction;
                                    ex_reissuecard_Items.Add(beLate_belate_ex);
                                }
                            }
                        }

                        #endregion

                        #region 外出打卡 迟到 早退 旷工

                        if (checkInData_outPunch.Count > 0)
                        {
                            List<Sp_Detail> sp_gooutpunch_details = new List<Sp_Detail>();
                            sp_gooutpunch_details = await _qiYeWeChatApiService.GetApprovalDetailsAsync(startDt, endDt, acctid, 2, 4); //时间段内所有 已同意的 外出打卡 审批数据
                            if (sp_gooutpunch_details.Count <= 0)
                            {
                                _result.Msg += $"{_name}:{startDt} - {endDt}  外出打卡 审批数据获取未获取到!\r\n";
                            }

                            List<LeaveDetails> goOutPunchDetails = new List<LeaveDetails>();
                            foreach (Sp_Detail sp_item in sp_gooutpunch_details)
                            {
                                Apply_data? apply_data = sp_item.apply_data;
                                if (apply_data != null)
                                {
                                    List<ContentsItem> contents = apply_data.contents;
                                    ContentsItem content_Attendance = contents.Where(it => it.control == "Attendance").FirstOrDefault();  //请假类型 
                                    ContentsItem content_Textarea = contents.Where(it => it.control == "Textarea").FirstOrDefault(); //多行文本 

                                    if (content_Attendance != null)
                                    {
                                        Attendance attendance = content_Attendance.value.attendance; //假勤组件

                                        string goOutText = string.Empty;
                                        if (content_Textarea != null)
                                        {
                                            goOutText = content_Textarea.value.text;
                                        }

                                        Date_range date_Range = attendance.date_range;

                                        //筛选 不在工作日内的假勤申请
                                        if (Convert.ToDateTime(date_Range.new_begin_dt) < startDt || Convert.ToDateTime(date_Range.new_end_dt.ToString("yyyy-MM-dd")) > endDt)
                                        {
                                            continue;
                                        }

                                        LeaveDetails leaveDetails1 = new LeaveDetails()
                                        {
                                            TypeId = 0,
                                            TypeName = "外出打卡",
                                            StartDt = date_Range.new_begin_dt,
                                            EndDt = date_Range.new_end_dt,
                                            DtType = date_Range.type,
                                            New_Duration = date_Range.new_duration
                                        };
                                        goOutPunchDetails.Add(leaveDetails1);
                                    }
                                }
                            }

                            foreach (var goOutPunchItem in goOutPunchDetails)
                            {
                                string thisDay = goOutPunchItem.StartDt.ToString("yyyy-MM-dd");
                                TimeSpan sp_gooutpunchStartTime = goOutPunchItem.StartDt.TimeOfDay;
                                TimeSpan sp_gooutpunchEndTime = goOutPunchItem.EndDt.TimeOfDay;
                                List<CheckInDataInfo> goOut_checkInDataInfos = checkInData_outPunch.Where(it => it.checkin_time_dt.ToString("yyyy-MM-dd").Equals(thisDay)).ToList();
                                //单天
                                if (goOut_checkInDataInfos.Count > 1)
                                {
                                    DateTime gooutStartDt = goOut_checkInDataInfos[0].checkin_time_dt;
                                    DateTime gooutendDt = goOut_checkInDataInfos[goOut_checkInDataInfos.Count - 1].checkin_time_dt;

                                    Ex_Item beLate_belate_ex = new Ex_Item()
                                    {
                                        SubTypeId = 4,
                                        SubType = "旷工",
                                        Duration = 0,
                                        StartTimeDt = Convert.ToDateTime(goOutPunchItem.StartDt),
                                        Unit = "分钟",
                                        Reason = "数据来源【外出打卡】"
                                    };

                                    decimal day_deduction = 0.00M;

                                    //迟到
                                    if (gooutStartDt.TimeOfDay > sp_gooutpunchStartTime)
                                    {
                                        int timeLong = gooutStartDt.Subtract(goOutPunchItem.StartDt).Minutes;
                                        beLate_belate_ex.Duration = timeLong;
                                        if (timeLong > 0 && timeLong < 10)
                                        {
                                            user_cd_zt_num++;
                                            beLate_belate_ex.SubTypeId = 1;
                                            beLate_belate_ex.SubType = "迟到";

                                            if (user_cd_zt_num >= 3)
                                            {
                                                day_deduction = 50.00M;
                                            }
                                            else
                                            {
                                                day_deduction = 0.00M;
                                            }
                                            beLate_deduction += day_deduction; //迟到扣款 总额
                                        }
                                        else if (timeLong >= 10 && timeLong < 60)
                                        {
                                            day_deduction = 50.00M;
                                            beLate_deduction += day_deduction; //迟到扣款 总额
                                            beLate_belate_ex.SubTypeId = 1;
                                            beLate_belate_ex.SubType = "迟到";
                                        }
                                        else if (timeLong >= 60 && timeLong <= 180)
                                        {
                                            day_deduction = ConvertToDecimal(dailyWage / 2); //3小时 按半天计算
                                            meal_deduction += 10.00M;  //餐补扣款
                                            absenteeism_deduction += day_deduction; //矿工半日
                                            beLate_belate_ex.Reason = "数据来源【外出打卡】" + thisDay + " 上午(09:00)缺卡/未打卡视为旷工半天";
                                        }
                                        else
                                        {
                                            day_deduction = ConvertToDecimal(dailyWage);
                                            absenteeism_deduction += day_deduction; //矿工一日
                                            meal_deduction += 10.00M;
                                            beLate_belate_ex.Reason = "数据来源【外出打卡】" + thisDay + " 上午(09:00)-下午(18:00) 缺卡/未打视为旷工一天(7.5小时)";
                                        }
                                        beLate_belate_ex.Deduction = day_deduction;
                                        ex_reissuecard_Items.Add(beLate_belate_ex);
                                    }

                                    //早退
                                    if (gooutendDt.TimeOfDay < sp_gooutpunchEndTime)
                                    {
                                        int timeLong = goOutPunchItem.EndDt.Subtract(gooutendDt).Minutes;
                                        beLate_belate_ex.Duration = timeLong;
                                        if (timeLong > 0 && timeLong < 10)
                                        {
                                            user_cd_zt_num++;
                                            beLate_belate_ex.SubTypeId = 1;
                                            beLate_belate_ex.SubType = "早退";


                                            if (user_cd_zt_num >= 3)
                                            {
                                                day_deduction = 50.00M;
                                            }
                                            else
                                            {
                                                day_deduction = 0.00M;
                                            }
                                            early_deduction += day_deduction; //迟到扣款 总额
                                        }
                                        else if (timeLong >= 10 && timeLong < 60)
                                        {
                                            day_deduction = 50.00M;
                                            early_deduction += day_deduction; //迟到扣款 总额
                                            beLate_belate_ex.SubTypeId = 1;
                                            beLate_belate_ex.SubType = "早退";
                                        }
                                        else if (timeLong >= 60 && timeLong <= 180)
                                        {
                                            day_deduction = ConvertToDecimal(dailyWage / 2); //3小时 按半天计算
                                            meal_deduction += 10.00M;  //餐补扣款
                                            absenteeism_deduction += day_deduction; //矿工半日
                                            beLate_belate_ex.Reason = "数据来源【外出打卡】" + thisDay + " 上午(09:00)缺卡/未打卡视为旷工半天";
                                        }
                                        else
                                        {
                                            day_deduction = ConvertToDecimal(dailyWage);
                                            absenteeism_deduction += day_deduction; //矿工一日
                                            meal_deduction += 10.00M;
                                            beLate_belate_ex.Reason = "数据来源【外出打卡】" + thisDay + " 上午(09:00)-下午(18:00) 缺卡/未打视为旷工一天(7.5小时)";
                                        }
                                        beLate_belate_ex.Deduction = day_deduction;
                                        ex_reissuecard_Items.Add(beLate_belate_ex);
                                    }
                                }

                                //多天
                            }
                        }
                        #endregion

                        #region 迟到早团旷工 日期排序

                        if (ex_reissuecard_Items.Count > 0)
                        {
                            ex_reissuecard_Items = ex_reissuecard_Items.OrderBy(it => it.StartTimeDt).ToList();
                        }

                        #endregion

                        #region 假勤/补卡次数 审批

                        int leaveNum = 0; //请假次数
                        int reissuecardNum = 0; //补卡次数
                        int evectionNum = 0; //出差次数
                        //类型:1 - 请假;2 - 补卡;3 - 出差;4 - 外出;100 - 外勤
                        leaveNum = acc_sp_items.Where(it => it.type == 1).ToList().Count();
                        reissuecardNum = acc_sp_items.Where(it => it.type == 2).ToList().Count();
                        List<Sp_items> acc_sp_items_evection = new List<Sp_items>();
                        acc_sp_items_evection = acc_sp_items.Where(it => it.type == 3).ToList();
                        evectionNum = acc_sp_items_evection.Count();

                        //请假审批
                        if (leaveNum > 0)
                        {
                            List<Sp_Detail> sp_leave_details = new List<Sp_Detail>();
                            sp_leave_details = await _qiYeWeChatApiService.GetApprovalDetailsAsync(startDt, endDt, acctid, 2, 1); //时间段内所有 已同意的 请假 审批数据
                            if (sp_leave_details.Count <= 0)
                            {
                                _result.Msg += $"{_name}: {startDt} - {endDt}  请假 审批数据获取未获取到!\r\n";
                                //continue;
                            }
                            List<Ex_Item> ex_ItemInfos = new List<Ex_Item>();

                            List<LeaveDetails> leaveDetails = new List<LeaveDetails>();
                            foreach (Sp_Detail sp_item in sp_leave_details)
                            {
                                Apply_data? apply_data = sp_item.apply_data;
                                if (apply_data != null)
                                {
                                    List<ContentsItem> contents = apply_data.contents;
                                    ContentsItem content_Vacation = contents.Where(it => it.control == "Vacation").FirstOrDefault();  //请假类型 
                                    ContentsItem content_Textarea = contents.Where(it => it.control == "Textarea").FirstOrDefault(); //多行文本 

                                    if (content_Vacation != null)
                                    {
                                        Vacation vacation = content_Vacation.value.vacation;
                                        Attendance attendance = vacation.attendance; //假勤组件
                                        Selector selector = vacation.selector;       //请假类型

                                        List<OptionsItem> optionsItems = selector.options; //key 请假类型 id
                                        List<TitleItem> value = optionsItems[0].value; // value 文本描述值

                                        int leaveType = int.Parse(optionsItems[0].key);  //key 请假子类型 id
                                        Date_range date_Range = attendance.date_range;

                                        //筛选 不在工作日内的假勤申请

                                        //if (Convert.ToDateTime(date_Range.new_begin_dt) < startDt || Convert.ToDateTime(date_Range.new_end_dt.ToString("yyyy-MM-dd")) > endDt)
                                        //{
                                        //    continue;
                                        //}

                                        //假期只要开始时间,结束时间在计算时间范围 即纳入计算 
                                        if ((Convert.ToDateTime(date_Range.new_begin_dt) < startDt || Convert.ToDateTime(date_Range.new_begin_dt) > endDt) &&
                                            (Convert.ToDateTime(date_Range.new_end_dt) < startDt || Convert.ToDateTime(date_Range.new_end_dt) > endDt))
                                        {
                                            continue;
                                        }

                                        string leave_starttime = date_Range.new_begin_dt.ToString("HH:mm");
                                        string leave_endtime = date_Range.new_end_dt.ToString("HH:mm");

                                        string typeName = string.Empty;
                                        string unit = string.Empty;
                                        int leaveTypeId = leaveType;
                                        var leaveTypeData = vacationLeaveTypes.Where(it => it.id == leaveTypeId).FirstOrDefault();

                                        if (leaveTypeData != null) { typeName = leaveTypeData.name; }

                                        string startTime = string.Empty;
                                        string endTime = string.Empty;
                                        string startTime1 = string.Empty;
                                        string endTime1 = string.Empty;
                                        Slice_info slice_info = new Slice_info();
                                        //2事假;3病假;
                                        if (leaveTypeId == 2 || leaveTypeId == 3)
                                        {
                                            slice_info = vacation.attendance.slice_info;
                                        }

                                        DateTime date_Range_new_begin_dt = date_Range.new_begin_dt;
                                        DateTime date_Range_new_end_dt = date_Range.new_end_dt;

                                        //计算请假类型扣款金额
                                        decimal new_duration = 0.00M;
                                        if (date_Range.type == "halfday")
                                        {
                                            new_duration = Convert.ToDecimal(date_Range.new_duration) / 86400.00M;

                                            if (date_Range.new_begin_dt < startDt)
                                            {
                                                decimal new_duration_count = new_duration;
                                                new_duration = 0.00M;

                                                for (int i = 0; i < new_duration_count; i++)
                                                {
                                                    DateTime thisDt = date_Range.new_begin_dt.AddDays(i);
                                                    Sys_Calendar sys_Calendar = new Sys_Calendar();
                                                    sys_Calendar = sys_Calendars.Where(it => it.Dt == thisDt.ToString("yyyy-MM-dd")).FirstOrDefault();
                                                    if (sys_Calendar != null)
                                                    {
                                                        if (sys_Calendar.IsWorkDay)
                                                        {

                                                            new_duration++;
                                                        }
                                                    }
                                                }
                                            }


                                            unit = "天";
                                            startTime = date_Range_new_begin_dt.ToString("yyyy-MM-dd") + " 09:00";
                                            endTime = date_Range_new_end_dt.ToString("yyyy-MM-dd") + " 18:00";

                                            if (new_duration > 0.50M)
                                            {
                                                if (slice_info != null)
                                                {
                                                    if (slice_info.day_items != null)
                                                    {
                                                        if (slice_info.day_items.Count > 1)
                                                        {
                                                            date_Range_new_begin_dt = slice_info.day_items[0].daytimeDt;
                                                            date_Range_new_end_dt = slice_info.day_items[slice_info.day_items.Count - 1].daytimeDt;

                                                            decimal startTime11 = slice_info.day_items[0].duration;
                                                            decimal startTime11_11 = startTime11 / 3600.00M;
                                                            decimal endTime11 = slice_info.day_items[slice_info.day_items.Count - 1].duration;
                                                            decimal endTime11_11 = endTime11 / 3600.00M;
                                                            if (startTime11_11 == 3.00M)
                                                            {
                                                                startTime1 = "09:00";
                                                            }
                                                            else if (startTime11_11 == 4.50M)
                                                            {
                                                                startTime1 = "12:00";
                                                            }
                                                            else if (startTime11_11 == 7.50M)
                                                            {
                                                                startTime1 = "09:00";
                                                            }

                                                            if (endTime11_11 == 3.00M)
                                                            {
                                                                endTime1 = "12:00";
                                                            }
                                                            else if (endTime11_11 == 4.50M)
                                                            {
                                                                endTime1 = "18:00";
                                                            }
                                                            else if (endTime11_11 == 7.50M)
                                                            {
                                                                endTime1 = "18:00";
                                                            }

                                                        }
                                                        else
                                                        {
                                                            decimal qjLongTime = slice_info.duration / 3600.00M;
                                                            if (qjLongTime == 4.50M)
                                                            {
                                                                startTime1 = "12:00";
                                                                endTime1 = "18:00:00";
                                                            }
                                                            else if (qjLongTime == 3.00M)
                                                            {
                                                                startTime1 = "09:00";
                                                                endTime1 = "12:00:00";
                                                            }
                                                            else if (qjLongTime % 7.50M == 0)
                                                            {
                                                                startTime1 = "09:00";
                                                                endTime1 = "18:00:00";
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (new_duration % 1 == 0)
                                                        {
                                                            startTime1 = "09:00";
                                                            endTime1 = "18:00";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if (new_duration % 1 == 0)
                                                    {
                                                        startTime1 = "09:00";
                                                        endTime1 = "18:00";
                                                    }
                                                }

                                            }
                                            else
                                            {
                                                if (new_duration % 1 == 0)
                                                {
                                                    startTime1 = "09:00";
                                                    endTime1 = "18:00";
                                                }
                                                else
                                                {
                                                    startTime1 = date_Range_new_begin_dt.ToString("HH:mm:ss");
                                                    endTime1 = date_Range_new_end_dt.ToString("HH:mm:ss");
                                                }
                                            }
                                        }
                                        else if (date_Range.type == "hour")
                                        {
                                            new_duration = Convert.ToDecimal(date_Range.new_duration) / 3600.00M;
                                            unit = "小时";
                                            startTime = date_Range_new_begin_dt.ToString("yyyy-MM-dd HH:mm:ss");
                                            endTime = date_Range_new_end_dt.ToString("yyyy-MM-dd HH:mm:ss");
                                            startTime1 = date_Range_new_begin_dt.ToString("HH:mm:ss");
                                            endTime1 = date_Range_new_end_dt.ToString("HH:mm:ss");
                                        }



                                        LeaveDetails leaveDetails1 = new LeaveDetails()
                                        {
                                            TypeId = leaveType,
                                            TypeName = typeName,
                                            StartDt = Convert.ToDateTime(date_Range_new_begin_dt.ToString("yyyy-MM-dd") + " " + startTime1),
                                            EndDt = Convert.ToDateTime(date_Range_new_end_dt.ToString("yyyy-MM-dd") + " " + endTime1),
                                            DtType = date_Range.type,
                                            Unit = unit,
                                            New_Duration = new_duration,
                                            SliceInfo = slice_info
                                        };
                                        leaveDetails.Add(leaveDetails1);
                                    }
                                }
                            }

                            #region 年假测试数据
                            //leaveDetails.Add(new LeaveDetails() { 
                            //    TypeId = 1,
                            //    TypeName = "年假",
                            //    StartDt = Convert.ToDateTime("2023-11-21 09:00:00"),
                            //    EndDt = Convert.ToDateTime("2023-11-21 12:00:00"),
                            //    DtType = "halfday",
                            //    Unit = "天",
                            //    New_Duration = 0.50M
                            //});

                            //leaveDetails.Add(new LeaveDetails()
                            //{
                            //    TypeId = 1,
                            //    TypeName = "年假",
                            //    StartDt = Convert.ToDateTime("2023-11-21 12:00:00"),
                            //    EndDt = Convert.ToDateTime("2023-11-23 18:00:00"),
                            //    DtType = "halfday",
                            //    Unit = "天",
                            //    New_Duration = 2.50M
                            //});


                            #endregion

                            if (leaveDetails.Count > 0)
                            {
                                leaveDetails = leaveDetails.OrderBy(it => it.StartDt).OrderBy(it => it.EndDt).ToList();

                                foreach (LeaveDetails leave_item in leaveDetails)
                                {
                                    decimal leave_meals = 0.00M;
                                    decimal thisTypeDeduction = 0.00M;//当前类型扣款

                                    int leaveType = leave_item.TypeId;
                                    decimal new_duration = leave_item.New_Duration;

                                    #region 处理跨月天数

                                    if (leave_item.EndDt > endDt)
                                    {
                                        DateTime dt1 = Convert.ToDateTime(leave_item.StartDt.ToString("yyyy-MM-dd") + " 12:00");
                                        DateTime dt2 = Convert.ToDateTime(leave_item.StartDt.ToString("yyyy-MM-dd") + " 09:00");
                                        TimeSpan ts = Convert.ToDateTime(endDt.ToString("yyyy-MM-dd") + " 18:00") - Convert.ToDateTime(leave_item.StartDt.ToString("yyyy-MM-dd"));
                                        if (dt2 >= leave_item.StartDt && leave_item.StartDt <= dt1)
                                        {
                                            new_duration = ts.Days + 1;
                                        }
                                        else
                                        {
                                            new_duration = ts.Days + 1.00M + 0.50M;
                                        }
                                    }

                                    #endregion

                                    //计算餐补 假勤类型扣款
                                    CalculateTypeFee1(leaveDetails, leaveType, leave_item.DtType, leave_item.StartDt, leave_item.EndDt, amountPayable, work_days,
                                        new_duration, out leave_meals, out thisTypeDeduction);
                                    if (leave_meals != 0)
                                    {
                                        leave_item.IsDeduction = true;
                                    }

                                    #region 累计类型扣款
                                    //1年假;2事假;3病假;4调休假;5婚假;6产假;7陪产假;8其他;9丧假
                                    if (leaveType == 2) //事假
                                    {
                                        personalLeaveTotal += thisTypeDeduction;
                                    }
                                    else if (leaveType == 3) //病假
                                    {
                                        sickLeaveTotal += thisTypeDeduction;
                                    }

                                    #endregion

                                    meal_deduction += leave_meals;

                                    Ex_Item ex_Item = new Ex_Item()
                                    {
                                        SubTypeId = leaveType,
                                        SubType = leave_item.TypeName,
                                        StartTimeDt = leave_item.StartDt,
                                        EndTimeDt = leave_item.EndDt,
                                        Duration = new_duration,
                                        Unit = leave_item.Unit,
                                        Deduction = thisTypeDeduction,
                                        //Reason = apply_data.reason,
                                        Apply_time_dt = leave_item.ApplyDt,
                                        //Approval_name = sp_item.approval_name,
                                    };
                                    ex_ItemInfos.Add(ex_Item);
                                }
                            }

                            if (ex_ItemInfos.Count > 0)
                            {
                                ex_Items_jq.Ex_ItemInfo = ex_ItemInfos.OrderBy(it => it.StartTimeDt).ThenBy(it => it.Apply_time_dt).ToList();
                                ex_Items.Add(ex_Items_jq);
                            }
                        }

                        //打卡补卡
                        //补卡:员工发现自己漏打卡时,需及时提起补卡申请,并说明情况。
                        //试用期员工每月有 2 次补卡机会,超过 2 次不足 5 次的部分,按 10 元/次处罚,5 次及以上的漏卡,按 50 元/次处罚;
                        //正式员工每月 3 次以内的补卡,按 10 元/次处罚,3 次及以上的漏卡,按 50 元/次处罚。
                        if (reissuecardNum > 0)
                        {
                            List<Sp_Detail> sp_buka_details = new List<Sp_Detail>();
                            sp_buka_details = await _qiYeWeChatApiService.GetApprovalDetailsAsync(startDt, endDt, acctid, 2, 2); //时间段内所有 已同意的 请假 审批数据


                            //外出审批 已通过的数据 且 外出未打卡
                            List<Sp_Detail> sp_goout_details = new List<Sp_Detail>();
                            sp_goout_details = await _qiYeWeChatApiService.GetApprovalDetailsAsync(startDt, endDt, acctid, 2, 4); //时间段内所有 已同意的 外出 审批数据
                            //打卡记录-未打卡 处理日期范围内的数据
                            List<CheckInDataInfo> filtratePrefix_checkInData = new List<CheckInDataInfo>();

                            //打卡记录-未打卡 扣款
                            if (sp_goout_details.Count > 0)
                            {
                                //找出外出的具体日期
                                List<string> goOutDts = new List<string>();
                                foreach (var goOutItem in sp_goout_details)
                                {
                                    Apply_data? apply_data = goOutItem.apply_data;
                                    if (apply_data != null)
                                    {
                                        List<ContentsItem> contents = apply_data.contents;
                                        ContentsItem content_Vacation = contents.Where(it => it.control == "Attendance").FirstOrDefault();  //请假类型 
                                        ContentsItem content_Textarea = contents.Where(it => it.control == "Textarea").FirstOrDefault();    //多行文本 

                                        if (content_Vacation != null)
                                        {
                                            var attendance = content_Vacation.value.attendance;

                                            DateTime goOutDt = attendance.date_range.new_begin_dt;
                                            DateTime goOutDtJudge = Convert.ToDateTime(goOutDt.ToString("yyyy-MM-dd"));
                                            //筛选 不在工作日内的假勤申请
                                            if (startDt >= goOutDtJudge || goOutDtJudge > endDt)
                                            {
                                                continue;
                                            }
                                            goOutDts.Add(goOutDt.ToString("yyyy-MM-dd"));
                                        }
                                    }
                                }

                                if (goOutDts.Count > 0)
                                {
                                    foreach (var goOutDtItem in goOutDts)
                                    {
                                        List<CheckInDataInfo> filtrate_checkInData = new List<CheckInDataInfo>();
                                        filtrate_checkInData = checkInData2.Where(it => it.checkin_time_dt.ToString("yyyy-MM-dd").Equals(goOutDtItem)).ToList();
                                        if (filtrate_checkInData.Count > 0)
                                        {
                                            filtratePrefix_checkInData.AddRange(filtrate_checkInData);
                                        }
                                    }
                                }
                            }

                            int bukaNum = 1;
                            foreach (var item in sp_buka_details)
                            {
                                Apply_data? apply_data = item.apply_data;
                                if (apply_data != null)
                                {
                                    List<ContentsItem> contents = apply_data.contents;
                                    ContentsItem content_Vacation = contents.Where(it => it.control == "PunchCorrection").FirstOrDefault();  //请假类型 
                                    ContentsItem content_Textarea = contents.Where(it => it.control == "Textarea").FirstOrDefault(); //多行文本 

                                    if (content_Vacation != null)
                                    {
                                        var punch_correction = content_Vacation.value.punch_correction;

                                        DateTime bukaDt = punch_correction.time_dt;
                                        DateTime bukaDtJudge = Convert.ToDateTime(bukaDt.ToString("yyyy-MM-dd"));
                                        //筛选 不在工作日内的假勤申请
                                        if (startDt > bukaDtJudge || bukaDtJudge > endDt)
                                        {
                                            continue;
                                        }

                                        decimal bukaPrice = 0.00M;

                                        if (user_probationary_bk_decimal == 0) //计算试用员工补卡次数
                                        {
                                            if (bukaNum <= 2) bukaPrice = 0.00M;
                                            else if (bukaNum <= 4 && bukaNum > 2) bukaPrice = 10.00M;
                                            else bukaPrice = 50.00M;

                                        }
                                        else   //计算正式员工补卡次数
                                        {
                                            if (bukaNum <= 2) bukaPrice = 10.00M;
                                            else bukaPrice = 50.00M;
                                        }

                                        var app_data = item.apply_data;
                                        var punch_correction1 = app_data.contents[0].value.punch_correction; //未打卡时间
                                        var punch_correction2 = app_data.contents[1].value;

                                        #region 处理未打卡记录表数据 已补卡的数据

                                        if (filtratePrefix_checkInData.Count > 0)
                                        {
                                            var filtratePrefix_checkInItems = filtratePrefix_checkInData.Where(it => it.sch_checkin_time_dt.ToString("yyyy-MM-dd")
                                                                                                                       .Equals(punch_correction1.time_dt.ToString("yyyy-MM-dd"))).ToList();
                                            if (filtratePrefix_checkInItems.Count > 0)
                                            {
                                                //按时间段移除 上午补卡时间段 09:00 - 12:00 下午补卡时间段 12:00 - 18:00
                                                TimeSpan _strWorkingDayAM = DateTime.Parse("09:00").TimeOfDay;
                                                TimeSpan _endWorkingDayAM = DateTime.Parse("12:00").TimeOfDay;
                                                TimeSpan _strWorkingDayPM = DateTime.Parse("13:30").TimeOfDay;
                                                TimeSpan _endWorkingDayPM = DateTime.Parse("18:00").TimeOfDay;
                                                TimeSpan _dspNow = punch_correction1.time_dt.TimeOfDay;

                                                //上午时间段 打卡记录数据
                                                var filtratePrefix_checkInItemAMs = filtratePrefix_checkInItems.Where(it => it.sch_checkin_time_dt.TimeOfDay >= _strWorkingDayAM &&
                                                                                                                           it.sch_checkin_time_dt.TimeOfDay <= _endWorkingDayAM).ToList();
                                                if (filtratePrefix_checkInItemAMs.Count > 0)
                                                {
                                                    foreach (var filtratePrefix_checkInItem1 in filtratePrefix_checkInItemAMs)
                                                    {
                                                        filtratePrefix_checkInData.Remove(filtratePrefix_checkInItem1);
                                                    }
                                                }

                                                //下午时间段 打卡记录数据
                                                var filtratePrefix_checkInItemPMs = filtratePrefix_checkInItems.Where(it => it.sch_checkin_time_dt.TimeOfDay >= _strWorkingDayPM &&
                                                                                                                           it.sch_checkin_time_dt.TimeOfDay <= _endWorkingDayPM).ToList();
                                                if (filtratePrefix_checkInItemPMs.Count > 0)
                                                {
                                                    foreach (var filtratePrefix_checkInItem1 in filtratePrefix_checkInItemPMs)
                                                    {
                                                        filtratePrefix_checkInData.Remove(filtratePrefix_checkInItem1);
                                                    }
                                                }
                                            }
                                        }

                                        #endregion

                                        Ex_Item ex_reissueCard = new Ex_Item()
                                        {
                                            SubTypeId = 7,
                                            SubType = "打卡补卡",
                                            StartTimeDt = Convert.ToDateTime(punch_correction1.time_dt.ToString("yyyy-MM-dd HH:mm:ss")),  //未打卡时间
                                            Deduction = bukaPrice,
                                            Reason = punch_correction2.text,
                                            Unit = string.Empty
                                        };
                                        unprinted_deduction += bukaPrice;
                                        ex_reissuecard_Items.Add(ex_reissueCard);
                                        bukaNum++;
                                    }
                                }
                            }

                            //打卡记录里抓取的未打卡数据 扣款
                            foreach (var item in filtratePrefix_checkInData)
                            {
                                decimal bukaPrice = 0.00M;

                                if (user_probationary_bk_decimal == 0) //计算试用员工补卡次数
                                {
                                    if (bukaNum <= 2) bukaPrice = 0.00M;
                                    else if (bukaNum <= 4 && bukaNum > 2) bukaPrice = 10.00M;
                                    else bukaPrice = 50.00M;
                                }
                                else   //计算正式员工补卡次数
                                {
                                    if (bukaNum <= 2) bukaPrice = 10.00M;
                                    else bukaPrice = 50.00M;
                                }

                                Ex_Item ex_reissueCard = new Ex_Item()
                                {
                                    SubTypeId = 7,
                                    SubType = "打卡补卡",
                                    StartTimeDt = Convert.ToDateTime(item.checkin_time_dt.ToString("yyyy-MM-dd HH:mm:ss")),  //未打卡时间
                                    Deduction = bukaPrice,
                                    Reason = "[打卡记录]抓取到的未打卡数据!",
                                    Unit = string.Empty
                                };
                                unprinted_deduction += bukaPrice;
                                ex_reissuecard_Items.Add(ex_reissueCard);
                                bukaNum++;
                            }
                        }

                        if (ex_reissuecard_Items.Count > 0)
                        {
                            ex_Items_dk.Ex_ItemInfo = ex_reissuecard_Items;
                            ex_Items_dk.Ex_ItemInfo = ex_reissuecard_Items.OrderBy(it => it.SubTypeId).ThenBy(it => it.StartTimeDt).ToList();
                            ex_Items.Add(ex_Items_dk);
                        }

                        //出差申请
                        if (evectionNum > 0)
                        {
                            List<Sp_Detail> sp_leave_details = new List<Sp_Detail>();
                            sp_leave_details = await _qiYeWeChatApiService.GetApprovalDetailsAsync(startDt, endDt, acctid, 2, 3); //时间段内所有 已同意的 出差 审批数据
                            if (sp_leave_details.Count <= 0)
                            {
                                _result.Msg += $"{_name}: {startDt} - {endDt}  请假 审批数据获取未获取到!\r\n";
                                //continue;
                            }
                            List<Ex_Item> cc_ex_ItemInfos = new List<Ex_Item>();

                            foreach (Sp_Detail sp_item in sp_leave_details)
                            {
                                Apply_data? apply_data = sp_item.apply_data;
                                if (apply_data != null)
                                {
                                    List<ContentsItem> contents = apply_data.contents;
                                    ContentsItem content_Vacation = contents.Where(it => it.control == "Attendance").FirstOrDefault();  //出差类型 
                                    ContentsItem content_Textarea = contents.Where(it => it.control == "Textarea").FirstOrDefault(); //多行文本 

                                    if (content_Vacation != null)
                                    {
                                        //Vacation vacation = content_Vacation.value.vacation;
                                        Attendance attendance = content_Vacation.value.attendance; //假勤组件
                                        //Selector selector = vacation.selector;       //请假类型

                                        //List<OptionsItem> optionsItems = selector.options; //key 请假类型 id
                                        //List<TitleItem> value = optionsItems[0].value; // value 文本描述值

                                        int leaveType = int.Parse("3");  //key 请假子类型 id
                                        Date_range date_Range = attendance.date_range;

                                        //筛选 不在工作日内的假勤申请
                                        if (date_Range.new_begin_dt < startDt || date_Range.new_end_dt > endDt)
                                        {
                                            continue;
                                        }

                                        string leave_starttime = date_Range.new_begin_dt.ToString("HH:mm");
                                        string leave_endtime = date_Range.new_end_dt.ToString("HH:mm");

                                        string typeName = string.Empty;
                                        string unit = string.Empty;
                                        int leaveTypeId = leaveType;
                                        typeName = "出差";

                                        string startTime = string.Empty;
                                        string endTime = string.Empty;
                                        string startTime1 = string.Empty;
                                        string endTime1 = string.Empty;
                                        //计算请假类型扣款金额
                                        decimal new_duration = 0.00M;
                                        if (date_Range.type == "halfday")
                                        {
                                            new_duration = Convert.ToDecimal(date_Range.new_duration) / 86400.00M;
                                            unit = "天";
                                            startTime = date_Range.new_begin_dt.ToString("yyyy-MM-dd") + " 00:00";
                                            endTime = date_Range.new_end_dt.ToString("yyyy-MM-dd") + " 00:00";
                                            startTime1 = "00:00:00";
                                            endTime1 = "00:00:00";
                                        }
                                        else if (date_Range.type == "hour")
                                        {
                                            new_duration = Convert.ToDecimal(date_Range.new_duration) / 3600.00M;
                                            unit = "小时";
                                            startTime = date_Range.new_begin_dt.ToString("yyyy-MM-dd HH:mm:ss");
                                            endTime = date_Range.new_end_dt.ToString("yyyy-MM-dd HH:mm:ss");
                                            startTime1 = date_Range.new_begin_dt.ToString("HH:mm:ss");
                                            endTime1 = date_Range.new_end_dt.ToString("HH:mm:ss");
                                        }

                                        //出差扣款
                                        decimal cckk = 0.00M;

                                        int days = (int)(Convert.ToDateTime(date_Range.new_end_dt.ToString("yyyy-MM-dd")) -
                                                         Convert.ToDateTime(date_Range.new_begin_dt.ToString("yyyy-MM-dd"))).TotalDays + 1;


                                        for (int i = 0; i < days; i++)
                                        {
                                            DateTime thisDt = date_Range.new_begin_dt.AddDays(i);

                                            //处理开始时间 是否在当天工作时间内
                                            if (i == 0) //开始时间
                                            {

                                                if (!date_Range.type.Equals("halfday"))
                                                {
                                                    string ccStartTime = thisDt.ToString("HH:mm:ss");
                                                    if (!IsWorkTime(ccStartTime))
                                                    {
                                                        continue;
                                                    }
                                                }

                                            }

                                            //处理结束时间 是否在当天工作时间内
                                            if (i == days - 1)
                                            {
                                                if (!date_Range.type.Equals("halfday"))
                                                {
                                                    string ccStartTime = date_Range.new_end_dt.ToString("HH:mm:ss");
                                                    if (!IsWorkTime(ccStartTime))
                                                    {
                                                        continue;
                                                    }
                                                }
                                            }

                                            Sys_Calendar sys_Calendar = new Sys_Calendar();
                                            sys_Calendar = sys_Calendars.Where(it => it.Dt == thisDt.ToString("yyyy-MM-dd")).FirstOrDefault();
                                            if (sys_Calendar != null)
                                            {
                                                if (sys_Calendar.IsWorkDay)
                                                {
                                                    cckk += 10.00M;
                                                }
                                            }
                                        }


                                        meal_deduction += cckk;


                                        Ex_Item ex_Item = new Ex_Item()
                                        {
                                            SubTypeId = leaveType,
                                            SubType = typeName,
                                            StartTimeDt = Convert.ToDateTime(date_Range.new_begin_dt.ToString("yyyy-MM-dd") + " " + startTime1),
                                            EndTimeDt = Convert.ToDateTime(date_Range.new_end_dt.ToString("yyyy-MM-dd") + " " + endTime1),
                                            Duration = new_duration,
                                            Unit = unit,
                                            Deduction = 0.00M,
                                            //Reason = apply_data.reason,
                                            Apply_time_dt = Convert.ToDateTime(sp_item.apply_time_dt.ToString("yyyy-MM-dd HH:mm:ss"))
                                            //Approval_name = sp_item.approval_name,
                                        };

                                        cc_ex_ItemInfos.Add(ex_Item);

                                    }
                                }
                            }

                            if (cc_ex_ItemInfos.Count > 0)
                            {
                                //ex_Items_cc.Ex_ItemInfo = cc_ex_ItemInfos.OrderBy(it => it.StartTimeDt).ThenBy(it => it.Apply_time_dt).ToList();
                                //;
                                //ex_Items.Add(ex_Items_cc);
                                List<Ex_Item> ex_jq_Items = new List<Ex_Item>();
                                List<Ex_Item> ex_Items1 = new List<Ex_Item>();
                                ex_Items1 = (List<Ex_Item>)ex_Items_jq.Ex_ItemInfo;
                                if (ex_Items1 != null && ex_Items1.Count > 0)
                                {
                                    ex_jq_Items = ex_Items1;
                                }

                                ex_jq_Items.AddRange(cc_ex_ItemInfos);
                                ex_Items.Remove(ex_Items_jq);
                                ex_Items.Add(
                                    new Ex_Items()
                                    {
                                        Type = "假勤",
                                        Ex_ItemInfo = ex_jq_Items.OrderBy(it => it.StartTimeDt).ThenBy(it => it.Apply_time_dt).ToList()
                                    }
                                    );
                            }
                        }


                        #endregion

                    }
                    else
                    {
                        meal_subsidy = work_days * 10.00M;
                    }

                    #region 应发合计 实发合计 扣款合计(假勤扣款,其他扣款,社保扣款,公积金代扣,个税扣款)
                    int workDays = dk_work_days + spe_offdays;
                    decimal mealTotal = meal_subsidy - meal_deduction;  //餐补
                    decimal salaryTotal = 0.00M;
                    if (dk_work_days >= work_days)
                    {
                        dk_work_days = work_days;
                        salaryTotal = amountPayable + mealTotal + pm_wsInfo.OtherHandle;    //应发合计
                    }
                    else
                    {
                        if (_name.Equals("张海麟"))
                        {
                            salaryTotal = amountPayable + mealTotal + pm_wsInfo.OtherHandle;    //应发合计
                        }
                        else
                        {
                            salaryTotal = (workDays * dailyWage) + mealTotal + pm_wsInfo.OtherHandle;    //应发合计
                        }

                    }


                    //扣款合计 不含个税
                    decimal eductionTotal = sickLeaveTotal + personalLeaveTotal + beLate_deduction + early_deduction + absenteeism_deduction + unprinted_deduction + other_deduction +
                        pm_wsInfo.WithholdingInsurance + pm_wsInfo.ReservedFunds + pm_wsInfo.OtherDeductions;
                    decimal actualReleaseTotal = salaryTotal - eductionTotal; //实发合计 * 不含个税

                    #endregion

                    #region 处理当月工资数据
                    pm_wsInfo.YearMonth = thisYearMonth;
                    pm_wsInfo.StartDate = startDt.ToString("yyyy-MM-dd");
                    pm_wsInfo.EndDate = endDt.ToString("yyyy-MM-dd");
                    pm_wsInfo.WorkDays = work_days;        //当月应出勤天数
                    pm_wsInfo.RegularDays = workDays;  //当月正常出勤天数
                    pm_wsInfo.SickLeave = sickLeaveTotal;           //病假
                    pm_wsInfo.SomethingFalse = personalLeaveTotal;  //事假
                    pm_wsInfo.LateTo = beLate_deduction;            //迟到
                    pm_wsInfo.LeaveEarly = early_deduction;         //早退
                    pm_wsInfo.Absenteeism = absenteeism_deduction;  //旷工
                    pm_wsInfo.NotPunch = unprinted_deduction;       //未打卡
                    pm_wsInfo.OtherDeductions = other_deduction;    //其他
                    pm_wsInfo.Ex_ItemsRemark = JsonConvert.SerializeObject(ex_Items);  //
                    pm_wsInfo.Mealsupplement = mealTotal;          //餐补

                    pm_wsInfo.Should = ConvertToDecimal(salaryTotal);               //应发合计
                    pm_wsInfo.TotalDeductions = ConvertToDecimal(eductionTotal);    //扣款合计
                    pm_wsInfo.TotalRealHair = ConvertToDecimal(actualReleaseTotal - pm_wsInfo.WithholdingTax); //实发合计
                    pm_wsInfo.AfterTax = ConvertToDecimal(actualReleaseTotal - pm_wsInfo.WithholdingTax); //税后工资

                    pm_wsInfo.LastUpdateUserId = userId;
                    pm_wsInfo.LastUpdateDt = DateTime.Now;
                    pm_wsInfo.CreateUserId = userId;
                    pm_wsInfo.CreateTime = DateTime.Now;
                    pm_wsInfo.DeleteUserId = null;
                    pm_wsInfo.DeleteTime = string.Empty;
                    #endregion

                }
            }
            catch (Exception ex)
            {

                _result.Msg = $"【{_name}】【Msg:{ex.Message}】";

                return _result;
            }

            _result.Code = 0;
            _result.Data = pm_WageSheetDattaSources;

            return _result;
        }

        /// <summary>
        /// 是否在工作时间内
        /// </summary>
        /// <param name="timeStr"></param>
        /// <returns></returns>
        public static bool IsWorkTime(string timeStr)
        {
            string thisDayWorkStartTime = "09:00:00";
            string thisDayWorkEndTime = "18:00:00";

            TimeSpan dspWorkingDayAM = DateTime.Parse(thisDayWorkStartTime).TimeOfDay;
            TimeSpan dspWorkingDayPM = DateTime.Parse(thisDayWorkEndTime).TimeOfDay;

            DateTime dt = Convert.ToDateTime(timeStr);
            TimeSpan dspNow = dt.TimeOfDay;
            if (dspNow >= dspWorkingDayAM && dspNow <= dspWorkingDayPM)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// decimal 保留两位小数 不四舍五入
        /// </summary>
        /// <param name="myDecimal"></param>
        /// <returns></returns>
        public static decimal ConvertToDecimal(decimal myDecimal)
        {
            var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
            return subDecimal;
        }

        /// <summary>
        /// decimal 保留两位小数 不四舍五入
        /// </summary>
        /// <param name="myDecimal"></param>
        /// <returns></returns>
        public static decimal ConvertToDecimal1(this decimal myDecimal)
        {
            var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
            return subDecimal;
        }

        /// <summary>
        /// 列表的成员移动到列表的前面
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="index"></param>
        public static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
        {
            T item = list[index];
            list.RemoveAt(index);
            list.Insert(0, item);
        }

        /// <summary>
        /// 获取请假类型
        /// </summary>
        /// <param name="template_id"></param>
        /// <returns></returns>
        public static async Task<List<VacationLeaveTypeView>> GetVacationLeaveTypes(string template_id)
        {
            List<VacationLeaveTypeView> vacationLeaveTypes = new List<VacationLeaveTypeView>();

            TemplateDetailView templateDetailView = new TemplateDetailView();
            templateDetailView = await _qiYeWeChatApiService.GetTemplateDetailAsync(template_id);
            if (templateDetailView.errcode != 0)
            {
                Serilog.Log.Error("【企业微信】【审批】【获取假勤类型的审批】【Msg】" + templateDetailView.errmsg);
                return vacationLeaveTypes;
            }
            List<VacationItemInfo> VacationItemInfos = templateDetailView.vacation_list.item;

            foreach (var item in VacationItemInfos)
            {
                ValueItem valueInfo = item.name.Where(it => it.lang == "zh_CN").FirstOrDefault();
                if (valueInfo != null)
                {
                    vacationLeaveTypes.Add(
                    new VacationLeaveTypeView()
                    {
                        id = item.id,
                        name = valueInfo.text
                    });
                }
            }

            return vacationLeaveTypes;
        }

        /// <summary>
        /// 计算类型费用
        /// 病假 事假 计算 按天计算
        /// </summary>
        /// <param name="leaveDetails"></param>
        /// <param name="leaveType">1年假;2事假;3病假;4调休假;5婚假;6产假;7陪产假;8其他;9丧假</param>
        /// <param name="date_Range_type"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="amountPayable"></param>
        /// <param name="work_days"></param>
        /// <param name="duration"></param>
        /// <param name="mealDeduction"></param>
        /// <param name="typeDeduction"></param>
        public static void CalculateTypeFee1(List<LeaveDetails> leaveDetails, int leaveType, string date_Range_type, DateTime startTime, DateTime endTime,
            decimal amountPayable, int work_days, decimal duration, out decimal mealDeduction, out decimal typeDeduction)
        {
            typeDeduction = 0;
            mealDeduction = 0;
            decimal personalkLeave_dailywage_day = amountPayable / work_days; //日薪 = 事假日薪 *计算方式:日平均工资 = 当月应发工资 /当月应出勤天数。

            //半小时单位
            //decimal halfHour = 7.50M / 0.50M;

            switch (leaveType)
            {
                case 1: //年假

                    if (date_Range_type == "halfday")
                    {
                        if (duration >= 0.5M && duration <= 1M) //一天
                        {
                            var njItem = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd") == startTime.ToString("yyyy-MM-dd") &&
                                                      it.EndDt.ToString("yyyy-MM-dd") == endTime.ToString("yyyy-MM-dd")).ToList();
                            if (njItem.Count > 1)
                            {
                                if (njItem[0].StartDt == startTime)
                                {
                                    mealDeduction = 10; //餐补扣款
                                }
                            }
                            else
                            {
                                mealDeduction = 10; //餐补扣款 
                            }
                        }
                        else // 多天
                        {
                            var njManyDaysItem = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd") == startTime.ToString("yyyy-MM-dd")).ToList();
                            if (njManyDaysItem.Count > 1)
                            {
                                var njManyDaysItem1 = njManyDaysItem.Where(it => it.StartDt != startTime).ToList();
                                if (njManyDaysItem1.Count > 0)
                                {
                                    if (njManyDaysItem1[0].Unit.Equals("天"))
                                    {
                                        mealDeduction = 10 * Math.Floor(duration);
                                    }
                                    else if (njManyDaysItem1[0].Unit.Equals("小时") && njManyDaysItem1[0].New_Duration >= 3)
                                    {
                                        mealDeduction = 10 * Math.Floor(duration);
                                    }
                                    else
                                    {
                                        mealDeduction = 10 * Math.Ceiling(duration);
                                    }
                                }
                            }
                            else
                            {
                                mealDeduction = 10 * Math.Ceiling(duration);
                            }
                        }
                    }

                    break;
                case 2: //2事假
                    // 事假日薪 *计算方式:日平均工资 = 当月应发工资 /当月应出勤天数。 
                    decimal personalkLeave_dailywage_halfhour = personalkLeave_dailywage_day / 7.50M; //事假单位 0.5小时

                    if (date_Range_type == "halfday")
                    {
                        #region 处理当天是否扣除餐补
                        string formatDt_begin = startTime.ToString("yyyy-MM-dd");
                        List<LeaveDetails> leaveDetails1 = leaveDetails.Where(it => it.IsDeduction && it.EndDt.ToString("yyyy-MM-dd") == formatDt_begin).ToList();
                        if (leaveDetails1.Count > 0) mealDeduction = 10.00M * Math.Floor(duration); //餐补扣款 
                        else mealDeduction = 10.00M * Math.Ceiling(duration); //餐补扣款 
                        #endregion

                        if (duration % 1 == 0) //整天
                        {
                            typeDeduction = ConvertToDecimal(personalkLeave_dailywage_day * duration);
                        }
                        else //多含 半天 另外处理
                        {
                            decimal sj_wholeDay = Math.Floor(duration); //整天
                            decimal sj_halfDay = duration % 1; //半天

                            if (duration % 1 > 0)
                            {
                                typeDeduction = (personalkLeave_dailywage_day / 2.00M) * (duration / 0.50M);
                            }
                            else
                            {
                                typeDeduction = (personalkLeave_dailywage_day / 2.00M);
                            }
                            typeDeduction = ConvertToDecimal(typeDeduction);
                        }
                    }
                    else if (date_Range_type == "hour")
                    {
                        decimal leave_halfHour = Convert.ToDecimal(duration) / Convert.ToDecimal(0.5);
                        typeDeduction = ConvertToDecimal(personalkLeave_dailywage_halfhour * leave_halfHour);
                        //duration = 11M;
                        if (duration >= 3 && duration < 7.5M) //单天请假三小时
                        {
                            mealDeduction = 10; //餐补扣款

                        }
                        else if (duration >= 7.5M) //多天计算
                        {
                            decimal leave_halfHour1 = Convert.ToDecimal(duration) / Convert.ToDecimal(0.5);


                            decimal leaveDays = duration / 7.5M;
                            if (leaveDays % 1 == 0)
                            {
                                typeDeduction = ConvertToDecimal(personalkLeave_dailywage_day * leaveDays);
                                mealDeduction = 10 * leaveDays; //餐补扣款
                            }
                            else
                            {
                                typeDeduction = personalkLeave_dailywage_day * Convert.ToInt32(leaveDays);
                                decimal sy_shijiaunit = leave_halfHour1 - Convert.ToDecimal(15.00M * Convert.ToInt32(leaveDays));
                                if (sy_shijiaunit > 0)
                                {
                                    typeDeduction += ConvertToDecimal(personalkLeave_dailywage_halfhour * sy_shijiaunit);
                                }
                                mealDeduction = 10 * Convert.ToInt32(leaveDays);

                                //得到最后一天的请假时间 是否有餐补
                                int lastHours = (Convert.ToDateTime(endTime) - Convert.ToDateTime("09:00")).Hours;
                                if (lastHours >= 3)
                                {
                                    mealDeduction += 10; //餐补扣款
                                }
                            }
                        }
                    }

                    break;
                case 3: //3病假
                        // 病假日薪 *计算方式:日平均工资 = 成都市最低工资标准的80% /当月应出勤天数。 短期病假=当月15天内 
                    decimal chengDuMinimumWage_Day = _chengDuMinimumWage / work_days;
                    decimal chengDuMinimumWage_halrHour = chengDuMinimumWage_Day / 7.50M;
                    decimal sickLeave_dailywage_halfhour_deduction1 = (personalkLeave_dailywage_day / 7.50M) - chengDuMinimumWage_halrHour; //病假单位 0.5小时 扣款金额

                    if (date_Range_type == "halfday")
                    {
                        mealDeduction = 10.00M * Math.Ceiling(duration); //餐补扣款 

                        decimal pl_dailywage_day = personalkLeave_dailywage_day - chengDuMinimumWage_Day;
                        if (duration % 1 == 0) //整天
                        {
                            typeDeduction = ConvertToDecimal(pl_dailywage_day * duration);
                        }
                        else //多含 半天 另外处理
                        {
                            #region 处理当天是否扣除餐补
                            string formatDt_begin = startTime.ToString("yyyy-MM-dd");
                            List<LeaveDetails> leaveDetails1 = leaveDetails.Where(it => it.IsDeduction && it.EndDt.ToString("yyyy-MM-dd") == formatDt_begin).ToList();
                            if (leaveDetails1.Count > 0) mealDeduction = 10.00M * Math.Floor(duration); //餐补扣款 
                            else mealDeduction = 10.00M * Math.Ceiling(duration); //餐补扣款 
                            #endregion

                            if (duration % 1 > 0)
                            {
                                typeDeduction = (pl_dailywage_day / 2.00M) * (duration / 0.50M); ;

                            }
                            else
                            {
                                typeDeduction = (pl_dailywage_day / 2.00M);
                            }

                            typeDeduction = ConvertToDecimal(typeDeduction);
                        }
                    }
                    else if (date_Range_type == "hour")
                    {
                        decimal sickLeave_halfHour = duration / 0.5M;
                        typeDeduction = ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * sickLeave_halfHour);

                        if (duration >= 3 && duration < 7.5M) //单天请假三小时 && 请假时间在上午 则没有餐补
                        {
                            mealDeduction = 10; //餐补扣款
                        }
                        else if (duration >= 7.5M) //多天计算
                        {
                            decimal sickLeave_halfHour1 = duration / 0.5M;

                            decimal leaveDays = Convert.ToDecimal(duration / 7.5M);

                            typeDeduction = ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * sickLeave_halfHour1);
                            if (leaveDays % 1 == 0)
                            {
                                mealDeduction = 10 * leaveDays; //餐补扣款
                            }
                            else
                            {
                                mealDeduction = 10 * Convert.ToInt32(leaveDays);

                                typeDeduction = ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * Convert.ToInt32(leaveDays));

                                decimal sy_bingjiaunit = sickLeave_halfHour1 - Convert.ToDecimal(15.00M * Convert.ToInt32(leaveDays));
                                if (sy_bingjiaunit > 0)
                                {
                                    typeDeduction += ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * sy_bingjiaunit);
                                }

                                //得到最后一天的请假时间 是否有餐补
                                int lastHours = (Convert.ToDateTime(endTime) - Convert.ToDateTime("09:00")).Hours;
                                if (lastHours >= 3)
                                {
                                    mealDeduction += 10; //餐补扣款
                                }
                            }
                        }
                    }
                    break;
                case 4: //4调休假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 5: //5婚假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 6: //6产假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 7: //7陪产假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 8: //8其他
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 9: //9丧假
                    if (date_Range_type == "halfday")
                    {
                        if (duration >= 0.5M && duration <= 1M) //一天
                        {
                            var njItem = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd") == startTime.ToString("yyyy-MM-dd") &&
                                                      it.EndDt.ToString("yyyy-MM-dd") == endTime.ToString("yyyy-MM-dd")).ToList();
                            if (njItem.Count > 1)
                            {
                                if (njItem[0].StartDt == startTime)
                                {
                                    mealDeduction = 10; //餐补扣款
                                }
                            }
                            else
                            {
                                mealDeduction = 10; //餐补扣款 
                            }
                        }
                        else // 多天
                        {
                            var njManyDaysItem = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd") == startTime.ToString("yyyy-MM-dd")).ToList();
                            if (njManyDaysItem.Count > 1)
                            {
                                var njManyDaysItem1 = njManyDaysItem.Where(it => it.StartDt != startTime).ToList();
                                if (njManyDaysItem1.Count > 0)
                                {
                                    if (njManyDaysItem1[0].Unit.Equals("天"))
                                    {
                                        mealDeduction = 10 * Math.Floor(duration);
                                    }
                                    else if (njManyDaysItem1[0].Unit.Equals("小时") && njManyDaysItem1[0].New_Duration >= 3)
                                    {
                                        mealDeduction = 10 * Math.Floor(duration);
                                    }
                                    else
                                    {
                                        mealDeduction = 10 * Math.Ceiling(duration);
                                    }
                                }
                            }
                            else
                            {
                                mealDeduction = 10 * Math.Ceiling(duration);
                            }
                        }
                    }
                    break;
            }
        }


        /// <summary>
        /// 计算类型费用
        /// 病假 事假 计算 按小时计算
        /// </summary>
        /// <param name="leaveDetails"></param>
        /// <param name="leaveType">1年假;2事假;3病假;4调休假;5婚假;6产假;7陪产假;8其他;9丧假</param>
        /// <param name="date_Range_type"> halfday 全天  hour  小时</param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="amountPayable"></param>
        /// <param name="work_days"></param>
        /// <param name="duration"></param>
        /// <param name="mealDeduction"></param>
        /// <param name="typeDeduction"></param>
        public static void CalculateTypeFee2(List<LeaveDetails> leaveDetails, int leaveType, string date_Range_type, DateTime startTime, DateTime endTime,
            decimal amountPayable, int work_days, decimal duration, out decimal mealDeduction, out decimal typeDeduction)
        {
            typeDeduction = 0;
            mealDeduction = 0;

            //string am_starttime = "08:59";
            //string am_endtime = "13:01";

            decimal personalkLeave_dailywage_day = amountPayable / work_days; //日薪 = 事假日薪 *计算方式:日平均工资 = 当月应发工资 /当月应出勤天数。

            //半小时单位
            //decimal halfHour = 7.50M / 0.50M;

            switch (leaveType)
            {
                case 1: //年假

                    if (date_Range_type == "halfday")
                    {
                        if (duration >= 0.5M && duration <= 1M) //一天
                        {
                            var njItem = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd") == startTime.ToString("yyyy-MM-dd") &&
                                                      it.EndDt.ToString("yyyy-MM-dd") == endTime.ToString("yyyy-MM-dd")).ToList();
                            if (njItem.Count > 1)
                            {
                                if (njItem[0].StartDt == startTime)
                                {
                                    mealDeduction = 10; //餐补扣款
                                }
                            }
                            else
                            {
                                mealDeduction = 10; //餐补扣款 
                            }
                        }
                        else // 多天
                        {
                            var njManyDaysItem = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd") == startTime.ToString("yyyy-MM-dd")).ToList();
                            if (njManyDaysItem.Count > 1)
                            {
                                var njManyDaysItem1 = njManyDaysItem.Where(it => it.StartDt != startTime).ToList();
                                if (njManyDaysItem1.Count > 0)
                                {
                                    if (njManyDaysItem1[0].Unit.Equals("天"))
                                    {
                                        mealDeduction = 10 * Math.Floor(duration);
                                    }
                                    else if (njManyDaysItem1[0].Unit.Equals("小时") && njManyDaysItem1[0].New_Duration >= 3)
                                    {
                                        mealDeduction = 10 * Math.Floor(duration);
                                    }
                                    else
                                    {
                                        mealDeduction = 10 * Math.Ceiling(duration);
                                    }
                                }
                            }
                            else
                            {
                                mealDeduction = 10 * Math.Ceiling(duration);
                            }
                        }
                    }

                    break;
                case 2: //2事假
                    // 事假日薪 *计算方式:日平均工资 = 当月应发工资 /当月应出勤天数。 
                    decimal personalkLeave_dailywage_halfhour = personalkLeave_dailywage_day / 7.50M; //事假单位 0.5小时

                    if (date_Range_type == "halfday")
                    {
                        mealDeduction = 10.00M * Math.Floor(duration); //餐补扣款 
                        if (duration % 1 == 0) //整天
                        {
                            typeDeduction = ConvertToDecimal(personalkLeave_dailywage_day * duration);
                        }
                        else //多含 半天 另外处理
                        {
                            decimal sj_wholeDay = Math.Floor(duration); //整天
                            decimal sj_halfDay = duration % 1; //半天

                            if (sj_halfDay > 0)
                            {
                                LeaveDetails sjDetails = leaveDetails.Where(it => it.StartDt == startTime && it.EndDt == endTime).FirstOrDefault();
                                //decimal sjPrice = 0.00M;
                                if (sjDetails != null)
                                {
                                    Slice_info sj_slice_Info = sjDetails.SliceInfo;
                                    if (sj_slice_Info != null)
                                    {
                                        decimal sjLongTime = (sj_slice_Info.duration / 3600.00M);
                                        typeDeduction = (personalkLeave_dailywage_day / 7.50M) * sjLongTime;
                                    }
                                }

                                LeaveDetails sjDetailsMeal = leaveDetails.Where(it => it.EndDt == startTime).FirstOrDefault();
                                if (sjDetailsMeal == null)
                                {
                                    mealDeduction += 10.00M;
                                }
                            }
                            else
                            {
                                typeDeduction = personalkLeave_dailywage_day * sj_wholeDay;
                            }
                            typeDeduction = ConvertToDecimal(typeDeduction);
                        }
                    }
                    else if (date_Range_type == "hour")
                    {

                        decimal leave_halfHour = Convert.ToDecimal(duration) / Convert.ToDecimal(0.5);
                        typeDeduction = ConvertToDecimal(personalkLeave_dailywage_halfhour * leave_halfHour);
                        //duration = 11M;
                        if (duration >= 3 && duration < 7.5M) //单天请假三小时
                        {
                            mealDeduction = 10; //餐补扣款

                        }
                        else if (duration >= 7.5M) //多天计算
                        {
                            decimal leave_halfHour1 = Convert.ToDecimal(duration) / Convert.ToDecimal(0.5);


                            decimal leaveDays = duration / 7.5M;
                            if (leaveDays % 1 == 0)
                            {
                                typeDeduction = ConvertToDecimal(personalkLeave_dailywage_day * leaveDays);
                                mealDeduction = 10 * leaveDays; //餐补扣款
                            }
                            else
                            {
                                typeDeduction = personalkLeave_dailywage_day * Convert.ToInt32(leaveDays);
                                decimal sy_shijiaunit = leave_halfHour1 - Convert.ToDecimal(15.00M * Convert.ToInt32(leaveDays));
                                if (sy_shijiaunit > 0)
                                {
                                    typeDeduction += ConvertToDecimal(personalkLeave_dailywage_halfhour * sy_shijiaunit);
                                }
                                mealDeduction = 10 * Convert.ToInt32(leaveDays);

                                //得到最后一天的请假时间 是否有餐补
                                int lastHours = (Convert.ToDateTime(endTime) - Convert.ToDateTime("09:00")).Hours;
                                if (lastHours >= 3)
                                {
                                    mealDeduction += 10; //餐补扣款
                                }
                            }
                        }
                    }

                    break;
                case 3: //3病假
                        // 病假日薪 *计算方式:日平均工资 = 成都市最低工资标准的80% /当月应出勤天数。 短期病假=当月15天内 
                    decimal chengDuMinimumWage_Day = _chengDuMinimumWage / work_days;
                    decimal chengDuMinimumWage_halrHour = chengDuMinimumWage_Day / 7.50M;
                    decimal sickLeave_dailywage_halfhour_deduction1 = (personalkLeave_dailywage_day / 7.50M) - chengDuMinimumWage_halrHour; //病假单位 0.5小时 扣款金额

                    if (date_Range_type == "halfday")
                    {
                        mealDeduction = 10.00M * Math.Ceiling(duration); //餐补扣款 

                        decimal pl_dailywage_day = personalkLeave_dailywage_day - chengDuMinimumWage_Day;
                        if (duration % 1 == 0) //整天
                        {
                            typeDeduction = ConvertToDecimal(pl_dailywage_day * duration);
                        }
                        else //多含 半天 另外处理
                        {
                            decimal bj_wholeDay = Math.Floor(duration); //整天
                            decimal bj_halfDay = duration % 1; //半天
                            decimal bj_wholeDayWage = pl_dailywage_day * bj_wholeDay;
                            decimal bj_halfDayWage = 0.00M;
                            if (bj_halfDay > 0)
                            {
                                LeaveDetails bjDetails = leaveDetails.Where(it => it.StartDt == startTime && it.EndDt == endTime).FirstOrDefault();

                                //decimal bjPrice = 0.00M;
                                if (bjDetails != null)
                                {
                                    Slice_info bj_slice_Info = bjDetails.SliceInfo;
                                    decimal bjLongTime = bj_slice_Info.duration / 3600.00M;
                                    if (bjLongTime == 3.00M)
                                    {
                                        bj_halfDayWage = (pl_dailywage_day / 7.50M) * 3.00M;
                                    }
                                    else if (bjLongTime == 4.50M)
                                    {
                                        bj_halfDayWage = (pl_dailywage_day / 7.50M) * 4.50M;
                                    }
                                }
                            }

                            typeDeduction = ConvertToDecimal(bj_wholeDayWage + bj_halfDayWage);
                        }
                    }
                    else if (date_Range_type == "hour")
                    {
                        decimal sickLeave_halfHour = duration / 0.5M;
                        typeDeduction = ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * sickLeave_halfHour);

                        if (duration >= 3 && duration < 7.5M) //单天请假三小时 && 请假时间在上午 则没有餐补
                        {
                            mealDeduction = 10; //餐补扣款
                        }
                        else if (duration >= 7.5M) //多天计算
                        {
                            decimal sickLeave_halfHour1 = duration / 0.5M;

                            decimal leaveDays = Convert.ToDecimal(duration / 7.5M);

                            typeDeduction = ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * sickLeave_halfHour1);
                            if (leaveDays % 1 == 0)
                            {
                                mealDeduction = 10 * leaveDays; //餐补扣款
                            }
                            else
                            {
                                mealDeduction = 10 * Convert.ToInt32(leaveDays);

                                typeDeduction = ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * Convert.ToInt32(leaveDays));

                                decimal sy_bingjiaunit = sickLeave_halfHour1 - Convert.ToDecimal(15.00M * Convert.ToInt32(leaveDays));
                                if (sy_bingjiaunit > 0)
                                {
                                    typeDeduction += ConvertToDecimal(sickLeave_dailywage_halfhour_deduction1 * sy_bingjiaunit);
                                }

                                //得到最后一天的请假时间 是否有餐补
                                int lastHours = (Convert.ToDateTime(endTime) - Convert.ToDateTime("09:00")).Hours;
                                if (lastHours >= 3)
                                {
                                    mealDeduction += 10; //餐补扣款
                                }
                            }
                        }
                    }
                    break;
                case 4: //4调休假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 5: //5婚假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 6: //6产假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 7: //7陪产假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 8: //8其他
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;
                case 9: //9丧假
                    CalculateTypeFeeSub(leaveDetails, date_Range_type, startTime, endTime, duration, out mealDeduction);
                    break;

            }
        }

        /// <summary>
        /// 计算类型费用
        /// </summary>
        /// <param name="leaveDetails"></param>
        /// <param name="date_Range_type"></param>
        /// <param name="startTime1"></param>
        /// <param name="endTime1"></param>
        /// <param name="duration"></param>
        /// <param name="mealDeduction"></param>
        public static void CalculateTypeFeeSub(List<LeaveDetails> leaveDetails, string date_Range_type, DateTime startTime1, DateTime endTime1,
            decimal duration, out decimal mealDeduction)
        {
            mealDeduction = 0;
            //string am_starttime = "09:00";
            //string am_endtime = "11:59";

            string startTime = startTime1.ToString("HH:mm:ss");
            string endTime = endTime1.ToString("HH:mm:ss");

            if (date_Range_type == "halfday")
            {
                mealDeduction = Math.Ceiling(duration) * 10; //餐补扣款 
            }
            else if (date_Range_type == "hour")
            {
                List<LeaveDetails> leaveDetails1 = new List<LeaveDetails>();
                leaveDetails1 = leaveDetails.Where(it => it.StartDt.ToString("yyyy-MM-dd").Equals(startTime1.ToString("yyyy-MM-dd")))
                                .OrderBy(it => it.StartDt).ToList();
                if (leaveDetails1.Count > 1)
                {
                    decimal timelenTatoal = leaveDetails1.Sum(it => it.New_Duration);
                    if (timelenTatoal >= 3.00M)
                    {
                        if (leaveDetails1[0].StartDt == startTime1)
                        {
                            mealDeduction = 10; //餐补扣款
                        }
                    }

                }
                else
                {
                    if (duration >= 3 && duration < 7) //单天请假三小时 && 请假时间在上午 则没有餐补
                    {
                        mealDeduction = 10; //餐补扣款
                    }
                    else if (duration >= 7 && duration <= 7.50M)
                    {
                        mealDeduction = 10; //餐补扣款
                    }
                    else if (duration >= 7.50M) //多天计算
                    {
                        decimal leaveDays = Convert.ToDecimal(duration / 7.50M);

                        if (leaveDays % 1 == 0)
                        {
                            mealDeduction = 10 * leaveDays; //餐补扣款
                        }
                        else
                        {
                            mealDeduction = 10 * Convert.ToInt32(leaveDays);

                            //得到最后一天的请假时间 是否有餐补
                            int lastHours = (Convert.ToDateTime(endTime) - Convert.ToDateTime("09:00")).Hours;
                            if (lastHours >= 3)
                            {
                                mealDeduction += 10; //餐补扣款

                                ////处理结束时间
                                //if (endTime.CompareTo(am_starttime) > 0 && endTime.CompareTo(am_endtime) < 0)
                                //{
                                //    mealDeduction += 10; //餐补扣款
                                //}
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取打卡补卡类型
        /// </summary>
        /// <param name="template_id"></param>
        /// <returns></returns>
        public static async Task<List<VacationLeaveTypeView>> GetVacationReissueCardTypes(string template_id)
        {
            List<VacationLeaveTypeView> vacationLeaveTypes = new List<VacationLeaveTypeView>();

            TemplateDetailView templateDetailView = new TemplateDetailView();
            templateDetailView = await _qiYeWeChatApiService.GetTemplateDetailAsync(template_id);
            if (templateDetailView.errcode != 0)
            {
                return vacationLeaveTypes;
            }
            List<VacationItemInfo> VacationItemInfos = templateDetailView.vacation_list.item;

            foreach (var item in VacationItemInfos)
            {
                ValueItem valueInfo = item.name.Where(it => it.lang == "zh_CN").FirstOrDefault();
                if (valueInfo != null)
                {
                    vacationLeaveTypes.Add(
                    new VacationLeaveTypeView()
                    {
                        id = item.id,
                        name = valueInfo.text
                    });
                }
            }

            return vacationLeaveTypes;
        }

        /// <summary>
        /// 打卡数据
        /// 假勤数据 统计
        /// </summary>
        /// <param name="datas">数据源</param>
        /// <param name="type">
        /// 1-请假;2-补卡;3-出差;4-外出;100-外勤;
        /// </param>
        /// <param name="subTypeName">
        /// 年假 事假 病假 调休假 婚嫁 产假  陪产假 丧假 补卡次数 出差 外出数 外勤 其他
        /// </param>
        /// <returns></returns>
        private static int Fallibilitydispose(List<Sp_Item> datas, int type, string? subTypeName)
        {
            int num = 0;

            Sp_Item _Info = datas.Where(it => it.type == type && it.name == subTypeName).FirstOrDefault();
            if (_Info != null) { num = _Info.count; }

            return num;
        }

        /// <summary>
        /// 打卡数据
        /// 异常数据 统计
        /// </summary>
        /// <returns></returns>
        private static int ExceptionStatistics(List<Exception_Info> datas, int type)
        {
            int num = 0;

            Exception_Info _Info = datas.Where(it => it.exception == type).FirstOrDefault();
            if (_Info != null) { num = _Info.count; }

            return num;
        }

        /// <summary>
        /// 获取时间段内除周末 节假日外的 工作日
        /// </summary>
        /// <param name="yearMonth"></param>
        /// <returns></returns>
        public static async Task<int> GetWorkDays(string yearMonth)
        {
            int workdays = 0;
            string sql = string.Format(@"Select * From  Pm_WageIssueWorkingDay 
                                         Where Isdel = 0 And YearMonth = '{0}' ", yearMonth);

            var data = await _usersRep._sqlSugar.SqlQueryable<WageYearMonthView>(sql).FirstAsync();

            if (data != null)
            {
                workdays = data.Workdays;
            }

            return workdays;
        }

        /// <summary>
        /// 获取一个类指定的属性值
        /// </summary>
        /// <param name="info">object对象</param>
        /// <param name="field">属性名称</param>
        /// <returns></returns>
        public static object GetPropertyValue(object info, string field)
        {
            if (info == null) return null;
            System.Type t = info.GetType();
            IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
            return property.First().GetValue(info, null);
        }
    }
}