using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Edu.AOP;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.User;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class UserCenterController : BaseController
    {
        /// <summary>
        /// 助教处理类对象
        /// </summary>
        private readonly NoticeModule noticeModule = new NoticeModule();
        /// <summary>
        /// 考勤处理类
        /// </summary>
        private readonly AttendanceModule attendancemodule = new AttendanceModule();
        /// <summary>
        /// 审核处理
        /// </summary>
        private readonly WorkFlowModule workFlowModule = new WorkFlowModule();
        /// <summary>
        /// 考勤记录处理类
        /// </summary>
        public AttendanceRecodModule attendRecodeModule = new AttendanceRecodModule();



        #region 公告管理

        /// <summary>
        /// 获取公告基础信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoticeBaseInfo()
        {
            var Robj = noticeModule.GetNoticeBaseInfo(base.UserInfo.Group_Id);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 新增修改公告基础
        /// </summary>
        /// <returns></returns>
        public ApiResult SetNoticeBaseInfo() {
            var demodel = JsonHelper.DeserializeObject<RB_Notice_Base_ViewModel>(RequestParm.Msg.ToString());
            demodel.Group_Id = base.UserInfo.Group_Id;
            demodel.School_Id = base.UserInfo.School_Id;
            demodel.CreateBy = base.UserInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = base.UserInfo.Id;
            demodel.UpdateTime = DateTime.Now;

            string msg = noticeModule.SetNoticeBaseInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoticeRuleEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(NoticeRuleEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }


        /// <summary>
        /// 获取公告分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoticePageList()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = JsonHelper.DeserializeObject<RB_Notice_ViewModel>(RequestParm.Msg.ToString());
            query.Group_Id = base.UserInfo.Group_Id;
            var list = noticeModule.GetNoticePageList(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.Count = rowsCount;
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.From,
                x.Number,
                x.Title,
                x.NoticeState,
                NoticeStateName = x.NoticeState.ToName(),
                x.Is_Top,
                x.ReadNum,
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.HasValue ? x.UpdateTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取公告信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoticeInfo() {
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int NoticeId = parms.GetInt("NoticeId", 0);
            if (NoticeId <= 0) {
                return ApiResult.ParamIsNull("请传递公告id");
            }

            return noticeModule.GetNoticeInfo(NoticeId);
        }

        /// <summary>
        /// 新增修改公告
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetNoticeInfo()
        {
            UserInfo userInfo = base.UserInfo;
            RB_Notice_ViewModel demodel = JsonHelper.DeserializeObject<RB_Notice_ViewModel>(RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(demodel.From))
            {
                return ApiResult.ParamIsNull("请传递来源");
            }
            if (string.IsNullOrEmpty(demodel.To))
            {
                return ApiResult.ParamIsNull("请传递发送部门");
            }
            if (string.IsNullOrEmpty(demodel.CopyPeople))
            {
                return ApiResult.ParamIsNull("请选择抄送人");
            }
            if (string.IsNullOrEmpty(demodel.Title))
            {
                return ApiResult.ParamIsNull("请输入标题");
            }
            demodel.FileList ??= new List<Model.Public.FileModel>();
            demodel.File = JsonHelper.Serialize(demodel.FileList.Select(x => new { x.FileName, x.FileUrl }));
            if (demodel.NoticeState != NoticeStateEnum.Publish && demodel.NoticeState != NoticeStateEnum.Draft)
            {
                return ApiResult.ParamIsNull("公告状态不正确");
            }
            demodel.Is_Top = demodel.Is_Top == 0 ? 2 : demodel.Is_Top;
            demodel.Status = Common.Enum.DateStateEnum.Normal;
            demodel.Group_Id = userInfo.Group_Id;
            demodel.School_Id = userInfo.School_Id;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            bool flag = noticeModule.SetNoticeInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 公告操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetNoticeOperation() {
            UserInfo userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int NoticeId = parms.GetInt("NoticeId", 0);
            int Type = parms.GetInt("Type", 1);// 类型 1置顶  2取消置顶  3撤回  4删除   5公告阅读
            if (NoticeId <= 0) {
                return ApiResult.ParamIsNull("公告id");
            }

            bool flag = noticeModule.SetNoticeOperation(NoticeId, Type, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoticeStateEnumList() {
            var list = EnumHelper.EnumToList(typeof(NoticeStateEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }

        /// <summary>
        /// 获取我的公告分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyNoticePageList()
        {
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = JsonHelper.DeserializeObject<RB_Notice_ViewModel>(RequestParm.Msg.ToString());
            query.Group_Id = base.UserInfo.Group_Id;
            query.DeptId = base.UserInfo.DeptId;
            var list = noticeModule.GetMyNoticePageList(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            pageModel.Count = rowsCount;
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.From,
                x.Number,
                x.Title,
                x.NoticeState,
                NoticeStateName = x.NoticeState.ToName(),
                x.Is_Top,
                x.ReadNum,
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.HasValue ? x.UpdateTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pageModel);
        }


        #endregion

        #region 考勤管理

        /// <summary>
        /// 考勤管理  分页列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetAttendancePageList()
        {
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            RB_Attendance_Extend demodel = JsonConvert.DeserializeObject<RB_Attendance_Extend>(RequestParm.Msg.ToString());
            List<RB_Attendance_Extend> data = attendancemodule.GetPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count, userInfo.Group_Id);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new { x.Id, x.RB_BranchId, x.IsBind, x.BranchName, x.UpdateName, x.UpdateTime, x.AttendanceDate, x.PeopleNum }).ToList();
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 根据主键id获取数据
        /// </summary>        
        /// <returns></returns>
        public virtual ApiResult GetAttendanceInfo()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int attendanceID = parm.GetInt("attendanceId");
            RB_Attendance_Extend dmodel = attendancemodule.Get(attendanceID);
            if (dmodel != null)
            {
                var Rmodel = new
                {
                    dmodel.Id,
                    dmodel.RB_BranchId,
                    dmodel.RB_GroupId,
                    dmodel.AwList,
                    dmodel.AwWifiList,
                    dmodel.NottdList,
                    dmodel.WdList,
                    dmodel.TdList
                };
                return ApiResult.Success("请求成功！", Rmodel);
            }
            return ApiResult.Failed("参数错误!");
        }

        /// <summary>
        /// 新增和修改
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult SetAttendanceInfo()
        {
            var userInfo = base.UserInfo;
            RB_Attendance_Extend demodel = JsonConvert.DeserializeObject<RB_Attendance_Extend>(RequestParm.Msg.ToString());
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            int attendanceId = pram.GetInt("attendanceId", 0);
            int Status = pram.GetInt("Status", 0);
            if (attendancemodule.ValidateName(attendanceId, userInfo.Group_Id, demodel.RB_BranchId))
            {
                return ApiResult.Failed("该校区已存在考勤，无法再次添加！");
            }
            foreach (var item in demodel.WdList)
            {
                if (string.IsNullOrWhiteSpace(item.Workday))
                {
                    return ApiResult.ParamIsNull("工作日设置有误，请核实后再试！");
                }
                if (string.IsNullOrWhiteSpace(item.BeOnDutyTime))
                {
                    return ApiResult.ParamIsNull("工作日上班时间设置有误，请核实后再试！");
                }
                if (string.IsNullOrWhiteSpace(item.OffDutyTime))
                {
                    return ApiResult.ParamIsNull("工作日下班时间设置有误，请核实后再试！");
                }
            }
            var tdlist = demodel.TdList;
            int allCount = 0;
            foreach (var item in tdlist.GroupBy(x => x.Date))
            {
                if (demodel.TdList.Where(x => x.Date == item.Key).ToList().Count() > 1)
                {
                    allCount = demodel.TdList.Where(x => x.Date == item.Key && x.RB_Department_Id == 0 && x.EmployeeId == 0).ToList().Count();//全部打卡
                    if (allCount > 1)
                    {//有两条这种数据
                        return ApiResult.Failed("特殊日期考勤:" + Convert.ToDateTime(item.Key).ToString("yyyy-MM-dd") + "重复！");
                    }
                    foreach (var itemDepartment in demodel.TdList.Where(x => x.Date == item.Key && x.RB_Department_Id > 0).GroupBy(x => x.RB_Department_Id))
                    {
                        int departmentCount = demodel.TdList.Where(x => x.Date == item.Key && x.RB_Department_Id == itemDepartment.Key && x.EmployeeId == 0).ToList().Count();//部门打卡
                        if (departmentCount > 1)
                        {//有两条这种数据
                            return ApiResult.Failed("特殊日期考勤:" + Convert.ToDateTime(item.Key).ToString("yyyy-MM-dd") + "重复！");
                        }

                        foreach (var itemEmployee in demodel.TdList.Where(x => x.Date == item.Key && x.EmployeeId > 0).GroupBy(x => x.EmployeeId))
                        {
                            departmentCount = demodel.TdList.Where(x => x.Date == item.Key && x.RB_Department_Id == itemDepartment.Key && x.EmployeeId == itemEmployee.Key).ToList().Count();//部门打卡
                            if (departmentCount > 1)
                            {//有两条这种数据
                                return ApiResult.Failed("特殊日期考勤:" + Convert.ToDateTime(item.Key).ToString("yyyy-MM-dd") + "重复！");
                            }
                        }
                    }
                }

            }
            if (demodel.NottdList.Count != demodel.NottdList.Distinct().Count())
            {
                return ApiResult.Failed("特殊日期有重复，请核实后再试");
            }
            //验证日期是否有重复
            int Count = 0;
            foreach (var item in tdlist)
            {
                Count = demodel.NottdList.Where(x => x.Date == item.Date).ToList().Count();
                if (Count > 0)
                {//有两条这种数据
                    return ApiResult.Failed("特殊日期考勤:" + Convert.ToDateTime(item.Date).ToString("yyyy-MM-dd") + "重复！");
                }
            }




            bool flag = attendancemodule.Set(attendanceId, Status, demodel.RB_BranchId, demodel.WdList, demodel.TdList, demodel.NottdList, demodel.AwList, demodel.AwWifiList, userInfo.Id, userInfo.Group_Id);
            if (flag)
                return ApiResult.Success();
            else
                return ApiResult.Failed("请求失败！");
        }

        /// <summary>
        /// 获取每日打卡记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetEveryDayAttendanceRecordList()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            var userInfo = base.UserInfo;

            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                return ApiResult.ParamIsNull("起始时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(StartTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("起始时间格式不正确！");
                }
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull("结束时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(EndTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("结束时间格式不正确！");
                }
            }
            var data = attendancemodule.GetEveryDayAttendanceRecordList(pmodel.PageIndex, pmodel.PageSize, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.EmployeeId,
                x.EmName,
                x.DepartmentName,
                x.PostName,
                x.DateStr,
                BeOnDutyTime = x.BeOnDutyTime == null ? "" : x.BeOnDutyTime.Value.ToString("HH:mm"),
                OffDutyTime = x.OffDutyTime == null ? "" : x.OffDutyTime.Value.ToString("HH:mm"),
                x.BeOnStatus,
                BeOnResult = EnumHelper.ToName(x.BeOnStatus),
                x.OffStatus,
                OffResult = EnumHelper.ToName(x.OffStatus),
                x.BeOnRelevance,
                x.BeOnRelevanceType,
                x.OffRelevance,
                x.OffRelevanceType
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取原始记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetOriginalRecordList()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                return ApiResult.ParamIsNull("起始时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(StartTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("起始时间格式不正确！");
                }
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull("结束时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(EndTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("结束时间格式不正确！");
                }
            }
            var data = attendancemodule.GetOriginalRecordList(pmodel.PageIndex, pmodel.PageSize, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.EmployeeId,
                x.EmName,
                x.DepartmentName,
                x.PostName,
                x.DateStr,
                x.BeOnTime,
                BeOnDutyTime = x.BeOnDutyTime == null ? "" : x.BeOnDutyTime.Value.ToString("HH:mm"),
                x.BeOnStatus,
                BeOnResult = EnumHelper.ToName(x.BeOnStatus),
                x.BeOnAddress,
                x.OffTime,
                OffDutyTime = x.OffDutyTime == null ? "" : x.OffDutyTime.Value.ToString("HH:mm"),
                x.OffStatus,
                OffResult = EnumHelper.ToName(x.OffStatus),
                OffAddress = x.OffAddress ?? "",
                x.PhoneName
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取打卡时间
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetClockTimeRecordList()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                return ApiResult.ParamIsNull("起始时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(StartTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("起始时间格式不正确！");
                }
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull("结束时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(EndTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("结束时间格式不正确！");
                }
            }
            var EmData = attendancemodule.GetClockTimeEmployeeList(StartTime, EndTime, pmodel.PageIndex, pmodel.PageSize, out long count, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            List<int> EmployeeList = EmData.Select(x => x.EmployeeId).Distinct().OrderByDescending(x => x).ToList();
            string EmIdStr = string.Join(",", EmployeeList);
            var data = attendancemodule.GetClockTimeRecordList(StartTime, EndTime, EmployeeId, BranchId, DepartmentId, EmIdStr, userInfo.Group_Id);
            //声明一个DataTable 动态添加每日打卡时间
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("EmName", typeof(string));
            Rdt.Columns.Add("DepartmentName", typeof(string));
            Rdt.Columns.Add("EmployeeId", typeof(string));
            Rdt.Columns.Add("PostName", typeof(string));
            string STime = StartTime;
            List<string> MonthList = new List<string>();
            while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
            {
                Rdt.Columns.Add(STime, typeof(string));
                MonthList.Add(STime);
                STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
            }
            Rdt.AcceptChanges();

            //遍历出所有的人  根据人再去找到对应的每天的打卡时间
            string TimeStr = "";
            foreach (var item in EmData)
            {
                var EmRecordList = data.Where(x => x.EmployeeId == item.EmployeeId).ToList();
                DataRow Rdr = Rdt.NewRow();
                Rdr["EmName"] = item.EmName;
                Rdr["DepartmentName"] = item.DepartmentName;
                Rdr["EmployeeId"] = item.EmployeeId;
                Rdr["PostName"] = item.PostName;
                if (EmRecordList.Count > 0)
                {
                    STime = StartTime;
                    while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
                    {
                        var EmTime = EmRecordList.Where(x => x.DateStr == STime).FirstOrDefault();
                        if (EmTime != null)
                        {
                            TimeStr = "";
                            if (EmTime.BeOnStatus == AttendanceEnum.ZC || EmTime.BeOnStatus == AttendanceEnum.CD)
                            {
                                TimeStr = "上班：" + EmTime.BeOnDutyTime.Value.ToString("HH:mm:ss");
                            }
                            if (EmTime.OffStatus == AttendanceEnum.ZC || EmTime.OffStatus == AttendanceEnum.CD)
                            {
                                if (TimeStr != "")
                                    TimeStr += "<br/>下班：" + EmTime.OffDutyTime.Value.ToString("HH:mm:ss");
                                else
                                    TimeStr += "下班：" + EmTime.OffDutyTime.Value.ToString("HH:mm:ss");
                            }
                            Rdr[STime] = TimeStr;
                        }
                        else
                        {
                            Rdr[STime] = "";
                        }
                        STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
                    }
                }
                Rdt.Rows.Add(Rdr);
            }

            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = Rdt;

            return ApiResult.Success("", new { pmodel.Count, pmodel.PageCount, pmodel.PageData, pmodel.PageIndex, pmodel.PageSize, columnData = MonthList });
        }

        /// <summary>
        /// 获取每月打卡统计
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetMonthRecordList()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            var userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            string MonthTime = pram.GetStringValue("MonthTime");
            if (string.IsNullOrWhiteSpace(MonthTime))
            {
                return ApiResult.ParamIsNull("月份时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(MonthTime + "-01");
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("分月时间格式不正确！");
                }
            }
            string StartTime = MonthTime + "-01";
            string EndTime = Convert.ToDateTime(MonthTime + "-01").AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            var EmData = attendancemodule.GetMonthRecordList(pmodel.PageIndex, pmodel.PageSize, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            List<int> EmployeeList = EmData.Select(x => x.EmployeeId).Distinct().OrderByDescending(x => x).ToList();
            string EmIdStr = string.Join(",", EmployeeList);
            var data = attendancemodule.GetClockTimeRecordList(StartTime, EndTime, EmployeeId, BranchId, DepartmentId, EmIdStr, userInfo.Group_Id, 0);
            //声明一个DataTable 动态添加每日打卡时间
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("EmName", typeof(string));
            Rdt.Columns.Add("DepartmentName", typeof(string));
            Rdt.Columns.Add("EmployeeId", typeof(string));
            Rdt.Columns.Add("PostName", typeof(string));
            Rdt.Columns.Add("CQDay", typeof(string));
            Rdt.Columns.Add("XXDay", typeof(string));
            Rdt.Columns.Add("CDNum", typeof(string));
            Rdt.Columns.Add("CDTime", typeof(string));
            Rdt.Columns.Add("SBQK", typeof(string));
            Rdt.Columns.Add("XBQK", typeof(string));
            Rdt.Columns.Add("QGDay", typeof(string));

            Rdt.Columns.Add("AffairLeave", typeof(string));//事假
            Rdt.Columns.Add("AnnualLeave", typeof(string));//年假
            Rdt.Columns.Add("SickLeave", typeof(string));//病假
            Rdt.Columns.Add("AffairLeaveForDay", typeof(string));//事假
            Rdt.Columns.Add("AnnualLeaveForDay", typeof(string));//年假
            Rdt.Columns.Add("SickLeaveForDay", typeof(string));//病假
            string STime = StartTime;
            List<string> MonthList = new List<string>();
            while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
            {
                Rdt.Columns.Add(STime, typeof(string));
                MonthList.Add(STime);
                STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
            }
            Rdt.AcceptChanges();

            //遍历出所有的人  根据人再去找到对应的每天的打卡时间
            string TimeStr = "";
            foreach (var item in EmData)
            {
                var EmRecordList = data.Where(x => x.EmployeeId == item.EmployeeId).ToList();
                DataRow Rdr = Rdt.NewRow();
                Rdr["EmName"] = item.EmName;
                Rdr["DepartmentName"] = item.DepartmentName;
                Rdr["EmployeeId"] = item.EmployeeId;
                Rdr["PostName"] = item.PostName;
                //Rdr["CQDay"] = item.CQDay;
                Rdr["XXDay"] = item.XXDay;
                Rdr["CDNum"] = item.CDNum;
                Rdr["CDTime"] = item.CDTime;
                Rdr["SBQK"] = item.SBQK;
                Rdr["XBQK"] = item.XBQK;
                Rdr["QGDay"] = item.QTKG;
                Rdr["AffairLeave"] = item.AffairLeaveSum;
                Rdr["AnnualLeave"] = item.AnnualLeaveSum;
                Rdr["SickLeave"] = item.SickLeaveSum;
                Double NJDay = 0;
                Double SJDay = 0;
                Double BJDay = 0;
                if (EmRecordList.Count > 0)
                {
                    STime = StartTime;
                    while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
                    {
                        var EmTime = EmRecordList.Where(x => x.DateStr == STime).FirstOrDefault();
                        if (EmTime != null)
                        {
                            TimeStr = "";
                            if (EmTime.BeOnRelevance.HasValue && EmTime.BeOnRelevance > 0 && EmTime.BeOnRelevanceType.HasValue && EmTime.BeOnRelevanceType > 0)
                            {
                                //根据workflowId和templateId求出该申请单
                                switch (EmTime.BeOnRelevanceType)
                                {
                                    case (int)WFTTemplateTypeEnum.AskForLeave:
                                        var askmodel = workFlowModule.GetAskforleave(EmTime.BeOnRelevance.Value);
                                        TimeStr = askmodel.AskforleaveType.ToName() + "<br/>" + askmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>";
                                        TimeStr += "到" + askmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>" + askmodel.Duration + " 小时<br/>";
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave)
                                        {//是年假  统计年假的天数
                                            NJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AffairLeave)
                                        {//是事假  统计年假的天数
                                            SJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                                        {//是病假  统计年假的天数
                                            BJDay += 0.5;
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Evection:
                                        var evemodel = workFlowModule.GetEvection(EmTime.BeOnRelevance.Value);
                                        var travelList = workFlowModule.GetTravelList(EmTime.BeOnRelevance.Value);
                                        if (travelList.Count > 0)
                                        {
                                            var travelModel = travelList.Where(x => Convert.ToDateTime(x.StartTime.Value.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(STime) && x.EndTime >= Convert.ToDateTime(STime)).ToList();
                                            foreach (var itemt in travelModel)
                                            {
                                                TimeStr += EnumHelper.ToName(WFTTemplateTypeEnum.Evection).Split('|')[0] + "<br/>" + itemt.StartTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>";
                                                TimeStr += "到" + itemt.EndTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>" + itemt.Duration + " 天<br/>";
                                            }
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Goout:
                                        var gooutmodel = workFlowModule.GetGoOut(EmTime.BeOnRelevance.Value);
                                        TimeStr = EnumHelper.ToName(WFTTemplateTypeEnum.Goout).Split('|')[0] + "<br/>" + gooutmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>";
                                        TimeStr += "到" + gooutmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>" + gooutmodel.Duration + " 小时<br/>";
                                        break;
                                    case (int)WFTTemplateTypeEnum.ReissueCard:
                                        TimeStr = "上班补卡<br/>";
                                        break;
                                    default:
                                        TimeStr = ""; break;
                                }
                            }
                            else
                            {
                                switch (EmTime.BeOnStatus)
                                {
                                    case AttendanceEnum.QK:
                                        TimeStr = "上班缺卡<br/>";
                                        break;
                                    case AttendanceEnum.CD:
                                        TimeStr = "上班迟到" + EmTime.BeLateTime + "分钟<br/>";
                                        break;
                                    default: TimeStr = ""; break;
                                }
                            }


                            if (EmTime.OffRelevance.HasValue && EmTime.OffRelevance > 0 && EmTime.OffRelevanceType.HasValue && EmTime.OffRelevanceType > 0)
                            {
                                //根据workflowId和templateId求出该申请单
                                switch (EmTime.OffRelevanceType)
                                {
                                    case (int)WFTTemplateTypeEnum.AskForLeave:
                                        var askmodel = workFlowModule.GetAskforleave(EmTime.OffRelevance.Value);
                                        TimeStr += askmodel.AskforleaveType.ToName() + "<br/>" + askmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>";
                                        TimeStr += "到" + askmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>" + askmodel.Duration + " 小时";
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave)
                                        {//是年假  统计年假的天数
                                            NJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AffairLeave)
                                        {//是事假  统计年假的天数
                                            SJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                                        {//是病假  统计年假的天数
                                            BJDay += 0.5;
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Evection:
                                        var evemodel = workFlowModule.GetEvection(EmTime.OffRelevance.Value);
                                        var travelList = workFlowModule.GetTravelList(EmTime.OffRelevance.Value);
                                        if (travelList.Count > 0)
                                        {
                                            var travelModel = travelList.Where(x => Convert.ToDateTime(x.StartTime.Value.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(STime) && x.EndTime >= Convert.ToDateTime(STime)).ToList();
                                            foreach (var itemt in travelModel)
                                            {
                                                TimeStr += EnumHelper.ToName(WFTTemplateTypeEnum.Evection).Split('|')[0] + "<br/>" + itemt.StartTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>";
                                                TimeStr += "到" + itemt.EndTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>" + itemt.Duration + " 天<br/>";
                                            }
                                            if (TimeStr != "")
                                                TimeStr = TimeStr.Substring(0, TimeStr.Length - 5);
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Goout:
                                        var gooutmodel = workFlowModule.GetGoOut(EmTime.OffRelevance.Value);
                                        TimeStr += EnumHelper.ToName(WFTTemplateTypeEnum.Goout).Split('|')[0] + "<br/>" + gooutmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>";
                                        TimeStr += "到" + gooutmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "<br/>" + gooutmodel.Duration + " 小时";
                                        break;
                                    case (int)WFTTemplateTypeEnum.ReissueCard:
                                        TimeStr += "下班补卡";
                                        break;
                                    default:
                                        TimeStr += ""; break;
                                }
                            }
                            else
                            {
                                switch (EmTime.OffStatus)
                                {
                                    case AttendanceEnum.QK:
                                        TimeStr += "下班缺卡";
                                        break;
                                    case AttendanceEnum.CD:
                                        TimeStr += "下班迟到" + EmTime.BeLateTime + "分钟";
                                        break;
                                    default: TimeStr += ""; break;
                                }
                            }

                            Rdr[STime] = TimeStr;
                        }
                        else
                        {
                            if (item.IsLeave == 0 && item.EmEntry.HasValue && item.EmEntry.Value > Convert.ToDateTime(STime))
                            {
                                Rdr[STime] = "";
                            }
                            else if (item.IsLeave == 1 && ((item.EmEntry.HasValue && item.EmEntry.Value > Convert.ToDateTime(STime)) || (item.EmLeave.HasValue && item.EmLeave < Convert.ToDateTime(STime))))
                            {
                                Rdr[STime] = "";
                            }
                            else
                            {
                                Rdr[STime] = "休息";
                            }
                        }
                        STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
                    }
                }
                Rdr["CQDay"] = Convert.ToDouble(item.CQDay) - item.QJDay + NJDay;
                Rdr["AffairLeaveForDay"] = SJDay;
                Rdr["AnnualLeaveForDay"] = NJDay;
                Rdr["SickLeaveForDay"] = BJDay;
                Rdt.Rows.Add(Rdr);
            }

            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = Rdt;

            return ApiResult.Success("", new { pmodel.Count, pmodel.PageCount, pmodel.PageData, pmodel.PageIndex, pmodel.PageSize, columnData = MonthList });
        }

        /// <summary>
        /// 根据两个日期 获取之间的天数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetTimeSpanValue()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            if (string.IsNullOrWhiteSpace(StartTime) || string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull();
            }
            try
            {
                Convert.ToDateTime(StartTime);
                Convert.ToDateTime(EndTime);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull();
            }
            string STime = StartTime;
            List<string> MonthList = new List<string>();
            while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
            {
                MonthList.Add(STime);
                STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
            }
            return ApiResult.Success("", MonthList);
        }

        /// <summary>
        /// 月度统计请假时长详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetAskLeaveInfo()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            string MonthTime = pram.GetStringValue("MonthTime");
            if (string.IsNullOrWhiteSpace(MonthTime))
            {
                return ApiResult.ParamIsNull("月份时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(MonthTime + "-01");
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("分月时间格式不正确！");
                }
            }
            string StartTime = MonthTime + "-01 00:00:00";
            string EndTime = Convert.ToDateTime(MonthTime + "-01").AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int AskLeaveType = pram.GetInt("AskLeaveType", 1);
            if (EmployeeId <= 0)
            {
                return ApiResult.ParamIsNull("员工id不能为空");
            }
            if (AskLeaveType < 1)
            {
                return ApiResult.ParamIsNull("请假类型不能为空！");
            }
            var data = attendancemodule.GetAskLeaveInfo(StartTime, EndTime, EmployeeId, AskLeaveType);
            return ApiResult.Success("", data.Select(x => new
            {
                x.Id,
                AskforleaveType = x.AskforleaveType.ToName(),
                StartTime = x.StartTime == null ? "" : x.StartTime.Value.ToString("yyyy-MM-dd HH:mm"),
                EndTime = x.EndTime == null ? "" : x.EndTime.Value.ToString("yyyy-MM-dd HH:mm"),
                x.Duration
            }));
        }

        /// <summary>
        /// 获取指定日期打卡记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetDayRecord()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            string CurrentTime = pram.GetStringValue("CurrentTime");
            if (string.IsNullOrWhiteSpace(CurrentTime))
            {
                return ApiResult.ParamIsNull("当前时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(CurrentTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("当前时间格式不正确！");
                }
            }
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            if (EmployeeId <= 0)
            {
                return ApiResult.ParamIsNull("员工id不能为空");
            }
            var data = attendancemodule.GetRecordForStatusList(CurrentTime, CurrentTime, EmployeeId, 0);
            var model = data.FirstOrDefault();
            if (model == null)
            {
                return ApiResult.ParamIsNull("参数有误，打卡记录不存在！");
            }
            string timeJson = attendancemodule.GetBeOnOffTime(model.EmployeeId, Convert.ToDateTime(CurrentTime));
            string BeOnTime = "", OffTime = "";
            if (timeJson != "")
            {
                JObject timeJ = JObject.Parse(timeJson);
                BeOnTime = timeJ.GetStringValue("BeOnTime");
                OffTime = timeJ.GetStringValue("OffTime");
            }
            return ApiResult.Success("", data.Select(x => new
            {
                x.Id,
                x.EmployeeId,
                x.DateStr,
                BeOnTime,
                BeOnDutyTime = x.BeOnDutyTime == null ? "" : x.BeOnDutyTime.Value.ToString("HH:mm"),
                OffDutyTime = x.OffDutyTime == null ? "" : x.OffDutyTime.Value.ToString("HH:mm"),
                BeOnResult = x.BeOnStatus.ToName(),
                OffTime,
                OffResult = x.OffStatus.ToName()
            }));
        }

        /// <summary>
        /// 获取每月状态打卡数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetRecordForStatusList()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            string MonthTime = pram.GetStringValue("MonthTime");
            if (string.IsNullOrWhiteSpace(MonthTime))
            {
                return ApiResult.ParamIsNull("月份时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(MonthTime + "-01");
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("分月时间格式不正确！");
                }
            }
            string StartTime = MonthTime + "-01";
            string EndTime = Convert.ToDateTime(MonthTime + "-01").AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int Status = pram.GetInt("Status", 0);
            if (EmployeeId <= 0)
            {
                return ApiResult.ParamIsNull("员工id不能为空！");
            }
            if (Status <= 0)
            {
                return ApiResult.ParamIsNull("状态条件不能为空！");
            }
            var data = attendancemodule.GetRecordForStatusList(StartTime, EndTime, EmployeeId, Status);
            return ApiResult.Success("", data.Select(x => new
            {
                x.Id,
                x.DateStr,
                BeOnDutyTime = x.BeOnDutyTime == null ? "" : x.BeOnDutyTime.Value.ToString("HH:mm"),
                OffDutyTime = x.OffDutyTime == null ? "" : x.OffDutyTime.Value.ToString("HH:mm"),
                BeOnResult = x.BeOnStatus.ToName(),
                OffResult = x.OffStatus.ToName()
            }));
        }

        /// <summary>
        /// 获取用户所在公司的考勤方式
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetAttendanceWay()
        {
            var userInfo = base.UserInfo;
            int aid = attendancemodule.IsAttendanceForBranch(userInfo.Group_Id, userInfo.School_Id);
            if (aid <= 0)
            {
                return ApiResult.Success("你所在的公司尚未启用考勤！");
            }
            var data = attendancemodule.GetAttendanceWay(aid);
            return ApiResult.Success("", data);
        }

        /// <summary>
        /// 更正缺卡
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult SetDayRecord()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            int RecordId = pram.GetInt("RecordId", 0);
            int OnAndOffDuty = pram.GetInt("OnAndOffDuty", 1);
            int RecordStatus = pram.GetInt("RecordStatus", 1);
            string BeLateTime = pram.GetStringValue("BeLateTime");
            string DKTime = pram.GetStringValue("DKTime");
            string SBTime = pram.GetStringValue("SBTime");
            if (RecordId <= 0)
            {
                return ApiResult.ParamIsNull("记录id不能为空！");
            }
            if (string.IsNullOrWhiteSpace(DKTime))
            {
                return ApiResult.ParamIsNull("上下班时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(DKTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("上下班时间格式不正确！");
                }
            }
            bool flag = attendancemodule.SetDayRecord(RecordId, OnAndOffDuty, RecordStatus, BeLateTime, DKTime, SBTime);
            if (flag)
                return ApiResult.Success("");
            else
                return ApiResult.Failed("非缺卡类型不能有更正操作！");


        }



        /// <summary>
        /// 获取每日打卡记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Obsolete]
        public virtual ApiResult GetEveryDayAttendanceRecordExcel()
        {
            var userInfo = base.UserInfo;
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                return ApiResult.ParamIsNull("起始时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(StartTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("起始时间格式不正确！");
                }
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull("结束时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(EndTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("结束时间格式不正确！");
                }
            }
            var data = attendancemodule.GetEveryDayAttendanceRecordList(1, int.MaxValue, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("姓名", typeof(string));
            Rdt.Columns.Add("部门", typeof(string));
            Rdt.Columns.Add("工号", typeof(string));
            Rdt.Columns.Add("职位", typeof(string));
            Rdt.Columns.Add("日期", typeof(string));
            Rdt.Columns.Add("上班打卡时间", typeof(string));
            Rdt.Columns.Add("上班打卡结果", typeof(string));
            Rdt.Columns.Add("下班打卡时间", typeof(string));
            Rdt.Columns.Add("下班打卡结果", typeof(string));
            Rdt.AcceptChanges();
            foreach (var item in data)
            {
                DataRow dr = Rdt.NewRow();
                dr["工号"] = item.EmployeeId;
                dr["姓名"] = item.EmName;
                dr["部门"] = item.DepartmentName;
                dr["职位"] = item.PostName;
                dr["日期"] = item.DateStr;
                dr["上班打卡时间"] = item.BeOnDutyTime;
                dr["上班打卡结果"] = EnumHelper.ToName(item.BeOnStatus);
                dr["下班打卡时间"] = item.OffDutyTime;
                dr["下班打卡结果"] = EnumHelper.ToName(item.OffStatus);
                Rdt.Rows.Add(dr);
            }
            string FileName = StartTime + "-" + EndTime + "每日打卡记录表.xls";
            NPOIHelper.ExportDTtoExcel(Rdt, "报表", Config.FileExportPath + "\\" + FileName);

            Task.Run(() => DeleteDownLoadFile(Config.FileExportPath + "\\" + FileName));
            return ApiResult.Success("", "/ExportFile/" + FileName);
        }

        /// <summary>
        /// 获取原始记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Obsolete]
        public virtual ApiResult GetOriginalRecordExcel()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            var userInfo = base.UserInfo;
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                return ApiResult.ParamIsNull("起始时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(StartTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("起始时间格式不正确！");
                }
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull("结束时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(EndTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("结束时间格式不正确！");
                }
            }
            var data = attendancemodule.GetOriginalRecordList(1, int.MaxValue, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("姓名", typeof(string));
            Rdt.Columns.Add("部门", typeof(string));
            Rdt.Columns.Add("工号", typeof(string));
            Rdt.Columns.Add("职位", typeof(string));
            Rdt.Columns.Add("日期", typeof(string));
            Rdt.Columns.Add("上班考勤时间", typeof(string));
            Rdt.Columns.Add("上班打卡时间", typeof(string));
            Rdt.Columns.Add("上班打卡结果", typeof(string));
            Rdt.Columns.Add("上班打卡地址", typeof(string));
            Rdt.Columns.Add("下班考勤时间", typeof(string));
            Rdt.Columns.Add("下班打卡时间", typeof(string));
            Rdt.Columns.Add("下班打卡结果", typeof(string));
            Rdt.Columns.Add("下班打卡地址", typeof(string));
            Rdt.Columns.Add("打卡设备", typeof(string));
            Rdt.AcceptChanges();
            foreach (var item in data)
            {
                DataRow dr = Rdt.NewRow();
                dr["工号"] = item.EmployeeId;
                dr["姓名"] = item.EmName;
                dr["部门"] = item.DepartmentName;
                dr["职位"] = item.PostName;
                dr["日期"] = item.DateStr;
                dr["上班考勤时间"] = item.BeOnTime;
                dr["上班打卡时间"] = item.BeOnDutyTime;
                dr["上班打卡结果"] = EnumHelper.ToName(item.BeOnStatus);
                dr["上班打卡地址"] = item.BeOnAddress;
                dr["下班考勤时间"] = item.OffTime;
                dr["下班打卡时间"] = item.OffDutyTime;
                dr["下班打卡结果"] = EnumHelper.ToName(item.OffStatus);
                dr["下班打卡地址"] = item.OffAddress;
                dr["打卡设备"] = item.PhoneName;
                Rdt.Rows.Add(dr);
            }
            string FileName = StartTime + "-" + EndTime + "原始打卡记录表.xls";
            NPOIHelper.ExportDTtoExcel(Rdt, "报表", Config.FileExportPath + "\\" + FileName);

            Task.Run(() => DeleteDownLoadFile(Config.FileExportPath + "\\" + FileName));
            return ApiResult.Success("", "/ExportFile/" + FileName);
        }

        /// <summary>
        /// 获取打卡时间
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Obsolete]
        public virtual ApiResult GetClockTimeRecordExcel()
        {
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            var userInfo = base.UserInfo;
            string StartTime = pram.GetStringValue("StartTime");
            string EndTime = pram.GetStringValue("EndTime");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                return ApiResult.ParamIsNull("起始时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(StartTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("起始时间格式不正确！");
                }
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                return ApiResult.ParamIsNull("结束时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(EndTime);
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("结束时间格式不正确！");
                }
            }
            var EmData = attendancemodule.GetClockTimeEmployeeList(StartTime, EndTime, 1, int.MaxValue, out long count, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            var data = attendancemodule.GetClockTimeRecordList(StartTime, EndTime, EmployeeId, BranchId, DepartmentId, "", userInfo.Group_Id);
            //声明一个DataTable 动态添加每日打卡时间
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("姓名", typeof(string));
            Rdt.Columns.Add("部门", typeof(string));
            Rdt.Columns.Add("工号", typeof(string));
            Rdt.Columns.Add("岗位", typeof(string));
            string STime = StartTime;
            while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
            {
                Rdt.Columns.Add(STime, typeof(string));
                STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
            }
            Rdt.AcceptChanges();

            //遍历出所有的人  根据人再去找到对应的每天的打卡时间
            string TimeStr = "";
            foreach (var item in EmData)
            {
                var EmRecordList = data.Where(x => x.EmployeeId == item.EmployeeId).ToList();
                DataRow Rdr = Rdt.NewRow();
                Rdr["姓名"] = item.EmName;
                Rdr["部门"] = item.DepartmentName;
                Rdr["工号"] = item.EmployeeId;
                Rdr["岗位"] = item.PostName;
                if (EmRecordList.Count > 0)
                {
                    STime = StartTime;
                    while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
                    {
                        var EmTime = EmRecordList.Where(x => x.DateStr == STime).FirstOrDefault();
                        if (EmTime != null)
                        {
                            TimeStr = "";
                            if (EmTime.BeOnStatus == AttendanceEnum.ZC || EmTime.BeOnStatus == AttendanceEnum.CD)
                            {
                                TimeStr = "上班：" + EmTime.BeOnDutyTime.Value.ToString("HH:mm:ss");
                            }
                            if (EmTime.OffStatus == AttendanceEnum.ZC || EmTime.OffStatus == AttendanceEnum.CD)
                            {
                                if (TimeStr != "")
                                    TimeStr += "\r\n下班：" + EmTime.OffDutyTime.Value.ToString("HH:mm:ss");
                                else
                                    TimeStr += "下班：" + EmTime.OffDutyTime.Value.ToString("HH:mm:ss");
                            }
                            Rdr[STime] = TimeStr;
                        }
                        else
                        {
                            Rdr[STime] = "";
                        }
                        STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
                    }
                }
                Rdt.Rows.Add(Rdr);
            }
            string FileName = StartTime + "-" + EndTime + "打卡时间表.xls";
            NPOIHelper.ExportDTtoExcel(Rdt, "报表", Config.FileExportPath + "\\" + FileName);

            Task.Run(() => DeleteDownLoadFile(Config.FileExportPath + "\\" + FileName));
            return ApiResult.Success("", "/ExportFile/" + FileName);
        }

        /// <summary>
        /// 获取每月打卡统计
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Obsolete]
        public virtual ApiResult GetMonthRecordExcel()
        {
            var userInfo = base.UserInfo;
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            string MonthTime = pram.GetStringValue("MonthTime");
            if (string.IsNullOrWhiteSpace(MonthTime))
            {
                return ApiResult.ParamIsNull("月份时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(MonthTime + "-01");
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("分月时间格式不正确！");
                }
            }
            string StartTime = MonthTime + "-01";
            string EndTime = Convert.ToDateTime(MonthTime + "-01").AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            var EmData = attendancemodule.GetMonthRecordList(1, int.MaxValue, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            var data = attendancemodule.GetClockTimeRecordList(StartTime, EndTime, EmployeeId, BranchId, DepartmentId, "", userInfo.Group_Id, 0);
            //声明一个DataTable 动态添加每日打卡时间
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("姓名", typeof(string));
            Rdt.Columns.Add("部门", typeof(string));
            Rdt.Columns.Add("工号", typeof(string));
            Rdt.Columns.Add("岗位", typeof(string));
            Rdt.Columns.Add("出勤天数", typeof(string));
            Rdt.Columns.Add("休息天数", typeof(string));
            Rdt.Columns.Add("迟到次数", typeof(string));
            Rdt.Columns.Add("迟到时长", typeof(string));
            Rdt.Columns.Add("上班缺卡", typeof(string));
            Rdt.Columns.Add("下班缺卡", typeof(string));
            Rdt.Columns.Add("旷工天数", typeof(string));

            Rdt.Columns.Add("事假时长", typeof(string));//事假
            Rdt.Columns.Add("年假时长", typeof(string));//年假
            Rdt.Columns.Add("病假时长", typeof(string));//病假
            Rdt.Columns.Add("事假天数", typeof(string));//事假
            Rdt.Columns.Add("年假天数", typeof(string));//年假
            Rdt.Columns.Add("病假天数", typeof(string));//病假

            string STime = StartTime;
            while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
            {
                Rdt.Columns.Add(STime, typeof(string));
                STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
            }
            Rdt.AcceptChanges();

            //遍历出所有的人  根据人再去找到对应的每天的打卡时间
            string TimeStr = "";
            foreach (var item in EmData)
            {
                var EmRecordList = data.Where(x => x.EmployeeId == item.EmployeeId).ToList();
                DataRow Rdr = Rdt.NewRow();
                Rdr["姓名"] = item.EmName;
                Rdr["部门"] = item.DepartmentName;
                Rdr["工号"] = item.EmployeeId;
                Rdr["岗位"] = item.PostName;
                //Rdr["出勤天数"] = item.CQDay;
                Rdr["休息天数"] = item.XXDay;
                Rdr["迟到次数"] = item.CDNum;
                Rdr["迟到时长"] = item.CDTime;
                Rdr["上班缺卡"] = item.SBQK;
                Rdr["下班缺卡"] = item.XBQK;
                Rdr["旷工天数"] = item.QTKG;
                Rdr["事假时长"] = item.AffairLeaveSum;
                Rdr["年假时长"] = item.AnnualLeaveSum;
                Rdr["病假时长"] = item.SickLeaveSum;
                Double NJDay = 0;
                Double BJDay = 0;
                Double SJDay = 0;
                if (EmRecordList.Count > 0)
                {
                    STime = StartTime;
                    while (Convert.ToDateTime(STime) <= Convert.ToDateTime(EndTime))
                    {
                        var EmTime = EmRecordList.Where(x => x.DateStr == STime).FirstOrDefault();
                        if (EmTime != null)
                        {
                            TimeStr = "";
                            if (EmTime.BeOnRelevance.HasValue && EmTime.BeOnRelevance > 0 && EmTime.BeOnRelevanceType.HasValue && EmTime.BeOnRelevanceType > 0)
                            {
                                //根据workflowId和templateId求出该申请单
                                switch (EmTime.BeOnRelevanceType)
                                {
                                    case (int)WFTTemplateTypeEnum.AskForLeave:
                                        var askmodel = workFlowModule.GetAskforleave(EmTime.BeOnRelevance.Value);
                                        TimeStr = askmodel.AskforleaveType.ToName() + "\r\n" + askmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n";
                                        TimeStr += "到" + askmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n " + askmodel.Duration + " 小时\r\n";
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave)
                                        {//是年假  统计年假的天数
                                            NJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AffairLeave)
                                        {//是事假  统计年假的天数
                                            SJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                                        {//是病假  统计年假的天数
                                            BJDay += 0.5;
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Evection:
                                        var evemodel = workFlowModule.GetEvection(EmTime.BeOnRelevance.Value);
                                        var travelList = workFlowModule.GetTravelList(EmTime.BeOnRelevance.Value);
                                        if (travelList.Count > 0)
                                        {
                                            var travelModel = travelList.Where(x => Convert.ToDateTime(x.StartTime.Value.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(STime) && x.EndTime >= Convert.ToDateTime(STime)).ToList();
                                            foreach (var itemt in travelModel)
                                            {
                                                TimeStr += EnumHelper.ToName(WFTTemplateTypeEnum.Evection).Split('|')[0] + "\r\n" + itemt.StartTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n";
                                                TimeStr += "到" + itemt.EndTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n " + itemt.Duration + " 天\r\n";
                                            }
                                            //if (TimeStr != "")
                                            //    TimeStr = TimeStr.Substring(0, TimeStr.Length - 5);
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Goout:
                                        var gooutmodel = workFlowModule.GetGoOut(EmTime.BeOnRelevance.Value);
                                        TimeStr = EnumHelper.ToName(WFTTemplateTypeEnum.Goout).Split('|')[0] + "\r\n" + gooutmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n";
                                        TimeStr += "到" + gooutmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n" + gooutmodel.Duration + " 小时\r\n";
                                        break;
                                    case (int)WFTTemplateTypeEnum.ReissueCard:
                                        TimeStr = "上班补卡\r\n";
                                        break;
                                    default:
                                        TimeStr = ""; break;
                                }
                            }
                            else
                            {
                                switch (EmTime.BeOnStatus)
                                {
                                    case AttendanceEnum.QK:
                                        TimeStr = "上班缺卡\r\n";
                                        break;
                                    case AttendanceEnum.CD:
                                        TimeStr = "上班迟到" + EmTime.BeLateTime + "分钟\r\n";
                                        break;
                                    default: TimeStr = ""; break;
                                }
                            }


                            if (EmTime.OffRelevance.HasValue && EmTime.OffRelevance > 0 && EmTime.OffRelevanceType.HasValue && EmTime.OffRelevanceType > 0)
                            {
                                //根据workflowId和templateId求出该申请单
                                switch (EmTime.OffRelevanceType)
                                {
                                    case (int)WFTTemplateTypeEnum.AskForLeave:
                                        var askmodel = workFlowModule.GetAskforleave(EmTime.OffRelevance.Value);
                                        TimeStr += askmodel.AskforleaveType.ToName() + "\r\n" + askmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n";
                                        TimeStr += "到" + askmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n " + askmodel.Duration + " 小时";
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave)
                                        {//是年假  统计年假的天数
                                            NJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AffairLeave)
                                        {//是事假  统计年假的天数
                                            SJDay += 0.5;
                                        }
                                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                                        {//是病假  统计年假的天数
                                            BJDay += 0.5;
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Evection:
                                        var evemodel = workFlowModule.GetEvection(EmTime.OffRelevance.Value);
                                        var travelList = workFlowModule.GetTravelList(EmTime.OffRelevance.Value);
                                        if (travelList.Count > 0)
                                        {
                                            var travelModel = travelList.Where(x => Convert.ToDateTime(x.StartTime.Value.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(STime) && x.EndTime >= Convert.ToDateTime(STime)).ToList();
                                            foreach (var itemt in travelModel)
                                            {
                                                TimeStr += EnumHelper.ToName(WFTTemplateTypeEnum.Evection).Split('|')[0] + "\r\n" + itemt.StartTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n";
                                                TimeStr += "到" + itemt.EndTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n " + itemt.Duration + " 天\r\n";
                                            }
                                            if (TimeStr != "")
                                                TimeStr = TimeStr.Substring(0, TimeStr.Length - 4);
                                        }
                                        break;
                                    case (int)WFTTemplateTypeEnum.Goout:
                                        var gooutmodel = workFlowModule.GetGoOut(EmTime.OffRelevance.Value);
                                        TimeStr += EnumHelper.ToName(WFTTemplateTypeEnum.Goout).Split('|')[0] + "\r\n" + gooutmodel.StartTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n";
                                        TimeStr += "到" + gooutmodel.EndTime.Value.ToString("MM-dd HH:mm:ss") + "\r\n " + gooutmodel.Duration + " 小时";
                                        break;
                                    case (int)WFTTemplateTypeEnum.ReissueCard:
                                        TimeStr += "下班补卡";
                                        break;
                                    default:
                                        TimeStr += ""; break;
                                }
                            }
                            else
                            {
                                switch (EmTime.OffStatus)
                                {
                                    case AttendanceEnum.QK:
                                        TimeStr += "下班缺卡";
                                        break;
                                    case AttendanceEnum.CD:
                                        TimeStr += "下班迟到" + EmTime.BeLateTime + "分钟";
                                        break;
                                    default: TimeStr += ""; break;
                                }
                            }

                            Rdr[STime] = TimeStr;
                        }
                        else
                        {
                            if (item.IsLeave == 0 && item.EmEntry.HasValue && item.EmEntry.Value > Convert.ToDateTime(STime))
                            {
                                Rdr[STime] = "";
                            }
                            else if (item.IsLeave == 1 && ((item.EmEntry.HasValue && item.EmEntry.Value > Convert.ToDateTime(STime)) || (item.EmLeave.HasValue && item.EmLeave < Convert.ToDateTime(STime))))
                            {
                                Rdr[STime] = "";
                            }
                            else
                            {
                                Rdr[STime] = "休息";
                            }
                        }
                        STime = Convert.ToDateTime(STime).AddDays(1).ToString("yyyy-MM-dd");
                    }
                }
                Rdr["出勤天数"] = Convert.ToDouble(item.CQDay) - item.QJDay + NJDay;
                Rdr["事假天数"] = SJDay;
                Rdr["年假天数"] = NJDay;
                Rdr["病假天数"] = BJDay;
                Rdt.Rows.Add(Rdr);
            }
            string FileName = MonthTime + "月打卡记录表.xls";
            NPOIHelper.ExportDTtoExcel(Rdt, "报表", Config.FileExportPath + "\\" + FileName);

            Task.Run(() => DeleteDownLoadFile(Config.FileExportPath + "\\" + FileName));
            return ApiResult.Success("", "/ExportFile/" + FileName);
        }

        /// <summary>
        /// 四川和平专用  统计每月打卡
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetMonthRecordExcelForHPZY()
        {
            var userInfo = base.UserInfo;
            JObject pram = JObject.Parse(RequestParm.Msg.ToString());
            string MonthTime = pram.GetStringValue("MonthTime");
            if (string.IsNullOrWhiteSpace(MonthTime))
            {
                return ApiResult.ParamIsNull("月份时间不能为空");
            }
            else
            {
                try
                {
                    DateTime.Parse(MonthTime + "-01");
                }
                catch (Exception)
                {
                    return ApiResult.ParamIsNull("分月时间格式不正确！");
                }
            }
            string StartTime = MonthTime + "-01";
            string EndTime = Convert.ToDateTime(MonthTime + "-01").AddMonths(1).AddSeconds(-1).ToString("yyyy-MM-dd");
            int EmployeeId = pram.GetInt("EmployeeId", 0);
            int BranchId = pram.GetInt("BranchId", -1);
            int DepartmentId = pram.GetInt("DepartmentId", 0);
            var EmData = attendancemodule.GetMonthRecordListForHPZY(1, int.MaxValue, out long count, StartTime, EndTime, EmployeeId, BranchId, DepartmentId, userInfo.Group_Id);
            //销售跟非销售列表   销售的需要查询出对应的收客数
            var EmSaleList = EmData.Where(x => x.DepartmentName.Contains("销售")).ToList();
            var EmNorList = EmData.Where(x => !x.DepartmentName.Contains("销售")).ToList();
            //求销售收客数量
            if (EmSaleList.Count() > 0)
            {
                //var GuestList = attendancemodule.GetMonthSaleGuestNum(string.Join(",", EmSaleList.Select(x => x.EmployeeId).ToList()), StartTime, EndTime);
                foreach (var item in EmSaleList)
                {
                    //var model = GuestList.Where(x => x.EnterID == item.EmployeeId).FirstOrDefault();
                    //if (model != null)
                    //{
                    //    item.GuestNum = model.GuestNum ?? 0;
                    //}
                    item.GuestNum = 0;
                }
            }

            //声明一个DataTable 动态添加每日打卡时间
            DataTable Rdt = new DataTable();
            Rdt.Columns.Add("序号", typeof(string));
            Rdt.Columns.Add("姓名", typeof(string));
            Rdt.Columns.Add("部门", typeof(string));
            Rdt.Columns.Add("实际上班天数", typeof(string));
            Rdt.Columns.Add("迟到一档", typeof(string));
            Rdt.Columns.Add("迟到二档", typeof(string));
            Rdt.Columns.Add("事假/天", typeof(string));
            Rdt.Columns.Add("病假/天", typeof(string));
            Rdt.Columns.Add("旷工/天", typeof(string));
            Rdt.Columns.Add("年假/天", typeof(string));

            Rdt.Columns.Add("婚假/天", typeof(string));
            Rdt.Columns.Add("罚单/元", typeof(string));
            Rdt.Columns.Add("代打卡", typeof(string));
            Rdt.Columns.Add("入职时间", typeof(string));
            Rdt.Columns.Add("剩余未修年假天数", typeof(string));
            Rdt.Columns.Add("离职时间", typeof(string));
            Rdt.Columns.Add("收客数", typeof(string));
            Rdt.Columns.Add("备注", typeof(string));
            Rdt.Columns.Add("社保个人扣款", typeof(string));
            Rdt.Columns.Add("备注2", typeof(string));
            Rdt.AcceptChanges();
            int Num = 1;
            DataRow Rdr = Rdt.NewRow();
            foreach (var item in EmNorList)
            {
                Rdr = Rdt.NewRow();
                Rdr["序号"] = Num;
                Num++;
                Rdr["姓名"] = item.EmName;
                Rdr["部门"] = item.DepartmentName;
                var SJWordDay = Convert.ToDouble(item.CQDay) - Convert.ToDouble(item.QTKG) - item.SJDay - (item.BJDay > 5 ? item.BJDay : 0);
                Rdr["实际上班天数"] = SJWordDay > 0 ? SJWordDay.ToString() : "";
                Rdr["迟到一档"] = item.OneCDNum > 0 ? item.OneCDNum.ToString() : "";
                Rdr["迟到二档"] = item.TwoCDNum > 0 ? item.TwoCDNum.ToString() : "";
                Rdr["事假/天"] = item.SJDay > 0 ? item.SJDay.ToString() : "";
                Rdr["病假/天"] = item.BJDay > 0 ? item.BJDay.ToString() : "";
                Rdr["旷工/天"] = item.QTKG > 0 ? item.QTKG.ToString() : "";
                Rdr["年假/天"] = item.NJDay > 0 ? item.NJDay.ToString() : "";
                Rdr["婚假/天"] = item.HJDay > 0 ? item.HJDay.ToString() : "";
                Rdr["罚单/元"] = "";
                Rdr["代打卡"] = "";
                Rdr["入职时间"] = item.EmEntry.HasValue ? item.EmEntry.Value.ToString("yyyy-MM-dd") : "";
                Rdr["剩余未修年假天数"] = item.AnnualLeaveDay > 0 ? item.AnnualLeaveDay.ToString() : "";
                Rdr["离职时间"] = item.IsLeave == 1 ? item.EmLeave.HasValue ? item.EmLeave.Value.ToString("yyyy-MM-dd") : "" : "";
                Rdr["收客数"] = "";
                Rdr["备注"] = "";
                Rdr["社保个人扣款"] = "";
                Rdr["备注2"] = "";
                Rdt.Rows.Add(Rdr);
            }
            Rdr = Rdt.NewRow();
            Rdt.Rows.Add(Rdr);
            Rdr = Rdt.NewRow();
            Rdt.Rows.Add(Rdr);
            Rdr = Rdt.NewRow();
            Rdr["序号"] = "销售统计";
            Rdt.Rows.Add(Rdr);
            Num = 1;
            foreach (var item in EmSaleList)
            {
                Rdr = Rdt.NewRow();
                Rdr["序号"] = Num;
                Num++;
                Rdr["姓名"] = item.EmName;
                Rdr["部门"] = item.DepartmentName;
                var SJWordDay = Convert.ToDouble(item.CQDay) - Convert.ToDouble(item.QTKG) - item.SJDay - (item.BJDay > 5 ? item.BJDay : 0);
                Rdr["实际上班天数"] = SJWordDay > 0 ? SJWordDay.ToString() : "";
                Rdr["迟到一档"] = item.OneCDNum > 0 ? item.OneCDNum.ToString() : "";
                Rdr["迟到二档"] = item.TwoCDNum > 0 ? item.TwoCDNum.ToString() : "";
                Rdr["事假/天"] = item.SJDay > 0 ? item.SJDay.ToString() : "";
                Rdr["病假/天"] = item.BJDay > 0 ? item.BJDay.ToString() : "";
                Rdr["旷工/天"] = item.QTKG > 0 ? item.QTKG.ToString() : "";
                Rdr["年假/天"] = item.NJDay > 0 ? item.NJDay.ToString() : "";
                Rdr["婚假/天"] = item.HJDay > 0 ? item.HJDay.ToString() : "";
                Rdr["罚单/元"] = "";
                Rdr["代打卡"] = "";
                Rdr["入职时间"] = item.EmEntry.HasValue ? item.EmEntry.Value.ToString("yyyy-MM-dd") : "";
                Rdr["剩余未修年假天数"] = item.AnnualLeaveDay > 0 ? item.AnnualLeaveDay.ToString() : "";
                Rdr["离职时间"] = item.IsLeave == 1 ? item.EmLeave.HasValue ? item.EmLeave.Value.ToString("yyyy-MM-dd") : "" : "";
                Rdr["收客数"] = item.GuestNum;
                Rdr["备注"] = "";
                Rdr["社保个人扣款"] = "";
                Rdr["备注2"] = "";
                Rdt.Rows.Add(Rdr);
            }
            Random ran = new Random();
            string FileName = MonthTime + "月打卡记录表" + ran.Next(1000, 9999) + ".xlsx";
            NPOIHelper.ExportInsertAndMergeCells(Rdt, "sheet", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/WordTemplate/月度考勤汇总.xlsx"), Config.FileExportPath + "\\" + FileName, 3, "MS Mincho", 11);

            Task.Run(() => DeleteDownLoadFile(Config.FileExportPath + "\\" + FileName));
            return ApiResult.Success("", "/ExportFile/" + FileName);
        }

        /// <summary>
        /// 删除下载的文件
        /// </summary>
        /// <param name="path"></param>
        public void DeleteDownLoadFile(object path)
        {
            System.Threading.Thread.Sleep(60000);
            if (System.IO.File.Exists(path.ToString()))
            {
                System.IO.File.Delete(path.ToString());
            }
        }

        #endregion


        #region APP考勤
        /// <summary>
        /// App获取今天打卡信息
        /// </summary>        
        /// <returns></returns>
        public ApiResult GetAttendRecod()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            string date = JsonHelper.GetStringValue(parm, "date");
            if (string.IsNullOrWhiteSpace(date))
            {
                return ApiResult.ParamIsNull("日期时间为空");
            }
            JObject result = new JObject();
            JObject recodeInfo = attendRecodeModule.GetAttendRecod(userInfo.Id, userInfo.DeptId, date);
            if (recodeInfo == null)
            {
                result["isNeedCard"] = false;
                result["recodeInfo"] = recodeInfo;
            }
            else
            {
                result["isNeedCard"] = true;
                result["recodeInfo"] = recodeInfo;
            }
            return ApiResult.Success("获取成功", data: result);
        }

        /// <summary>
        /// App验证是否在打卡范围
        /// </summary>        
        /// <returns></returns>
        public ApiResult VerifyPunchCard()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            string latAndLong = JsonHelper.GetStringValue(parm, "latAndLong");
            string wifiMac = JsonHelper.GetStringValue(parm, "wifiMac");
            string oldWifiMac = JsonHelper.GetStringValue(parm, "wifiMac");
            string version = JsonHelper.GetStringValue(parm, "version");
            if (string.IsNullOrWhiteSpace(latAndLong) && string.IsNullOrWhiteSpace(wifiMac))
            {
                return ApiResult.ParamIsNull("参数为空");
            }
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<RB_Attendance_Way_Extend> wayList = new List<RB_Attendance_Way_Extend>();
            wifiMac = GetMdifyWifiMac(wifiMac);
            bool isNotVerifyVifi = JudgeNotVerifyVifi(version, empId);
            bool isRang = isNotVerifyVifi ? isNotVerifyVifi : attendRecodeModule.VerifyPunchCard(empId, latAndLong, wifiMac, oldWifiMac, out wayList);
            var attendWay = wayList.Select(t => new { type = t.Type, name = t.Name, address = t.Address, targetAddress = t.TargetAddress, scope = t.Scope });
            var result = new { isLegal = isRang, attendWay };
            return ApiResult.Success("获取成功", data: result);
        }

        /// <summary>
        /// App考勤打卡
        /// </summary>        
        /// <returns></returns>
        public ApiResult PunchCard()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            string latAndLong = JsonHelper.GetStringValue(parm, "latAndLong");
            string address = JsonHelper.GetStringValue(parm, "address");
            string wifiMac = JsonHelper.GetStringValue(parm, "wifiMac");
            string oldWifiMac = wifiMac;
            string phoneId = JsonHelper.GetStringValue(parm, "phoneId");
            string PhoneName = JsonHelper.GetStringValue(parm, "PhoneName");
            string version = JsonHelper.GetStringValue(parm, "version");
            if (string.IsNullOrWhiteSpace(latAndLong) && string.IsNullOrWhiteSpace(wifiMac))
            {
                return ApiResult.ParamIsNull("参数为空");
            }
            if (string.IsNullOrWhiteSpace(phoneId))
            {
                return ApiResult.ParamIsNull("手机标识码为空");
            }
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            string date = JsonHelper.GetStringValue(parm, "date");
            wifiMac = GetMdifyWifiMac(wifiMac);
            LogHelper.WriteInfo($"打卡信息:{JsonConvert.SerializeObject(RequestParm)}-->更新后的mac:{wifiMac}");
            int PunchCardType;
            bool isNotVerifyVifi = JudgeNotVerifyVifi(version, userInfo.Id);
            string result = attendRecodeModule.PunchCard(userInfo.Id, userInfo.DeptId, latAndLong, wifiMac, oldWifiMac, phoneId, address, PhoneName, out PunchCardType, isNotVerifyVifi);
            var resultData = new { punchCardType = PunchCardType };
            if (result.Equals("ok"))
            {
                return ApiResult.Success("打卡成功", data: resultData);
            }
            else if (result.Equals("不在打卡范围"))
            {
                return new ApiResult() { Code = (int)ResultCode.NotInCardRange, Message = result };
            }
            else
            {
                return ApiResult.Failed(message: result);
            }

        }
        /// <summary>
        /// 不打卡wifi版本
        /// </summary>
        /// <param name="version"></param>
        /// <param name="EmpId"></param>
        /// <returns></returns>
        private bool JudgeNotVerifyVifi(string version, int EmpId)
        {
            bool isNotVerifyVifi = false;
            if (!string.IsNullOrWhiteSpace(version))
            {
                string[] versionInfo = version.Split('&');
                if (versionInfo.Length == 3 && versionInfo[1].ToLower().Equals("ios") && versionInfo[2].Equals("1.1.8"))
                {
                    isNotVerifyVifi = true;
                }
            }
            return isNotVerifyVifi;
        }
        /// <summary>
        /// 获取修改后wifimac
        /// </summary>
        /// <param name="wifiMac">原始</param>
        /// <returns></returns>
        private string GetMdifyWifiMac(string wifiMac)
        {
            if (!string.IsNullOrWhiteSpace(wifiMac))
            {
                string[] mac = wifiMac.Split(':');
                for (int i = 0; i < mac.Length; i++)
                {
                    if (mac[i].Length == 1)
                    {
                        mac[i] = $"0{mac[i]}";
                    }
                }
                wifiMac = string.Join(":", mac).ToLower();
            }
            return wifiMac;
        }

        /// <summary>
        /// App考勤打卡统计
        /// </summary>
        /// <returns></returns>
        public ApiResult PunchCardStatistical()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            string date = JsonHelper.GetStringValue(parm, "date");
            if (string.IsNullOrWhiteSpace(date))
            {
                return ApiResult.ParamIsNull("日期为空");
            }
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<JObject> result = attendRecodeModule.PunchCardStatistical(empId, date);
            return ApiResult.Success("获取成功", data: result);

        }

        /// <summary>
        /// App考勤打卡月历
        /// </summary>
        /// <returns></returns>
        public ApiResult PunchCardCalendar()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            string date = JsonHelper.GetStringValue(parm, "date");
            if (string.IsNullOrWhiteSpace(date))
            {
                return ApiResult.ParamIsNull("日期为空");
            }
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<JObject> result = attendRecodeModule.PunchCardCalendar(empId, date);
            return ApiResult.Success("获取成功", data: result);
        }
        #endregion
    }
}