using Edu.Common.API;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.User;
using Edu.Model.Public;
using Edu.Model.ViewModel.User;
using Edu.Repository.User;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Edu.Module.User
{
    /// <summary>
    /// 流程处理类
    /// </summary>
    public class WorkFlowModule
    {
        private readonly Rb_workdaysetingRepository WDrespository = new Rb_workdaysetingRepository();
        private readonly Rb_Workflow_AskforleaveRepository askforleaveRepository = new Rb_Workflow_AskforleaveRepository();
        private readonly Rb_technicaldatesRepository technicaldatesRepository = new Rb_technicaldatesRepository();
        private readonly Rb_attendance_recordRepository RecordRepository = new Rb_attendance_recordRepository();
        private readonly Rb_dictvalueRepository rb_DictvalueRepository = new Rb_dictvalueRepository();
        private readonly RB_Attendance_LeaveTimeRepository attendance_LeaveTimeRepository = new RB_Attendance_LeaveTimeRepository();

        /// <summary>
        /// 部门
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();
        /// <summary>
        /// 账号
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();


        private readonly Rb_Workflow_TemplateRepository workFlowTemplateRepository = new Rb_Workflow_TemplateRepository();
        private readonly Rb_Workflow_ConditionRepository conditionRepository = new Rb_Workflow_ConditionRepository();
        private readonly Rb_Workflow_AuditRepository wfAuditRepository = new Rb_Workflow_AuditRepository();
        private readonly Rb_Workflow_AuditRelevanceRepository auditRelevanceRepository = new Rb_Workflow_AuditRelevanceRepository();
        private readonly Rb_Workflow_AuditUserRepository auditUserRepository = new Rb_Workflow_AuditUserRepository();
        private readonly Rb_Workflow_AuditUserRelevanceRepository auditUserRelevanceRepository = new Rb_Workflow_AuditUserRelevanceRepository();

        private readonly Rb_Workflow_AuditrecordRepository auditrecordRepository = new Rb_Workflow_AuditrecordRepository();
        private readonly Rb_Workflow_EvectionRepository wfEvectionRepository = new Rb_Workflow_EvectionRepository();
        private readonly Rb_Workflow_TravelRepository wfTravelRepository = new Rb_Workflow_TravelRepository();
        private readonly Rb_Workflow_ReissuecardRepository wfReissuecardRepository = new Rb_Workflow_ReissuecardRepository();
        private readonly Rb_Workflow_GoOutRepository wfGoOutRepository = new Rb_Workflow_GoOutRepository();
        private readonly Rb_Workflow_CopyToPeopleRepository copyToPeopleRepository = new Rb_Workflow_CopyToPeopleRepository();
        private readonly Rb_Workflow_SignInRepository SignInModule = new Rb_Workflow_SignInRepository();


        #region OA
        /// <summary>
        /// 根据员工id获取审批模板
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Template_Extend> GetTemplateByEmpId(int empId)
        {
            return workFlowTemplateRepository.GetTemplateByEmpId(empId);
        }


        #region 获取审批信息
        /// <summary>
        /// 获取请假信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Rb_Workflow_Askforleave GetAskforleave(int id)
        {
            return askforleaveRepository.GetEntity(id);
        }
        /// <summary>
        /// 获取出差信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Rb_Workflow_Evection GetEvection(int id)
        {
            return wfEvectionRepository.GetEntity(id);
        }
        /// <summary>
        /// 获取出差行程信息
        /// </summary>
        /// <param name="eveId"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Travel_Extend> GetTravelList(int eveId)
        {
            return wfTravelRepository.GetTravelListForEvection(eveId);
        }
        /// <summary>
        /// 获取外出信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Rb_Workflow_GoOut GetGoOut(int id)
        {
            return wfGoOutRepository.GetEntity(id);
        }
        /// <summary>
        /// 获取补卡信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Rb_Workflow_Reissuecard GetReissuecard(int id)
        {
            return wfReissuecardRepository.GetEntity(id);
        }
        #endregion

        #region 提交申请

        #region 获取时长

        /// <summary>
        /// 获取午休时间
        /// </summary>
        /// <param name="RB_Group_id"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetLunchTime(int RB_Group_id, string key)
        {
            var list = rb_DictvalueRepository.GetList(new RB_Dictvalue_Extend() { RB_Group_id = RB_Group_id, DictKey = key });
            if (list.Count > 0)
            {
                return list.FirstOrDefault()?.Content;
            }
            return "";
        }

        /// <summary>
        /// 获取时长
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="templateId">模板id</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="LunchTime">结束时间</param>
        /// <returns></returns>
        public object CalculateDuration(int empId, int? templateId, DateTime startTime, DateTime endTime, string LunchTime)
        {
            double TotalLunch = 0;
            double LunchT = 0;
            if (!string.IsNullOrWhiteSpace(LunchTime))
            {
                string LTimeStart = LunchTime.Split('-')[0];
                string LTimeEnd = LunchTime.Split('-')[1];
                TimeSpan ts = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + LTimeEnd) - Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + LTimeStart);
                LunchT = ts.TotalHours;
                //首先根据开始结束时间  对应的减去午休时间
                string STimeStr = startTime.ToString("yyyy-MM-dd");
                string ETimeStr = endTime.ToString("yyyy-MM-dd");
                //判断请假的开始结束时间是否在午休范围内
                if (STimeStr == ETimeStr)
                {
                    if (startTime > Convert.ToDateTime(STimeStr + " " + LTimeStart) && startTime < Convert.ToDateTime(STimeStr + " " + LTimeEnd) && endTime <= Convert.ToDateTime(ETimeStr + " " + LTimeEnd))
                    {
                        startTime = Convert.ToDateTime(STimeStr + " " + LTimeStart);
                    }
                    if (startTime > Convert.ToDateTime(STimeStr + " " + LTimeStart) && startTime < Convert.ToDateTime(STimeStr + " " + LTimeEnd) && endTime > Convert.ToDateTime(ETimeStr + " " + LTimeEnd))
                    {
                        startTime = Convert.ToDateTime(STimeStr + " " + LTimeEnd);
                    }
                    if (endTime > Convert.ToDateTime(ETimeStr + " " + LTimeStart) && endTime < Convert.ToDateTime(ETimeStr + " " + LTimeEnd) && startTime >= Convert.ToDateTime(STimeStr + " " + LTimeStart))
                    {
                        endTime = Convert.ToDateTime(ETimeStr + " " + LTimeEnd);
                    }
                    if (endTime > Convert.ToDateTime(ETimeStr + " " + LTimeStart) && endTime < Convert.ToDateTime(ETimeStr + " " + LTimeEnd) && startTime < Convert.ToDateTime(STimeStr + " " + LTimeStart))
                    {
                        endTime = Convert.ToDateTime(ETimeStr + " " + LTimeStart);
                    }
                }
                else
                {
                    if (startTime > Convert.ToDateTime(STimeStr + " " + LTimeStart) && startTime < Convert.ToDateTime(STimeStr + " " + LTimeEnd))
                    {
                        startTime = Convert.ToDateTime(STimeStr + " " + LTimeEnd);
                    }
                    if (endTime > Convert.ToDateTime(ETimeStr + " " + LTimeStart) && endTime < Convert.ToDateTime(ETimeStr + " " + LTimeEnd))
                    {
                        endTime = Convert.ToDateTime(ETimeStr + " " + LTimeStart);
                    }
                }
            }
            Rb_Workflow_Template template = new Rb_Workflow_Template();
            if (templateId != null && templateId != 0)
            {
                template = workFlowTemplateRepository.GetEntity(templateId);
            }
            else
            {
                template = workFlowTemplateRepository.GetTempateByTempateType(empId, (int)WFTTemplateTypeEnum.AskForLeave);
            }
            //请假时长（天/小时）
            double dayOrHour = 0;
            if (template != null)
            {
                //获取特殊日期
                List<RB_Technicaldates_Extend> technicalList = technicaldatesRepository.GetSpecialDateList(empId);
                //正常打卡日期
                List<RB_WorkdaySeting_Extend> workDayList = WDrespository.GetWorkDayList(empId);
                int days = StringHelper.GetDateDayInterval(startTime, endTime);
                var empModel = accountRepository.GetEmployeeInfo(empId);
                for (int i = 0; i < days; i++)
                {
                    DateTime currentDate = startTime.AddDays(i);
                    var techlist = technicalList.Where(t => t.Date.Date == currentDate.Date).ToList();
                    //ld   2019-09-26 增加部门  人员筛选
                    RB_Technicaldates_Extend technical = null;
                    if (techlist.Where(x => x.EmployeeId == empId).Any())
                    {
                        technical = techlist.Where(x => x.EmployeeId == empId).FirstOrDefault();
                    }
                    else if (techlist.Where(x => x.RB_Department_Id == empModel.Dept_Id && x.EmployeeId == 0).Any())
                    {
                        technical = techlist.Where(x => x.RB_Department_Id == empModel.Dept_Id && x.EmployeeId == 0).FirstOrDefault();
                    }
                    else
                    {
                        technical = techlist.FirstOrDefault();
                    }
                    if (technical != null)//特殊日期
                    {
                        #region 特殊日期
                        //当天上班时间
                        DateTime onDateTime = Convert.ToDateTime($"{technical.Date.Year}-{technical.Date.Month}-{technical.Date.Day}  {Convert.ToDateTime(technical.BeOnDutyTime).Hour}: {Convert.ToDateTime(technical.BeOnDutyTime).Minute}: {Convert.ToDateTime(technical.BeOnDutyTime).Second}");
                        //当天下班时间
                        DateTime offDateTime = Convert.ToDateTime($"{technical.Date.Year}-{technical.Date.Month}-{technical.Date.Day}  {Convert.ToDateTime(technical.OffDutyTime).Hour}: {Convert.ToDateTime(technical.OffDutyTime).Minute}: {Convert.ToDateTime(technical.OffDutyTime).Second}");
                        dayOrHour = GetDayOrHour(startTime, endTime, template, dayOrHour, currentDate, onDateTime, offDateTime);
                        if (!string.IsNullOrWhiteSpace(LunchTime))
                            GetLunchTime(startTime, endTime, currentDate, LunchTime, LunchT, ref TotalLunch);
                        #endregion
                    }
                    else
                    {
                        RB_WorkdaySeting_Extend workDay = workDayList.Where(t => t.Workday == StringHelper.GetWeek(currentDate.Date)).FirstOrDefault();
                        if (workDay != null)
                        {
                            #region 正常日期
                            //当天上班时间
                            DateTime onDateTime = Convert.ToDateTime($"{currentDate.Date.Year}-{currentDate.Date.Month}-{currentDate.Date.Day}  {Convert.ToDateTime(workDay.BeOnDutyTime).Hour}: {Convert.ToDateTime(workDay.BeOnDutyTime).Minute}: {Convert.ToDateTime(workDay.BeOnDutyTime).Second}");
                            //当天下班时间
                            DateTime offDateTime = Convert.ToDateTime($"{currentDate.Date.Year}-{currentDate.Date.Month}-{currentDate.Date.Day}  {Convert.ToDateTime(workDay.OffDutyTime).Hour}: {Convert.ToDateTime(workDay.OffDutyTime).Minute}: {Convert.ToDateTime(workDay.OffDutyTime).Second}");
                            dayOrHour = GetDayOrHour(startTime, endTime, template, dayOrHour, currentDate, onDateTime, offDateTime);
                            if (!string.IsNullOrWhiteSpace(LunchTime))
                                GetLunchTime(startTime, endTime, currentDate, LunchTime, LunchT, ref TotalLunch);
                            #endregion
                        }
                    }
                }
                if (template.TemplateType != WFTTemplateTypeEnum.Evection)
                {
                    dayOrHour -= TotalLunch;
                }
                return Math.Round(dayOrHour, 2);
            }
            else
            {
                return 0;
            }


        }

        /// <summary>
        /// 获取两个日期间休息的天数
        /// </summary>
        /// <param name="empId">员工id</param>        
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public double GetTimeSpanDays(int empId, DateTime startTime, DateTime endTime)
        {
            double NotWorkTime = 0;
            //获取特殊日期
            List<RB_Technicaldates_Extend> technicalList = technicaldatesRepository.GetSpecialDateList(empId);
            //正常打卡日期
            List<RB_WorkdaySeting_Extend> workDayList = WDrespository.GetWorkDayList(empId);
            //true  上午   false   下午
            bool IsStartMorning = DateTime.Compare(startTime, Convert.ToDateTime(startTime.ToString("yyyy-MM-dd") + " 13:00")) < 0;
            bool IsEndMorning = DateTime.Compare(endTime, Convert.ToDateTime(endTime.ToString("yyyy-MM-dd") + " 13:00")) <= 0;
            int days = StringHelper.GetDateDayInterval(startTime, endTime);
            var empModel = accountRepository.GetEmployeeInfo(empId);
            for (int i = 0; i < days; i++)
            {
                DateTime currentDate = startTime.AddDays(i);
                //RB_Technicaldates_Extend technical = technicalList.Where(t => t.Date.Date == currentDate.Date).FirstOrDefault();
                var techlist = technicalList.Where(t => t.Date.Date == currentDate.Date).ToList();
                //ld   2019-09-26 增加部门  人员筛选
                RB_Technicaldates_Extend technical = null;
                if (techlist.Where(x => x.EmployeeId == empId).Any())
                {
                    technical = techlist.Where(x => x.EmployeeId == empId).FirstOrDefault();
                }
                else if (techlist.Where(x => x.RB_Department_Id == empModel.Dept_Id && x.EmployeeId == 0).Any())
                {
                    technical = techlist.Where(x => x.RB_Department_Id == empModel.Dept_Id && x.EmployeeId == 0).FirstOrDefault();
                }
                else
                {
                    technical = techlist.FirstOrDefault();
                }
                if (technical != null)//特殊日期
                {
                    #region 特殊日期
                    if (technical.Type == 1)
                    {
                        //正常打卡  判断第一天  与 最后一天
                        if (i == 0)
                        {//第一天
                            if (IsStartMorning == false)
                            {
                                NotWorkTime += 0.5;
                            }
                            else if (i == (days - 1) & IsStartMorning == true & IsEndMorning == true)
                            {
                                NotWorkTime += 0.5;
                            }
                        }
                        else if (i == days - 1)
                        {//最后一天
                            if (IsEndMorning == true)
                            {
                                NotWorkTime += 0.5;
                            }
                        }
                    }
                    else
                    {
                        NotWorkTime += 1;
                    }
                    #endregion
                }
                else
                {
                    RB_WorkdaySeting_Extend workDay = workDayList.Where(t => t.Workday == StringHelper.GetWeek(currentDate.Date)).FirstOrDefault();
                    if (workDay != null)
                    {
                        //正常打卡  判断第一天  与 最后一天
                        if (i == 0)
                        {//第一天
                            if (IsStartMorning == false)
                            {
                                NotWorkTime += 0.5;
                            }
                            else if (i == (days - 1) & IsStartMorning == true & IsEndMorning == true)
                            {
                                NotWorkTime += 0.5;
                            }
                        }
                        else if (i == days - 1)
                        {//最后一天
                            if (IsEndMorning == true)
                            {
                                NotWorkTime += 0.5;
                            }
                        }
                    }
                    else
                    {
                        NotWorkTime += 1;
                    }
                }
            }
            return NotWorkTime;
        }

        private static void GetLunchTime(DateTime startTime, DateTime endTime, DateTime currentDate, string LunchTime, double LunchT, ref double TotalLunch)
        {
            if (!string.IsNullOrWhiteSpace(LunchTime))
            {
                string LTimeStart = LunchTime.Split('-')[0];
                string LTimeEnd = LunchTime.Split('-')[1];
                //首先根据开始结束时间  对应的减去午休时间
                string STimeStr = startTime.ToString("yyyy-MM-dd");
                string ETimeStr = endTime.ToString("yyyy-MM-dd");
                string CTimeStr = currentDate.ToString("yyyy-MM-dd");
                if (STimeStr == ETimeStr)
                {
                    //请假在同一天
                    if (startTime <= Convert.ToDateTime(STimeStr + " " + LTimeStart) && Convert.ToDateTime(ETimeStr + " " + LTimeEnd) <= endTime)
                    {
                        TotalLunch = LunchT;
                    }
                }
                else
                {
                    if (CTimeStr != STimeStr && ETimeStr != CTimeStr)
                    {
                        TotalLunch += LunchT;
                    }
                    else if (CTimeStr == STimeStr && ETimeStr != CTimeStr)
                    {//第一天
                        if (startTime <= Convert.ToDateTime(STimeStr + " " + LTimeStart))
                        {
                            TotalLunch += LunchT;
                        }
                    }
                    else if (CTimeStr != STimeStr && ETimeStr == CTimeStr)
                    {//最后一天
                        if (endTime >= Convert.ToDateTime(ETimeStr + " " + LTimeEnd))
                        {
                            TotalLunch += LunchT;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取请假时长
        /// </summary>
        /// <param name="startTime">请假开始时间</param>
        /// <param name="endTime">请假拘束时间</param>
        /// <param name="template">请假模板</param>
        /// <param name="dayOrHour">请假时长</param>
        /// <param name="currentDate">当天日期</param>
        /// <param name="onDateTime">当天上班日期</param>
        /// <param name="offDateTime">当天下班日期</param>
        /// <returns></returns>
        private static double GetDayOrHour(DateTime startTime, DateTime endTime, Rb_Workflow_Template template, double dayOrHour, DateTime currentDate, DateTime onDateTime, DateTime offDateTime)
        {
            //当天工作时长
            double workHour = StringHelper.GetDayTimeSpan(onDateTime, offDateTime).TotalHours;
            if (currentDate.Date == startTime.Date && startTime.Date == endTime.Date)//请假一天
            {
                if (startTime <= onDateTime && endTime >= offDateTime)//考勤时间之外
                {
                    dayOrHour = GetAllDayLong(template, dayOrHour, workHour);
                }
                else if (startTime >= onDateTime && endTime <= offDateTime)//考勤时间之间
                {
                    dayOrHour = GetComputationDayLong(startTime, template, dayOrHour, endTime, workHour);
                }
                else if (startTime <= onDateTime && endTime < offDateTime && endTime >= onDateTime)//结束时间在考勤之间
                {
                    dayOrHour = GetComputationDayLong(onDateTime, template, dayOrHour, endTime, workHour);
                }
                else if (startTime >= onDateTime && endTime >= offDateTime && startTime <= offDateTime)//开始时间在考勤之间
                {
                    dayOrHour = GetComputationDayLong(startTime, template, dayOrHour, offDateTime, workHour);
                }
            }
            else if (currentDate.Date == startTime.Date)//开始时间
            {

                //一整天
                if (startTime < onDateTime)
                {
                    dayOrHour = GetAllDayLong(template, dayOrHour, workHour);
                }
                else if (startTime >= onDateTime && startTime <= offDateTime)
                {
                    dayOrHour = GetComputationDayLong(startTime, template, dayOrHour, offDateTime, workHour);
                }
            }
            else if (currentDate.Date == endTime.Date)//结束时间
            {
                //一整天
                if (endTime > offDateTime)
                {
                    dayOrHour = GetAllDayLong(template, dayOrHour, workHour);
                }
                else if (endTime >= onDateTime && endTime <= offDateTime)
                {
                    dayOrHour = GetComputationDayLong(onDateTime, template, dayOrHour, endTime, workHour);
                }
            }
            else//中间时间
            {
                dayOrHour = GetAllDayLong(template, dayOrHour, workHour);
            }

            return dayOrHour;
        }
        /// <summary>
        /// 获取计算时长
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="template">模板</param>
        /// <param name="dayOrHour">请假时长</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="workHour">当天工作时长</param>
        /// <returns></returns>
        private static double GetComputationDayLong(DateTime startTime, Rb_Workflow_Template template, double dayOrHour, DateTime endTime, double workHour)
        {
            TimeSpan timeSpan = StringHelper.GetDayTimeSpan(startTime, endTime);
            if (template.TemplateType != WFTTemplateTypeEnum.Evection)
            {
                dayOrHour += timeSpan.TotalHours;
            }
            else
            {
                dayOrHour += timeSpan.TotalHours / workHour;
            }

            return dayOrHour;
        }

        /// <summary>
        /// 获取一整天时长
        /// </summary>
        /// <param name="template">模板</param>
        /// <param name="dayOrHour">请假时长</param>
        /// <param name="workHour">当天工作时长</param>
        /// <returns></returns>
        private static double GetAllDayLong(Rb_Workflow_Template template, double dayOrHour, double workHour)
        {
            if (template.TemplateType != WFTTemplateTypeEnum.Evection)
            {
                dayOrHour += workHour;
            }
            else
            {
                dayOrHour += 1;
            }

            return dayOrHour;
        }
        #endregion

        /// <summary>
        /// 提交请假申请
        /// </summary>
        /// <param name="askforleave"></param>
        /// <returns></returns>
        public ApiResult AskForLeaveSubmit(Rb_Workflow_Askforleave_Extend askforleave)
        {
            var emp = accountRepository.GetEmployeeInfo(askforleave.CreateBy ?? 0);
            if (emp != null)
            {
                askforleave.CreateTime = DateTime.Now;
                askforleave.Status = WFAuditStatus.InReview;
                askforleave.RB_BranchId = emp.School_Id;
                askforleave.RB_GroupId = emp.Group_Id;
                askforleave.UpdateBy = emp.Id;
                askforleave.UpdateTime = DateTime.Now;
                askforleave.IsCancel = WFAuditCancelStatus.Normal;
                //两时间段相差天数
                double dayOrHour = askforleave.Duration.GetValueOrDefault();
                //图片处理
                List<string> imgList = new List<string>();
                List<string> oldImgList = new List<string>();
                ImageOperation(askforleave.Images, out imgList);
                askforleave.Image = JsonConvert.SerializeObject(imgList);
                Rb_Workflow_Condition_Extend condition = GetCondition(askforleave.TemplateId.Value, dayOrHour, askforleave.AskforleaveType.Value);
                if (askforleave.AskforleaveType == AskforleaveTypeEnum.AnnualLeave)
                {
                    double AnnualNum = 0;
                    string startT = askforleave.StartTime.Value.ToString("yyyy-MM-dd");
                    string endT = askforleave.EndTime.Value.ToString("yyyy-MM-dd");
                    TimeSpan span = Convert.ToDateTime(endT) - Convert.ToDateTime(startT);
                    AnnualNum = span.Days + 1 - GetTimeSpanDays(askforleave.CreateBy ?? 0, askforleave.StartTime.Value, askforleave.EndTime.Value);
                    if (emp.AnnualLeaveDay < AnnualNum)
                    {
                        return ApiResult.ParamIsNull("年假的天数不够,当前剩余" + emp.AnnualLeaveDay + "天！");
                    }
                }
                //病假必须上传凭证   2019-05-10 新增需求，ld   何娟需求
                if (askforleave.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                {
                    if (imgList.Count() <= 0)
                    {
                        return ApiResult.ParamIsNull("病假需上传证明！");
                    }
                }
                if (condition == null)
                {
                    return ApiResult.Failed("该模板没有审核条件");
                }
                else
                {
                    #region 时间段验重
                    List<Rb_Workflow_Askforleave_Extend> auditTypeList = new List<Rb_Workflow_Askforleave_Extend>();
                    string checkStr = AllAuditValverifyTime(emp.Id, askforleave.StartTime.ToString(), askforleave.EndTime.Value.ToString(), out auditTypeList);
                    //修改
                    if (askforleave.Id > 0)
                    {
                        Rb_Workflow_Askforleave currentAskforleave = askforleaveRepository.GetEntity(askforleave.Id);
                        oldImgList = JsonConvert.DeserializeObject<List<string>>(currentAskforleave.Image);
                        //判断申请审核状态
                        if (currentAskforleave != null && currentAskforleave.Status != WFAuditStatus.InReview)
                        {
                            return ApiResult.Failed(message: "该请假申请不能被修改");
                        }
                        //判断申请时间段有没有被其他申请占用
                        if (auditTypeList.Where(t => t.Id != askforleave.Id && t.TemplateType != WFTTemplateTypeEnum.AskForLeave).Count() > 0)
                        {
                            return ApiResult.Failed(message: checkStr);
                        }
                        else
                        {
                            var trans = askforleaveRepository.DbTransaction;
                            try
                            {
                                askforleave.ConditionId = condition.Id;
                                askforleaveRepository.Update(askforleave, trans);
                                //删除节点所有相关信息
                                ModifyAuditDeleteAllInfo(askforleave.Id, (int)WFTTemplateTypeEnum.AskForLeave, trans);
                                //要发送审核消息的账号
                                List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                                //添加审核节点
                                bool success = InsertAuditRelevance(askforleave.CreateBy.Value, askforleave.Id, askforleave.ConditionId.Value, WFTTemplateTypeEnum.AskForLeave, trans, out sendAccount);
                                if (success)
                                {
                                    askforleaveRepository.DBSession.Commit();
                                    PushAuditMessage(sendAccount, askforleave.Id, WFTTemplateTypeEnum.AskForLeave, emp.EmployeeName + "发起请假申请，请尽快审批", "审批通知", askforleave.CreateBy ?? 0, SysTemPushTypeEnum.Audit);
                                    //ThirdCore.Commom.CommonHelper.RemoveNoExitFile(imgList, oldImgList);

                                    return ApiResult.Success("修改成功");
                                }
                                else
                                {
                                    askforleaveRepository.DBSession.Rollback("AskForLeaveSubmit");
                                    return ApiResult.Failed("该流程没有审核人,修改失败");
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "AskForLeaveSubmit");
                                askforleaveRepository.DBSession.Rollback("AskForLeaveSubmit");
                                return ApiResult.Success("修改提交失败");
                            }
                        }
                    }
                    else//新增
                    {
                        if (!checkStr.Equals("ok"))
                        {
                            return ApiResult.Failed(message: checkStr);
                        }
                        else
                        {
                            var trans = askforleaveRepository.DbTransaction;
                            try
                            {
                                askforleave.ConditionId = condition.Id;
                                askforleave.Id = askforleaveRepository.Insert(askforleave.RefMapperTo<Rb_Workflow_Askforleave>(), trans);
                                //要发送审核消息的账号
                                List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                                //添加审核节点
                                bool success = InsertAuditRelevance(askforleave.CreateBy.Value, askforleave.Id, askforleave.ConditionId.Value, WFTTemplateTypeEnum.AskForLeave, trans, out sendAccount);
                                if (success)
                                {

                                    askforleaveRepository.DBSession.Commit();
                                    PushAuditMessage(sendAccount, askforleave.Id, WFTTemplateTypeEnum.AskForLeave, emp.EmployeeName + "发起请假申请，请尽快审批", "审批通知", askforleave.CreateBy ?? 0, SysTemPushTypeEnum.Audit);
                                    return ApiResult.Success("申请提交成功");
                                }
                                else
                                {
                                    askforleaveRepository.DBSession.Rollback("AskForLeaveSubmit");
                                    return ApiResult.Failed("该流程没有审核人,申请失败");
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "AskForLeaveSubmit");
                                askforleaveRepository.DBSession.Rollback("AskForLeaveSubmit");
                                return ApiResult.Success("申请提交失败");
                            }
                        }
                    }

                    #endregion
                }
            }
            else
            {
                return ApiResult.Failed("你的账号异常");
            }
        }
        /// <summary>
        /// 提交出差申请
        /// </summary>
        /// <param name="evection">出差数据</param>
        /// <returns></returns>
        public ApiResult EvectionSubmit(Rb_Workflow_Evection_Extend evection)
        {
            var emp = accountRepository.GetEmployeeInfo(evection.CreateBy ?? 0);
            if (emp != null)
            {
                evection.CreateTime = DateTime.Now;
                evection.Status = WFAuditStatus.InReview;
                evection.RB_BranchId = emp.School_Id;
                evection.RB_GroupId = emp.Group_Id;
                evection.UpdateBy = emp.Id;
                evection.UpdateTime = DateTime.Now;
                evection.IsCancel = WFAuditCancelStatus.Normal;
                //出差时间
                double dayOrHour = evection.Traveldays.Value;
                Rb_Workflow_Condition_Extend condition = GetCondition(evection.TemplateId.Value, dayOrHour, AskforleaveTypeEnum.AffairLeave);
                if (condition == null)
                {
                    return ApiResult.Failed("该模板没有审核条件");
                }
                else
                {
                    #region 时间段验重
                    DateTime endTime = new DateTime(2000, 1, 1);
                    foreach (var item in evection.Travel)
                    {
                        //多个行程时间段合理验证
                        if (item.StartTime <= endTime)
                        {
                            return ApiResult.Failed(message: "时段设置不合理");
                        }
                        endTime = item.EndTime.Value;
                        List<Rb_Workflow_Askforleave_Extend> auditTypeList = new List<Rb_Workflow_Askforleave_Extend>();
                        string checkStr = AllAuditValverifyTime(emp.Id, item.StartTime.ToString(), item.EndTime.Value.ToString(), out auditTypeList);
                        //排除自己占有时间
                        if (evection.Id > 0)
                        {
                            if (auditTypeList.Where(t => t.Id != evection.Id && t.TemplateType != WFTTemplateTypeEnum.Evection).Count() > 0)
                            {
                                return ApiResult.Failed(message: checkStr);
                            }
                        }
                        else
                        {
                            if (!checkStr.Equals("ok"))
                            {
                                return ApiResult.Failed(message: checkStr);
                            }
                        }

                    }
                    #endregion

                    evection.ConditionId = condition.Id;
                    //修改
                    if (evection.Id > 0)
                    {
                        Rb_Workflow_Evection currentEvection = wfEvectionRepository.GetEntity(evection.Id);
                        //判断申请审核状态
                        if (currentEvection != null && currentEvection.Status != WFAuditStatus.InReview)
                        {
                            return ApiResult.Failed(message: "该外出申请不能被修改");
                        }
                        var trans = wfEvectionRepository.DbTransaction;
                        try
                        {
                            wfEvectionRepository.Update(evection.RefMapperTo<Rb_Workflow_Evection>(), trans);
                            #region 删除原行程
                            IList<WhereHelper> whereHelpers = new List<WhereHelper>
                            {
                                new WhereHelper()
                                {
                                    FiledName = nameof(Rb_Workflow_Travel.EvectionId),
                                    FiledValue = evection.Id,
                                    OperatorEnum = OperatorEnum.Equal
                                }
                            };
                            wfTravelRepository.Delete(whereHelpers, trans);
                            #endregion
                            #region 添加新行程
                            List<Rb_Workflow_Travel> travelList = evection.Travel;
                            for (int i = 0; i < travelList.Count(); i++)
                            {
                                travelList[i].Sort = i + 1;
                                travelList[i].EvectionId = evection.Id;
                            }
                            wfTravelRepository.InsertBatch(travelList, trans);
                            #endregion
                            //删除节点所有相关信息
                            ModifyAuditDeleteAllInfo(evection.Id, (int)WFTTemplateTypeEnum.Evection, trans);
                            //要发送审核消息的账号
                            List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                            //添加审核节点
                            bool success = InsertAuditRelevance(evection.CreateBy.Value, evection.Id, evection.ConditionId.Value, WFTTemplateTypeEnum.Evection, trans, out sendAccount);
                            if (success)
                            {
                                wfEvectionRepository.DBSession.Commit();
                                PushAuditMessage(sendAccount, evection.Id, WFTTemplateTypeEnum.Evection, emp.EmployeeName + "发起出差申请，请尽快审批", "审批通知", evection.CreateBy, SysTemPushTypeEnum.Audit);
                                return ApiResult.Success("出差修改提交成功");
                            }
                            else
                            {
                                wfEvectionRepository.DBSession.Rollback("EvectionSubmit");
                                return ApiResult.Failed("该流程没有审核人,修改失败");
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "EvectionSubmit");
                            wfEvectionRepository.DBSession.Rollback("EvectionSubmit");
                            return ApiResult.Success("出差修改提交失败");
                        }
                    }
                    else//新增
                    {
                        var trans = wfEvectionRepository.DbTransaction;
                        try
                        {
                            evection.Id = wfEvectionRepository.Insert(evection.RefMapperTo<Rb_Workflow_Evection>(), trans);
                            List<Rb_Workflow_Travel> travelList = evection.Travel;
                            for (int i = 0; i < travelList.Count(); i++)
                            {
                                travelList[i].Sort = i + 1;
                                travelList[i].EvectionId = evection.Id;
                            }
                            wfTravelRepository.InsertBatch(travelList, trans);
                            //要发送审核消息的账号
                            List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                            //添加审核节点
                            bool success = InsertAuditRelevance(evection.CreateBy.Value, evection.Id, evection.ConditionId.Value, WFTTemplateTypeEnum.Evection, trans, out sendAccount);
                            if (success)
                            {
                                wfEvectionRepository.DBSession.Commit();
                                PushAuditMessage(sendAccount, evection.Id, WFTTemplateTypeEnum.Evection, emp.EmployeeName + "发起出差申请，请尽快审批", "审批通知", evection.CreateBy, SysTemPushTypeEnum.Audit);
                                return ApiResult.Success("出差申请提交成功");
                            }
                            else
                            {
                                wfEvectionRepository.DBSession.Rollback("EvectionSubmit");
                                return ApiResult.Failed("该流程没有审核人,申请失败");
                            }


                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "EvectionSubmit");
                            wfEvectionRepository.DBSession.Rollback("EvectionSubmit");
                            return ApiResult.Success("出差申请提交失败");
                        }
                    }
                }
            }
            else
            {
                return ApiResult.Failed("你的账号异常");
            }

        }

        /// <summary>
        /// 提交外出申请
        /// </summary>
        /// <param name="goOut">外出数据</param>
        /// <returns></returns>
        public ApiResult GooutSubmit(Rb_Workflow_GoOut_Extend goOut)
        {
            var emp = accountRepository.GetEmployeeInfo(goOut.CreateBy ?? 0);
            if (emp != null)
            {
                goOut.CreateTime = DateTime.Now;
                goOut.Status = WFAuditStatus.InReview;
                goOut.RB_BranchId = emp.School_Id;
                goOut.RB_GroupId = emp.Group_Id;
                goOut.UpdateBy = emp.Id;
                goOut.UpdateTime = DateTime.Now;
                goOut.IsCancel = WFAuditCancelStatus.Normal;
                //出差时间
                double dayOrHour = goOut.Duration.Value;
                //图片处理
                List<string> imgList = new List<string>();
                ImageOperation(goOut.Images, out imgList);
                goOut.Image = JsonConvert.SerializeObject(imgList);
                Rb_Workflow_Condition_Extend condition = GetCondition(goOut.TemplateId.Value, dayOrHour, AskforleaveTypeEnum.AffairLeave);
                if (condition == null)
                {
                    return ApiResult.Failed("该模板没有审核条件");
                }
                else
                {
                    #region 时间段验重
                    List<Rb_Workflow_Askforleave_Extend> auditTypeList = new List<Rb_Workflow_Askforleave_Extend>();
                    string checkStr = AllAuditValverifyTime(emp.Id, goOut.StartTime.ToString(), goOut.EndTime.Value.ToString(), out auditTypeList);
                    #endregion
                    //修改
                    if (goOut.Id > 0)
                    {
                        Rb_Workflow_GoOut currentGoOut = wfGoOutRepository.GetEntity(goOut.Id);
                        List<string> oldImgList = JsonConvert.DeserializeObject<List<string>>(currentGoOut.Image);
                        //判断申请审核状态
                        if (currentGoOut != null && currentGoOut.Status != WFAuditStatus.InReview)
                        {
                            return ApiResult.Failed(message: "该外出申请不能被修改");
                        }
                        //判断申请时间段有没有被其他申请占用
                        if (auditTypeList.Where(t => t.Id != goOut.Id && t.TemplateType != WFTTemplateTypeEnum.Goout).Count() > 0)
                        {
                            return ApiResult.Failed(message: checkStr);
                        }
                        else
                        {
                            var trans = wfGoOutRepository.DbTransaction;
                            try
                            {
                                goOut.ConditionId = condition.Id;
                                wfGoOutRepository.Update(goOut.RefMapperTo<Rb_Workflow_GoOut>(), trans);
                                //删除节点所有相关信息
                                ModifyAuditDeleteAllInfo(goOut.Id, (int)WFTTemplateTypeEnum.Goout, trans);
                                //要发送审核消息的账号
                                List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                                //添加审核节点
                                bool success = InsertAuditRelevance(goOut.CreateBy.Value, goOut.Id, goOut.ConditionId.Value, WFTTemplateTypeEnum.Goout, trans, out sendAccount);
                                if (success)
                                {
                                    wfGoOutRepository.DBSession.Commit();
                                    PushAuditMessage(sendAccount, goOut.Id, WFTTemplateTypeEnum.Goout, emp.EmployeeName + "发起外出申请，请尽快审批", "审批通知", goOut.CreateBy, SysTemPushTypeEnum.Audit);
                                    //ThirdCore.Commom.CommonHelper.RemoveNoExitFile(imgList, oldImgList);
                                    return ApiResult.Success("修改申请提交成功");
                                }
                                else
                                {
                                    wfGoOutRepository.DBSession.Rollback("GooutSubmit");
                                    return ApiResult.Failed("该流程没有审核人,修改失败");
                                }


                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "GooutSubmit");
                                wfGoOutRepository.DBSession.Rollback("GooutSubmit");
                                return ApiResult.Success("申请提交失败");
                            }
                        }
                    }
                    else//新增
                    {
                        if (!checkStr.Equals("ok"))
                        {
                            return ApiResult.Failed(message: checkStr);
                        }
                        else
                        {
                            var trans = wfGoOutRepository.DbTransaction;
                            try
                            {
                                goOut.ConditionId = condition.Id;
                                goOut.Id = wfGoOutRepository.Insert(goOut.RefMapperTo<Rb_Workflow_GoOut>(), trans);
                                //要发送审核消息的账号
                                List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                                //添加审核节点
                                bool success = InsertAuditRelevance(goOut.CreateBy.Value, goOut.Id, goOut.ConditionId.Value, WFTTemplateTypeEnum.Goout, trans, out sendAccount);
                                if (success)
                                {
                                    wfGoOutRepository.DBSession.Commit();
                                    PushAuditMessage(sendAccount, goOut.Id, WFTTemplateTypeEnum.Goout, emp.EmployeeName + "发起外出申请，请尽快审批", "审批通知", goOut.CreateBy, SysTemPushTypeEnum.Audit);
                                    return ApiResult.Success("申请提交成功");
                                }
                                else
                                {
                                    wfGoOutRepository.DBSession.Rollback("GooutSubmit");
                                    return ApiResult.Failed("该流程没有审核人,申请失败");
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "GooutSubmit");
                                wfGoOutRepository.DBSession.Rollback("GooutSubmit");
                                return ApiResult.Success("申请提交失败");
                            }
                        }
                    }
                }

            }
            else
            {
                return ApiResult.Failed("你的账号异常");
            }

        }

        /// <summary>
        /// 提交补卡申请
        /// </summary>
        /// <param name="reissuecard">补卡数据</param>
        /// <returns></returns>
        public ApiResult ReissueCardSubmit(Rb_Workflow_Reissuecard_Extend reissuecard)
        {
            ; var emp = accountRepository.GetEmployeeInfo(reissuecard.CreateBy??0);
            if (emp != null)
            {
                reissuecard.CreateTime = DateTime.Now;
                reissuecard.Status = WFAuditStatus.InReview;
                reissuecard.RB_BranchId = emp.School_Id;
                reissuecard.RB_GroupId = emp.Group_Id;
                reissuecard.UpdateBy = emp.Id;
                reissuecard.UpdateTime = DateTime.Now;
                reissuecard.IsCancel = WFAuditCancelStatus.Normal;
                //图片处理
                List<string> oldImgList = new List<string>();
                ImageOperation(reissuecard.Images, out List<string> imgList);
                reissuecard.Image = JsonConvert.SerializeObject(imgList);
                Rb_Workflow_Condition_Extend condition = GetCondition(reissuecard.TemplateId.Value, 0, AskforleaveTypeEnum.AffairLeave);
                if (condition == null)
                {
                    return ApiResult.Failed("该模板没有审核条件");
                }
                else
                {
                    var trans = wfReissuecardRepository.DbTransaction;
                    try
                    {
                        reissuecard.ConditionId = condition.Id;
                        if (reissuecard.Id > 0)
                        {
                            Rb_Workflow_Reissuecard currentReissuecard = wfReissuecardRepository.GetEntity(reissuecard.Id);
                            oldImgList = JsonConvert.DeserializeObject<List<string>>(currentReissuecard.Image);
                            //判断申请审核状态
                            if (currentReissuecard != null && currentReissuecard.Status != WFAuditStatus.InReview)
                            {
                                wfReissuecardRepository.DBSession.Commit();
                                return ApiResult.Failed(message: "该补卡申请不能被修改");
                            }
                            wfReissuecardRepository.Update(reissuecard.RefMapperTo<Rb_Workflow_Reissuecard>(), trans);
                            //删除节点所有相关信息
                            ModifyAuditDeleteAllInfo(reissuecard.Id, (int)WFTTemplateTypeEnum.ReissueCard, trans);
                        }
                        else
                        {
                            reissuecard.Id = wfReissuecardRepository.Insert(reissuecard.RefMapperTo<Rb_Workflow_Reissuecard>(), trans);
                        }
                        //要发送审核消息的账号
                        List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                        //添加审核节点
                        bool success = InsertAuditRelevance(reissuecard.CreateBy.Value, reissuecard.Id, reissuecard.ConditionId.Value, WFTTemplateTypeEnum.ReissueCard, trans, out sendAccount);
                        if (success)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            PushAuditMessage(sendAccount, reissuecard.Id, WFTTemplateTypeEnum.ReissueCard, emp.EmployeeName + "发起补卡申请，请尽快审批", "审批通知", reissuecard.CreateBy, SysTemPushTypeEnum.Audit);
                            //ThirdCore.Commom.CommonHelper.RemoveNoExitFile(imgList, oldImgList);
                            return ApiResult.Success("操作提交成功");
                        }
                        else
                        {
                            wfReissuecardRepository.DBSession.Rollback("ReissueCardSubmit");
                            return ApiResult.Failed("该流程没有审核人,操作失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write(ex, "ReissueCardSubmit");
                        wfReissuecardRepository.DBSession.Rollback("ReissueCardSubmit");
                        return ApiResult.Success("操作失败");
                    }

                }

            }
            else
            {
                return ApiResult.Failed("你的账号异常");
            }

        }


        /// <summary>
        /// 所有申请验证该时间段是否有重复数据
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="auditTypeList">申请信息</param>
        /// <returns></returns>
        public string AllAuditValverifyTime(int empId, string startTime, string endTime, out List<Rb_Workflow_Askforleave_Extend> auditTypeList)
        {
            auditTypeList = askforleaveRepository.AllAuditValverifyTime(empId, startTime, endTime);
            if (auditTypeList.Count > 0)
            {
                if (auditTypeList.Where(t => t.TemplateType == WFTTemplateTypeEnum.AskForLeave).Count() > 0)
                {
                    return "该时间段内已存在请假申请";
                }
                else if (auditTypeList.Where(t => t.TemplateType == WFTTemplateTypeEnum.Evection).Count() > 0)
                {
                    return "该时间段内已存在出差申请";
                }
                else if (auditTypeList.Where(t => t.TemplateType == WFTTemplateTypeEnum.Goout).Count() > 0)
                {
                    return "该时间段内已存在外出申请";
                }
                else
                {
                    return "ok";
                }
            }
            else
            {
                return "ok";
            }
        }

        /// <summary>
        /// 修改申请删除相关节点所有信息
        /// </summary>
        /// <param name="workFlowId"></param>
        /// <param name="templateType"></param>
        /// <param name="trans">事务连接对象</param>
        private void ModifyAuditDeleteAllInfo(int workFlowId, int templateType, IDbTransaction trans)
        {
            List<Rb_Workflow_AuditRelevance_Extend> auditRelevanceList = auditRelevanceRepository.GetAuditRelevanceList(workFlowId, templateType);
            #region 删除所有审核节点
            {
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditRelevance.WorkFlowId),
                        FiledValue = workFlowId,
                        OperatorEnum = OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditRelevance.TemplateType),
                        FiledValue = templateType,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                auditRelevanceRepository.Delete(whereHelpers, trans);
            }
            #endregion

            #region 删除审核人记录
            {
                #region 删除审核人
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_Auditrecord.WorkFlowId),
                        FiledValue = workFlowId,
                        OperatorEnum = OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_Auditrecord.TemplateType),
                        FiledValue = templateType,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                auditrecordRepository.Delete(whereHelpers, trans);
                #endregion
            }
            #endregion

            #region 删除指定成员关联信息
            foreach (var item in auditRelevanceList)
            {
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditUserRelevance.AuditRelevanceId),
                        FiledValue = item.Id,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                auditUserRelevanceRepository.Delete(whereHelpers, trans);
            }
            #endregion

            #region 删除抄送人
            {
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditRelevance.WorkFlowId),
                        FiledValue = workFlowId,
                        OperatorEnum = OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditRelevance.TemplateType),
                        FiledValue = templateType,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                copyToPeopleRepository.Delete(whereHelpers, trans);
            }
            #endregion
        }

        /// <summary>
        /// 图片表单上传处理
        /// </summary>
        /// <param name="images">上传图片</param>
        /// <param name="imgList">处理后图片地址</param>
        private static void ImageOperation(string[] images, out List<string> imgList)
        {
            imgList = new List<string>();
            if (images != null && images.Length > 0)
            {
                imgList = images.ToList();
            }
        }

        /// <summary>
        /// 添加拷贝审核节点
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="wfId">工作流id</param>
        /// <param name="conditionId">工作流条件id</param>
        /// <param name="wFTTemplateTypeEnum">工作模板</param>
        /// <param name="trans"></param>
        /// <param name="sendAccount">推送信息账号</param>
        private bool InsertAuditRelevance(int empId, int wfId, int conditionId, WFTTemplateTypeEnum wFTTemplateTypeEnum, System.Data.IDbTransaction trans, out List<EmAccoutIdModel> sendAccount)
        {
            sendAccount = new List<EmAccoutIdModel>();
            List<Rb_Workflow_Audit_Extend> auditList = wfAuditRepository.GetDefaultAudit(conditionId);
            List<Rb_Workflow_AuditRelevance> auditRelevanceList = new List<Rb_Workflow_AuditRelevance>();
            //首先查询出来 是否是部门负责人
            var empModel = accountRepository.GetEmployeeInfo(empId);
            if (empModel == null)
            {
                return false;
            }
            #region 拷贝审核节点
            if (auditList.Count > 0)
            {
                var depModel = departmentRepository.GetEntity(empModel.Dept_Id);
                if (depModel == null)
                {
                    return false;
                }
                if (("," + depModel.ManagerIds + ",").Contains("," + empId + ","))
                {//说明他是部门的负责人   需要遍历出所有直属主管审核  改成第二级 ，如果有第二级  就干掉，
                 //找出直属主管审批

                    int roleinNum = 2;
                    //查询第二级主管是否制单人  是的话  找第三级主管
                    var dep2 = departmentRepository.GetEntity(depModel.ParentId);
                    if (dep2 != null && ("," + dep2.ManagerIds + ",").Contains("," + empId + ","))
                    {
                        roleinNum = 3;
                        //查询第三级主管是否制单人   是的话  找第四级主管
                        var dep3 = departmentRepository.GetEntity(dep2.ParentId);
                        if (dep3 != null && ("," + dep3.ManagerIds + ",").Contains("," + empId + ","))
                        {
                            roleinNum = 4;
                            var dep4 = departmentRepository.GetEntity(dep3.ParentId);
                            if (dep4 != null && ("," + dep4.ManagerIds + ",").Contains("," + empId + ","))
                            {
                                roleinNum = 5;
                                var dep5 = departmentRepository.GetEntity(dep4.ParentId);
                                if (dep5 != null && ("," + dep5.ManagerIds + ",").Contains("," + empId + ","))
                                {
                                    roleinNum = 6;
                                }
                            }
                        }
                    }

                    var AuditDirectorList = auditList.Where(x => x.AuditType == (int)WFTAuditTypeEnum.Director && x.RoleOrInitiator == 1).ToList();
                    if (AuditDirectorList.Count > 0)
                    {
                        //需要 直属主管审核  改成第二级 ，如果有第二级  就干掉，排除掉小级审批的
                        var AuditDirectorTwoList = auditList.Where(x => x.AuditType == (int)WFTAuditTypeEnum.Director && x.RoleOrInitiator > 1 && x.RoleOrInitiator <= roleinNum).ToList();
                        if (AuditDirectorTwoList.Count > 0)
                        {
                            //有下级部门审批  直接删除直接主管审批
                            List<int> AIDArr = AuditDirectorTwoList.Select(x => x.Id).ToList();
                            auditList = auditList.Where(x => !AIDArr.Contains(x.Id)).ToList();
                        }

                        //需要只留一条数据
                        var auditModel = AuditDirectorList[0];
                        auditModel.RoleOrInitiator = roleinNum;
                        if (AuditDirectorList.Count > 1)
                        {
                            List<int> AIDArr = AuditDirectorList.Where(x => x.Id != auditModel.Id).Select(x => x.Id).ToList();
                            auditList = auditList.Where(x => !AIDArr.Contains(x.Id)).ToList();
                        }
                    }
                }
                auditList = auditList.OrderBy(x => x.Sort).ToList();

                //添加拷贝审核节点
                foreach (var item in auditList)
                {
                    Rb_Workflow_AuditRelevance auditRelevance = item.RefMapperTo<Rb_Workflow_AuditRelevance>();
                    auditRelevance.WorkFlowId = wfId;
                    auditRelevance.AuditType = (WFTAuditTypeEnum)item.AuditType.Value;
                    auditRelevance.TemplateType = wFTTemplateTypeEnum;
                    auditRelevance.OriginalAuditId = item.Id;
                    auditRelevance.Stauts = WFRrocessStatus.NotAudit;
                    auditRelevance.AuditWay = (WFTAuditWayEnum)item.AuditWay;
                    auditRelevance.Id = auditRelevanceRepository.Insert(auditRelevance, trans);
                    auditRelevanceList.Add(auditRelevance);
                    //添加审核节点指定审核成员
                    if (auditRelevance.AuditType == WFTAuditTypeEnum.SpecifiedMember)
                    {
                        List<Rb_Workflow_Audituser_Extend> audituserList = auditUserRepository.GetConditionAuditUser(item.Id);
                        if (audituserList.Count > 0)
                        {
                            List<Rb_Workflow_AuditUserRelevance> audituserRelevanceList = new List<Rb_Workflow_AuditUserRelevance>();
                            foreach (var audituser in audituserList)
                            {
                                Rb_Workflow_AuditUserRelevance auditUserRelevance = audituser.RefMapperTo<Rb_Workflow_AuditUserRelevance>();
                                auditUserRelevance.AuditRelevanceId = auditRelevance.Id;
                                audituserRelevanceList.Add(auditUserRelevance);
                            }
                            auditUserRelevanceRepository.InsertBatch(audituserRelevanceList, trans);
                        }
                    }
                }
            }
            else//申请拒绝
            {
                return false;
            }
            #endregion

            #region 添加初始审核人
            if (auditRelevanceList.Count > 0)
            {
                Rb_Workflow_AuditRelevance auditRelevance = auditRelevanceList.OrderBy(t => t.Sort).FirstOrDefault();
                //部门负责人审核
                if (auditRelevance.AuditType == WFTAuditTypeEnum.Director)
                {
                    var empList = GetEmployeeByDeptTierModule(new Employee_ViewModel() { DeptTier = auditRelevance.RoleOrInitiator ?? 0, Dept_Id = empModel.Dept_Id, Group_Id = empModel.Group_Id });
                    if (empList.Any())
                    {
                        List<int> empIds = empList.Select(x => x.Id).ToList();
                        InsertBatcheAuditRecord(empIds, wfId, wFTTemplateTypeEnum, trans, auditRelevance);
                        foreach (var item in empList)
                        {
                            sendAccount.Add(new EmAccoutIdModel() { EmAccount = item.Account, EmployeeId = item.Id });
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (auditRelevance.AuditType == WFTAuditTypeEnum.Role)//角色审核
                {
                    var empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Post_Id = auditRelevance.RoleOrInitiator ?? 0, Group_Id = empModel.Group_Id });
                    if (empList.Count > 0)
                    {
                        List<int> empIds = empList.Select(t => t.Id).ToList();
                        sendAccount = empList.Select(t => new EmAccoutIdModel() { EmAccount = t.Account, EmployeeId = t.Id }).ToList();
                        InsertBatcheAuditRecord(empIds, wfId, wFTTemplateTypeEnum, trans, auditRelevance);
                    }
                    else
                    {
                        return false;
                    }

                }
                else if (auditRelevance.AuditType == WFTAuditTypeEnum.SpecifiedMember)//指定人审核
                {
                    List<Rb_Workflow_Audituser_Extend> audituserList = auditUserRepository.GetConditionAuditUser(auditRelevance.OriginalAuditId.Value);
                    if (audituserList.Count > 0)
                    {
                        List<int> empIds = audituserList.Select(t => t.EmployeeId.Value).ToList();
                        sendAccount = audituserList.Select(t => new EmAccoutIdModel() { EmAccount = t.EmLoginMobile, EmployeeId = t.EmployeeId ?? 0 }).ToList();
                        InsertBatcheAuditRecord(empIds, wfId, wFTTemplateTypeEnum, trans, auditRelevance);
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            #endregion

            #region 添加抄送人
            List<Rb_Workflow_Audituser_Extend> aduitUserList = auditUserRepository.GetDefaultAuditUser(conditionId);
            if (aduitUserList.Count > 0)
            {

                List<Rb_Workflow_CopyToPeople> copyToPeopleList = new List<Rb_Workflow_CopyToPeople>();
                foreach (var item in aduitUserList)
                {
                    Rb_Workflow_CopyToPeople copyToPeople = new Rb_Workflow_CopyToPeople
                    {
                        EmployeeId = item.EmployeeId,
                        ReadStauts = 1,
                        Stauts = WFRrocessStatus.NotAudit,
                        WorkFlowId = wfId,
                        TemplateType = wFTTemplateTypeEnum
                    };
                    copyToPeopleList.Add(copyToPeople);
                }
                copyToPeopleRepository.InsertBatch(copyToPeopleList, trans);
            }
            #endregion
            return true;
        }

        /// <summary>
        /// 根据员工部门获取员工列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<Employee_ViewModel> GetEmployeeByDeptTierModule(Employee_ViewModel query)
        {
            List<Employee_ViewModel> employeeList = new List<Employee_ViewModel>();
            //获取当前部门所有的上级部门
            if (query.DeptTier == 1)
            {
                var currentDeptModel = departmentRepository.GetEntity<RB_Department_ViewModel>(query.Dept_Id);
                if (currentDeptModel != null && !string.IsNullOrEmpty(currentDeptModel.ManagerIds))
                {
                    employeeList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
                    {
                        QIds = currentDeptModel.ManagerIds
                    });
                }
            }
            else
            {
                var allDeptList = departmentRepository.GetAllSuperiorDepartmentListRepository(query.Dept_Id);
                var subList = allDeptList.Where(qitem => qitem.DeptTier == (query.DeptTier - 1));
                if (subList != null && subList.Count() > 0)
                {
                    string managerIds = "0";
                    foreach (var item in subList)
                    {
                        if (!string.IsNullOrEmpty(item.ManagerIds))
                        {
                            managerIds += "," + item.ManagerIds;
                        }
                    }
                    if (!string.IsNullOrEmpty(managerIds))
                    {
                        employeeList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
                        {
                            QIds = managerIds
                        });
                    }
                }
            }
            return employeeList;
        }

        /// <summary>
        /// 批量添加审核人
        /// </summary>
        /// <param name="empIds">审核人id集合</param>
        /// <param name="wfId">工作流id</param>
        /// <param name="wFTTemplateTypeEnum">工作流模板</param>
        /// <param name="trans">事务</param>
        /// <param name="auditRelevance">审核节点</param>
        private void InsertBatcheAuditRecord(List<int> empIds, int wfId, WFTTemplateTypeEnum wFTTemplateTypeEnum, System.Data.IDbTransaction trans, Rb_Workflow_AuditRelevance auditRelevance)
        {
            List<Rb_Workflow_Auditrecord> auditrecordList = new List<Rb_Workflow_Auditrecord>();
            foreach (var item in empIds)
            {
                Rb_Workflow_Auditrecord auditrecord = new Rb_Workflow_Auditrecord
                {
                    AuditEmId = item,
                    AuditId = auditRelevance.Id,
                    AuditStatus = WFRrocessStatus.NotAudit,
                    CreateBy = item,
                    CreateTime = DateTime.Now,
                    UpdateBy = item,
                    UpdateTime = DateTime.Now,
                    TemplateType = wFTTemplateTypeEnum,
                    WorkFlowId = wfId
                };
                auditrecordList.Add(auditrecord);
            }
            auditrecordRepository.InsertBatch(auditrecordList, trans);
            auditRelevance.ToAuditId = string.Join(",", empIds);
            auditRelevanceRepository.Update(auditRelevance, trans);
        }

        /// <summary>
        /// 获取模板条件
        /// </summary>
        /// <param name="templateId">模板id</param>
        /// <param name="dayOrHour">申请时常或天数</param>
        /// <param name="askforleaveTypeEnum">请假类型</param>
        /// <returns></returns>
        private Rb_Workflow_Condition_Extend GetCondition(int templateId, double dayOrHour, AskforleaveTypeEnum askforleaveTypeEnum)
        {
            List<Rb_Workflow_Condition_Extend> conditionList = conditionRepository.GetConditionByTemplateId(templateId).OrderByDescending(t => t.Sort).ToList();
            //找出默认条件
            Rb_Workflow_Condition_Extend condition = conditionList.Where(t => t.Sort == 0).FirstOrDefault();
            foreach (var item in conditionList)
            {
                //请假类型和(天数/小时)同时存在
                if (!string.IsNullOrWhiteSpace(item.AskforleaveType) && item.StartValue != null)
                {
                    //判断请假类型
                    if (item.AskforleaveType.Contains(((int)askforleaveTypeEnum).ToString()))
                    {
                        #region 条件筛选
                        //判断(天数/小时)条件
                        if (item.ConditionType != (int)EquationTypeEnum.InBetween)
                        {
                            if (item.ConditionType == (int)EquationTypeEnum.LessThan && dayOrHour < item.StartValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.ConditionType == (int)EquationTypeEnum.LessThanOrEqualTo && dayOrHour <= item.StartValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.ConditionType == (int)EquationTypeEnum.EqualTo && dayOrHour == item.StartValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.ConditionType == (int)EquationTypeEnum.GreaterThanOrEqualTo && dayOrHour >= item.StartValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.ConditionType == (int)EquationTypeEnum.GreaterThan && dayOrHour > item.StartValue)
                            {
                                condition = item;
                                break;
                            }
                        }
                        else
                        {
                            if (item.StartType == 1 && item.StartValue < dayOrHour && item.EndType == 1 && dayOrHour < item.EndValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.StartType == 1 && item.StartValue < dayOrHour && item.EndType == 2 && dayOrHour <= item.EndValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.StartType == 2 && dayOrHour >= item.StartValue && item.EndType == 1 && dayOrHour < item.EndValue)
                            {
                                condition = item;
                                break;
                            }
                            if (item.StartType == 2 && dayOrHour >= item.StartValue && item.EndType == 2 && dayOrHour <= item.EndValue)
                            {
                                condition = item;
                                break;
                            }
                        }
                        #endregion
                    }
                }
                else if (!string.IsNullOrWhiteSpace(item.AskforleaveType) && item.StartValue == null)//请假类型存在和(天数/小时)不存在
                {
                    //判断请假类型
                    if (item.AskforleaveType.Contains(((int)askforleaveTypeEnum).ToString()))
                    {
                        condition = item;
                        break;
                    }
                }
                else if (string.IsNullOrWhiteSpace(item.AskforleaveType) && item.StartValue != null)//请假类型不存在和(天数/小时)存在
                {
                    #region 条件筛选
                    //判断(天数/小时)条件
                    if (item.ConditionType != (int)EquationTypeEnum.InBetween)
                    {
                        if (item.ConditionType == (int)EquationTypeEnum.LessThan && dayOrHour < item.StartValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.ConditionType == (int)EquationTypeEnum.LessThanOrEqualTo && dayOrHour <= item.StartValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.ConditionType == (int)EquationTypeEnum.EqualTo && dayOrHour == item.StartValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.ConditionType == (int)EquationTypeEnum.GreaterThanOrEqualTo && dayOrHour >= item.StartValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.ConditionType == (int)EquationTypeEnum.GreaterThan && dayOrHour > item.StartValue)
                        {
                            condition = item;
                            break;
                        }
                    }
                    else
                    {
                        if (item.StartType == 1 && item.StartValue < dayOrHour && item.EndType == 1 && dayOrHour < item.EndValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.StartType == 1 && item.StartValue < dayOrHour && item.EndType == 2 && dayOrHour <= item.EndValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.StartType == 2 && dayOrHour >= item.StartValue && item.EndType == 1 && dayOrHour < item.EndValue)
                        {
                            condition = item;
                            break;
                        }
                        if (item.StartType == 2 && dayOrHour >= item.StartValue && item.EndType == 2 && dayOrHour <= item.EndValue)
                        {
                            condition = item;
                            break;
                        }
                    }
                    #endregion
                }
            }

            return condition;
        }
        #endregion

        #region 获取审核详情信息
        /// <summary>
        /// 根据id获取请假数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Rb_Workflow_Askforleave_Extend GetAskforleaveModel(int Id)
        {
            return askforleaveRepository.GetModel(Id);
        }
        /// <summary>
        /// 根据id获取出差数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Rb_Workflow_Evection_Extend GetEvectionModel(int Id)
        {
            return wfEvectionRepository.GetModel(Id);
        }
        /// <summary>
        /// 根据id获取外出数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Rb_Workflow_GoOut_Extend GetGooutModel(int Id)
        {
            return wfGoOutRepository.GetModel(Id);
        }
        /// <summary>
        /// 根据id获取补卡数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Rb_Workflow_Reissuecard_Extend GetReissuecarModel(int Id)
        {
            return wfReissuecardRepository.GetModel(Id);
        }

        /// <summary>
        /// 通过工作流id 和 模版类型  获取审核记录
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <returns></returns>
        public List<Rb_Workflow_AuditRelevance_Extend> GetAuditRecordList(int WorkFlowId, int TemplateType)
        {
            List<Rb_Workflow_AuditRelevance_Extend> arList = auditRelevanceRepository.GetAuditRelevanceList(WorkFlowId, TemplateType);
            List<Rb_Workflow_Auditrecord_Extend> aurList = auditrecordRepository.GetAuditRecordList(WorkFlowId, TemplateType);
            List<Rb_Workflow_AuditRelevance_Extend> RList = new List<Rb_Workflow_AuditRelevance_Extend>();
            var arAuditList = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough || x.Stauts == WFRrocessStatus.AuditThrough).OrderBy(x => x.Sort).ToList();
            foreach (var item in arAuditList)
            {
                var RecordList = aurList.Where(x => x.AuditId == item.Id && (x.AuditStatus == WFRrocessStatus.AuditThrough || x.AuditStatus == WFRrocessStatus.AuditNotThrough)).ToList();
                if (RecordList.Count > 0)
                {//表示已经审核  或者 即将审核  或者  驳回的
                    item.AuditRecordList = RecordList;
                    RList.Add(item);
                }
            }
            int NotThroughCount = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough).Count();
            if (NotThroughCount <= 0)//状态为审核中  或者已审核完毕
            {
                var listToAudit = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit && x.ToAuditId != "" && x.ToAuditId != null).OrderBy(x => x.Sort).ToList();
                if (listToAudit.Count > 0)
                {
                    var ToAuditModel = listToAudit[0];//获取当前审核
                    string ToauditId = ToAuditModel.ToAuditId;//获取该流程所有的审核人;
                    if (string.IsNullOrWhiteSpace(ToauditId))
                    {//暂无审核人
                        var rlist = new List<Rb_Workflow_Auditrecord_Extend>();
                        Rb_Workflow_Auditrecord_Extend arm = new Rb_Workflow_Auditrecord_Extend()
                        {
                            AuditEmId = 0,
                            AuditEmName = "暂无审核人",
                            AuditEmPhoto = "",
                            AuditStatus = WFRrocessStatus.Rejected,
                            Description = "",
                            Image = "[]",
                            UpdateTime = DateTime.Now,
                            CareOfRemarks = ""
                        };
                        rlist.Add(arm);
                        ToAuditModel.AuditRecordList = rlist;
                    }
                    else
                    {
                        //获取到所有的待审核人
                        List<int> ToAuditList = JsonConvert.DeserializeObject<List<int>>("[" + ToauditId + "]");
                        var RecordList = aurList.Where(x => x.AuditId == ToAuditModel.Id && (x.AuditStatus == WFRrocessStatus.AuditThrough || x.AuditStatus == WFRrocessStatus.AuditNotThrough || x.AuditStatus == WFRrocessStatus.NotAudit)).ToList();
                        foreach (int auid in ToAuditList)
                        {
                            var rcountList = RecordList.Where(x => x.AuditEmId == auid).ToList();
                            if (rcountList.Count <= 0)
                            {
                                var emodel = accountRepository.GetEmployeeInfo(auid);
                                if (emodel != null)
                                {
                                    Rb_Workflow_Auditrecord_Extend arm = new Rb_Workflow_Auditrecord_Extend()
                                    {
                                        AuditEmId = emodel.Id,
                                        AuditEmName = emodel.EmployeeName,
                                        AuditEmPhoto = emodel.UserIcon,
                                        AuditStatus = WFRrocessStatus.NotAudit,
                                        Description = "",
                                        Image = "[]",
                                        UpdateTime = DateTime.Now,
                                        CareOfRemarks = ""
                                    };
                                    RecordList.Add(arm);
                                }
                                else
                                {
                                    Rb_Workflow_Auditrecord_Extend arm = new Rb_Workflow_Auditrecord_Extend()
                                    {
                                        AuditEmId = 0,
                                        AuditEmName = "审核人不存在",
                                        AuditEmPhoto = "",
                                        AuditStatus = WFRrocessStatus.Rejected,
                                        Description = "",
                                        Image = "[]",
                                        UpdateTime = DateTime.Now,
                                        CareOfRemarks = ""
                                    };
                                    RecordList.Add(arm);
                                }
                            }
                        }
                        ToAuditModel.AuditRecordList = RecordList;
                    }
                    RList.Add(ToAuditModel);
                }
            }
            return RList;
        }
        /// <summary>
        /// 获取抄送人列表
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <returns></returns>
        public List<Rb_Workflow_CopyToPeople_Extend> GetCopyToPeopleList(int WorkFlowId, int TemplateType)
        {
            return copyToPeopleRepository.GetCopyToPeopleList(WorkFlowId, TemplateType);
        }
        /// <summary>
        /// 获取该申请单下的所有审核步骤
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <returns></returns>
        public List<Rb_Workflow_AuditRelevance_Extend> GetRelevanceForAuditList(int WorkFlowId, int TemplateType)
        {
            return auditRelevanceRepository.GetAuditRelevanceList(WorkFlowId, TemplateType);
        }
        /// <summary>
        /// 获取该申请单下所有的审核详情
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Auditrecord_Extend> GetRecordForAuditList(int WorkFlowId, int TemplateType)
        {
            return auditrecordRepository.GetAuditRecordList(WorkFlowId, TemplateType);
        }

        /// <summary>
        /// 获取出差下的所有行程
        /// </summary>
        /// <param name="EveId"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Travel_Extend> GetTravelListForEvection(int EveId)
        {
            return wfTravelRepository.GetTravelListForEvection(EveId);
        }

        /// <summary>
        /// 审核  同意
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <param name="empId"></param>
        /// <param name="Description"></param>
        /// <param name="ImageStr"></param>
        /// <returns></returns>
        public ApiResult SetConsent(int WorkFlowId, int TemplateType, int empId, string Description, string ImageStr)
        {
            var trans = wfReissuecardRepository.DbTransaction;
            try
            {
                List<EmAccoutIdModel> AuditAccountList = new List<EmAccoutIdModel>();
                List<EmAccoutIdModel> CopyAccountList = new List<EmAccoutIdModel>();
                //图片处理
                if (!string.IsNullOrWhiteSpace(ImageStr) && ImageStr != "[]")
                {
                    List<string> imgList = new List<string>();
                    ImageOperation(JsonConvert.DeserializeObject<string[]>(ImageStr), out imgList);
                    ImageStr = JsonConvert.SerializeObject(imgList);
                }
                //首先更改 审核关联  审核记录
                List<Rb_Workflow_AuditRelevance_Extend> arList = auditRelevanceRepository.GetAuditRelevanceList(WorkFlowId, TemplateType);
                List<Rb_Workflow_Auditrecord_Extend> aurList = auditrecordRepository.GetAuditRecordList(WorkFlowId, TemplateType);
                //找出当前审核
                int Notcount = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough).Count();
                if (Notcount > 0)
                {
                    wfReissuecardRepository.DBSession.Commit();
                    return ApiResult.Failed("该申请单已被拒绝！");
                }
                var ToAuditFlow = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit).OrderBy(x => x.Sort).ToList();
                if (ToAuditFlow.Count <= 0)
                {
                    wfReissuecardRepository.DBSession.Commit();
                    return ApiResult.Failed("该申请单审核已经完结！");
                }
                if (ToAuditFlow.Count == 1)//目前审核为最后一步   --------------------------------还需要有更新打卡记录表   抄送人状态更新
                {
                    var model = ToAuditFlow[0];
                    var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();

                    if (model.AuditWay == WFTAuditWayEnum.Countersign)
                    {//会签  所有人必须审核完该流程才算完成
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                        if (amodel == null)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                        }
                        #region 更新审核记录表状态
                        IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                            ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditrecordRepository.Update(fileds, whereHelpers, trans);
                        #endregion

                        int AuditCount = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).Count();
                        if (AuditCount <= 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            //同时  修改  审核记录状态 审核流程 
                            model.Stauts = WFRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + empId;
                            }
                            else
                            {
                                model.AuditedId = empId.ToString();
                            }
                            #region 更新审核关联表状态
                            fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                            whereHelpers = new List<WhereHelper>
                            {
                                new WhereHelper()
                                {
                                    FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                    FiledValue = model.Id,
                                    OperatorEnum = OperatorEnum.Equal
                                }
                            };
                            auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                            #endregion
                            switch (TemplateType)
                            {
                                case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                                    fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Askforleave.Status), WFAuditStatus.Through },
                                    };
                                    whereHelpers = new List<WhereHelper>
                                    {
                                        new WhereHelper()
                                        {
                                            FiledName = nameof(Rb_Workflow_Askforleave.Id),
                                            FiledValue = WorkFlowId,
                                            OperatorEnum = OperatorEnum.Equal
                                        }
                                    };
                                    askforleaveRepository.Update(fileds, whereHelpers, trans);

                                    break;
                                case (int)WFTTemplateTypeEnum.Evection:
                                    fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Evection.Status), WFAuditStatus.Through },
                                    };
                                    whereHelpers = new List<WhereHelper>
                                    {
                                        new WhereHelper()
                                        {
                                            FiledName = nameof(Rb_Workflow_Evection.Id),
                                            FiledValue = WorkFlowId,
                                            OperatorEnum = OperatorEnum.Equal
                                        }
                                    };
                                    wfEvectionRepository.Update(fileds, whereHelpers, trans);
                                    break;
                                case (int)WFTTemplateTypeEnum.Goout:
                                    fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_GoOut.Status), WFAuditStatus.Through },
                                    };
                                    whereHelpers = new List<WhereHelper>
                                    {
                                        new WhereHelper()
                                        {
                                            FiledName = nameof(Rb_Workflow_GoOut.Id),
                                            FiledValue = WorkFlowId,
                                            OperatorEnum = OperatorEnum.Equal
                                        }
                                    };
                                    wfGoOutRepository.Update(fileds, whereHelpers, trans);
                                    break;
                                case (int)WFTTemplateTypeEnum.ReissueCard:
                                    fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Reissuecard.Status), WFAuditStatus.Through },
                                    };
                                    whereHelpers = new List<WhereHelper>
                                    {
                                        new WhereHelper()
                                        {
                                            FiledName = nameof(Rb_Workflow_Reissuecard.Id),
                                            FiledValue = WorkFlowId,
                                            OperatorEnum = OperatorEnum.Equal
                                        }
                                    };
                                    wfReissuecardRepository.Update(fileds, whereHelpers, trans);
                                    break;
                            }
                        }
                        else
                        {
                            //同时  修改  审核记录状态 审核流程 
                            model.Stauts = WFRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + empId;
                            }
                            else
                            {
                                model.AuditedId = empId.ToString();
                            }
                            #region 更新审核关联表状态
                            fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                            whereHelpers = new List<WhereHelper>
                            {
                                new WhereHelper()
                                {
                                    FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                    FiledValue = model.Id,
                                    OperatorEnum = OperatorEnum.Equal
                                }
                            };
                            auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                            #endregion
                        }
                    }
                    else if (model.AuditWay == WFTAuditWayEnum.OrSign)
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                        if (amodel == null)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = WFRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + empId;
                        }
                        else
                        {
                            model.AuditedId = empId.ToString();
                        }
                        #region 更新审核记录表状态
                        IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                            ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditrecordRepository.Update(fileds, whereHelpers, trans);
                        #endregion
                        #region 更新审核关联表状态
                        fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                        whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                FiledValue = model.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                        #endregion

                        var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            foreach (var item in list)
                            {
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.OtherHaveAudit },
                                        { nameof(Rb_Workflow_Auditrecord.Description),Description}
                                    ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                                    ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                        FiledValue = item.Id,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                auditrecordRepository.Update(fileds, whereHelpers, trans);
                            }
                        }
                        switch (TemplateType)
                        {
                            case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Askforleave.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Askforleave.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                askforleaveRepository.Update(fileds, whereHelpers, trans);

                                break;
                            case (int)WFTTemplateTypeEnum.Evection:
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Evection.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Evection.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                wfEvectionRepository.Update(fileds, whereHelpers, trans);
                                break;
                            case (int)WFTTemplateTypeEnum.Goout:
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_GoOut.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_GoOut.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                wfGoOutRepository.Update(fileds, whereHelpers, trans);
                                break;
                            case (int)WFTTemplateTypeEnum.ReissueCard:
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Reissuecard.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Reissuecard.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                wfReissuecardRepository.Update(fileds, whereHelpers, trans);
                                break;
                        }
                    }
                    else
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                        if (amodel == null)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                        }
                        var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("流程配置出错啦！非会签，或签 都只能有一个审核人！");
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = WFRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + empId;
                        }
                        else
                        {
                            model.AuditedId = empId.ToString();
                        }
                        #region 更新审核记录表状态
                        IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                            ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditrecordRepository.Update(fileds, whereHelpers, trans);
                        #endregion
                        #region 更新审核关联表状态
                        fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                        whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                FiledValue = model.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                        #endregion

                        switch (TemplateType)
                        {
                            case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Askforleave.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Askforleave.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                askforleaveRepository.Update(fileds, whereHelpers, trans);

                                break;
                            case (int)WFTTemplateTypeEnum.Evection:
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Evection.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Evection.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                wfEvectionRepository.Update(fileds, whereHelpers, trans);
                                break;
                            case (int)WFTTemplateTypeEnum.Goout:
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_GoOut.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_GoOut.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                wfGoOutRepository.Update(fileds, whereHelpers, trans);
                                break;
                            case (int)WFTTemplateTypeEnum.ReissueCard:
                                fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Reissuecard.Status), WFAuditStatus.Through },
                                    };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Reissuecard.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                wfReissuecardRepository.Update(fileds, whereHelpers, trans);
                                break;
                        }
                    }
                    //更新打卡记录表
                    string Rmsg = UpdateAttendanceRecord(WorkFlowId, TemplateType, empId, trans);
                    if (Rmsg != "")
                    {
                        wfReissuecardRepository.DBSession.Rollback("SetConsent");
                        return ApiResult.Failed(Rmsg);
                    }
                    //更新抄送人状态
                    var CopyToPeopleList = copyToPeopleRepository.GetCopyToPeopleList(WorkFlowId, TemplateType);
                    foreach (var item in CopyToPeopleList)
                    {
                        item.Stauts = WFRrocessStatus.AuditThrough;
                    }
                    CopyAccountList = CopyToPeopleList.Select(x => new EmAccoutIdModel { EmAccount = x.EmLoginMobile, EmployeeId = x.EmployeeId ?? 0 }).Distinct().ToList();
                    copyToPeopleRepository.UpdateBatch(CopyToPeopleList, trans);
                }
                else//同时创建下一步审核  复制审核人到审核关联表   创建审核记录表
                {
                    var model = ToAuditFlow[0];
                    var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();

                    if (model.AuditWay == WFTAuditWayEnum.Countersign)
                    {//会签  所有人必须审核完该流程才算完成
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                        if (amodel == null)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                        }
                        //审核记录状态
                        #region 更新审核记录表状态
                        IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                            ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditrecordRepository.Update(fileds, whereHelpers, trans);
                        #endregion

                        int AuditCount = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).Count();
                        if (AuditCount <= 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            //同时  修改  审核流程 
                            model.Stauts = WFRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + empId;
                            }
                            else
                            {
                                model.AuditedId = empId.ToString();
                            }
                            #region 更新审核关联表状态
                            fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                            whereHelpers = new List<WhereHelper>
                            {
                                new WhereHelper()
                                {
                                    FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                    FiledValue = model.Id,
                                    OperatorEnum = OperatorEnum.Equal
                                }
                            };
                            auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                            #endregion
                            //赋值下一步到审核记录中  并更新这一步的待审核人
                            var modelNext = ToAuditFlow[1];
                            var flag = InsertAuditRelevanceNext(empId, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, modelNext, trans, out AuditAccountList);
                            if (flag == false)
                            {
                                wfReissuecardRepository.DBSession.Rollback("SetConsent_22");
                                return ApiResult.Failed("审核流程不完整无法审核，请联系相关负责人！");
                            }
                        }
                        else
                        {
                            //同时  修改  审核流程 
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + empId;
                            }
                            else
                            {
                                model.AuditedId = empId.ToString();
                            }
                            #region 更新审核关联表状态
                            fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                            whereHelpers = new List<WhereHelper>
                            {
                                new WhereHelper()
                                {
                                    FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                    FiledValue = model.Id,
                                    OperatorEnum = OperatorEnum.Equal
                                }
                            };
                            auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                            #endregion
                        }
                    }
                    else if (model.AuditWay == WFTAuditWayEnum.OrSign)
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                        if (amodel == null)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = WFRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + empId;
                        }
                        else
                        {
                            model.AuditedId = empId.ToString();
                        }
                        #region 更新审核记录表状态
                        IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                            ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditrecordRepository.Update(fileds, whereHelpers, trans);
                        #endregion
                        #region 更新审核关联表状态
                        fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                        whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                FiledValue = model.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                        #endregion

                        var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            foreach (var item in list)
                            {
                                fileds = new Dictionary<string, object>
                                {
                                   { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.OtherHaveAudit },
                                   { nameof(Rb_Workflow_Auditrecord.Description),Description},
                                   { nameof(Rb_Workflow_Auditrecord.Image),ImageStr},
                                   { nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                                };
                                whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                        FiledValue = item.Id,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                                auditrecordRepository.Update(fileds, whereHelpers, trans);
                            }
                        }
                        //赋值下一步到审核记录中  并更新这一步的待审核人
                        var modelNext = ToAuditFlow[1];
                        var flag = InsertAuditRelevanceNext(empId, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, modelNext, trans, out AuditAccountList);
                        if (flag == false)
                        {
                            wfReissuecardRepository.DBSession.Rollback("SetConsent");
                            return ApiResult.Failed("审核流程不完整无法审核，请联系相关负责人！");
                        }
                    }
                    else
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                        if (amodel == null)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                        }
                        var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)
                        {
                            wfReissuecardRepository.DBSession.Commit();
                            return ApiResult.Failed("流程配置出错啦！非会签、或签 都只能有一个审核人！");
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = WFRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + empId;
                        }
                        else
                        {
                            model.AuditedId = empId.ToString();
                        }
                        #region 更新审核记录表状态
                        IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                            ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditrecordRepository.Update(fileds, whereHelpers, trans);
                        #endregion
                        #region 更新审核关联表状态
                        fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                        whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                FiledValue = model.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                        #endregion
                        //赋值下一步到审核记录中  并更新这一步的待审核人
                        var modelNext = ToAuditFlow[1];
                        var flag = InsertAuditRelevanceNext(empId, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, modelNext, trans, out AuditAccountList);
                        if (flag == false)
                        {
                            wfReissuecardRepository.DBSession.Rollback("SetConsent");
                            return ApiResult.Failed("审核流程不完整无法审核，请联系相关负责人！");
                        }
                    }

                }
                wfReissuecardRepository.DBSession.Commit();
                //发送推送信息                
                string EmAccout = "";
                string EmName = "";
                string AskforName = "";
                int EmId = 0;
                switch (TemplateType)
                {
                    case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                        var askm = askforleaveRepository.GetModel(WorkFlowId);
                        EmAccout = askm.EmLoginMobile;
                        EmName = askm.EmName;
                        AskforName = "请假申请";
                        EmId = askm.CreateBy.Value;
                        break;
                    case (int)WFTTemplateTypeEnum.Evection:
                        var evem = wfEvectionRepository.GetModel(WorkFlowId);
                        EmAccout = evem.EmLoginMobile;
                        EmName = evem.EmName;
                        AskforName = "出差申请";
                        EmId = evem.CreateBy.Value;
                        break;
                    case (int)WFTTemplateTypeEnum.Goout:
                        var gooutm = wfGoOutRepository.GetModel(WorkFlowId);
                        EmAccout = gooutm.EmLoginMobile;
                        EmName = gooutm.EmName;
                        AskforName = "外出申请";
                        EmId = gooutm.CreateBy.Value;
                        break;
                    case (int)WFTTemplateTypeEnum.ReissueCard:
                        var reim = wfReissuecardRepository.GetModel(WorkFlowId);
                        EmAccout = reim.EmLoginMobile;
                        EmName = reim.EmName;
                        AskforName = "补卡申请";
                        EmId = reim.CreateBy.Value;
                        break;
                }
                List<EmAccoutIdModel> EmNameList = new List<EmAccoutIdModel>() { new EmAccoutIdModel { EmAccount = EmAccout, EmployeeId = EmId } };
                if (ToAuditFlow.Count == 1)
                {//审批完成
                    PushAuditMessage(EmNameList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您的{AskforName}已完成！", "审批完成", empId, SysTemPushTypeEnum.Audit);
                    //抄送人通知
                    PushAuditMessage(CopyAccountList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"{EmName}发起{AskforName}抄送通知！", "抄送通知", empId, SysTemPushTypeEnum.Audit);
                    //所有审核人
                    AuditAccountList = aurList.Where(x => x.AuditStatus == WFRrocessStatus.AuditThrough && x.AuditEmId != empId).Select(x => new EmAccoutIdModel() { EmAccount = x.EmLoginMobile, EmployeeId = x.AuditEmId ?? 0 }).Distinct().ToList();
                    PushAuditMessage(AuditAccountList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您参与{EmName}发起{AskforName}审核已完成！", "审核完成通知", empId, SysTemPushTypeEnum.Audit);
                }
                else
                {//审批通过
                    PushAuditMessage(EmNameList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您的{AskforName}已被{(accountRepository.GetEmployeeInfo(empId)?.EmployeeName ?? "")}审批通过！", "审批通过", empId, SysTemPushTypeEnum.Audit);
                    //下级审核人通知
                    PushAuditMessage(AuditAccountList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"{EmName}发起{AskforName}，请尽快审批", "审核通知", empId, SysTemPushTypeEnum.Audit);
                }
                return ApiResult.Success("审核成功！");
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("UserModule_SetConsent:WorkFlowId:{0},TemplateType:{1},empId:{2},Description:{3},ImageStr:{4}", WorkFlowId, TemplateType, empId, Description, ImageStr));
                wfReissuecardRepository.DBSession.Rollback("UserModule_SetConsent");
                return ApiResult.Failed("申请提交失败");
            }
        }
        /// <summary>
        /// 更新打卡记录
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <param name="trans"></param>
        /// <param name="empId"></param>
        private string UpdateAttendanceRecord(int WorkFlowId, int TemplateType, int empId, System.Data.IDbTransaction trans)
        {
            string StartTime = "", EndTime = "";
            bool IsStartMorning = true, IsEndMorning = true;
            List<RB_Attendance_Record> ARecordList = new List<RB_Attendance_Record>();
            switch (TemplateType)
            {
                case (int)WFTTemplateTypeEnum.AskForLeave:
                    Rb_Workflow_Askforleave_Extend askmodel = GetAskforleaveModel(WorkFlowId);
                    StartTime = askmodel.StartTime.Value.ToString("yyyy-MM-dd");
                    EndTime = askmodel.EndTime.Value.ToString("yyyy-MM-dd");
                    //true  上午   false   下午
                    IsStartMorning = DateTime.Compare(askmodel.StartTime.Value, Convert.ToDateTime(StartTime + " 13:00")) < 0;
                    IsEndMorning = DateTime.Compare(askmodel.EndTime.Value, Convert.ToDateTime(EndTime + " 13:00")) <= 0;
                    //查询出所有在请假范围里的打卡记录表
                    ARecordList = RecordRepository.GetAttendanceRecordForTimeList(StartTime, EndTime, askmodel.CreateBy.Value);
                    double AnnualNum = 0;
                    Employee_ViewModel emodel = new Employee_ViewModel();
                    if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave)
                    {
                        emodel = accountRepository.GetEmployeeInfo(askmodel.CreateBy ?? 0);
                        string startT = askmodel.StartTime.Value.ToString("yyyy-MM-dd");
                        string endT = askmodel.EndTime.Value.ToString("yyyy-MM-dd");
                        TimeSpan span = Convert.ToDateTime(endT) - Convert.ToDateTime(startT);
                        AnnualNum = span.Days + 1 - GetTimeSpanDays(askmodel.CreateBy ?? 0, askmodel.StartTime.Value, askmodel.EndTime.Value);
                        if (askmodel.IsCancel == WFAuditCancelStatus.Normal && emodel.AnnualLeaveDay < AnnualNum)
                        {
                            return "年假的天数不够！";
                        }
                    }
                    if (askmodel.IsCancel == WFAuditCancelStatus.Cancel)//回滚以前的数据
                    {
                        if (ARecordList.Count > 0)
                        {
                            int num = 0;
                            foreach (var item in ARecordList)
                            {
                                List<RB_Attendance_Record_Extend> listH = new List<RB_Attendance_Record_Extend>();
                                if (!string.IsNullOrEmpty(item.History))
                                {
                                    listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(item.History);
                                    listH = listH.Where(x => x.WorkFlowId == WorkFlowId && x.TemplateType == TemplateType).OrderByDescending(x => x.Date).ToList();
                                }
                                if (listH.Count > 0)
                                {//有可用的撤回
                                    var Hmodel = listH[0];
                                    num++;
                                    if (num == 1)
                                    {
                                        if (IsStartMorning == IsEndMorning && IsStartMorning)
                                        {
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                        }
                                        else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                        {//上午
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                        else
                                        {
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                    }
                                    else if (num == ARecordList.Count)
                                    {
                                        if (IsEndMorning)
                                        {//上午
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                        }
                                        else
                                        {
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                    }
                                    else
                                    {
                                        item.BeOnStatus = Hmodel.BeOnStatus;
                                        item.OffStatus = Hmodel.OffStatus;
                                        item.BeOnRelevance = Hmodel.BeOnRelevance;
                                        item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                        item.OffRelevance = Hmodel.OffRelevance;
                                        item.OffRelevanceType = Hmodel.OffRelevanceType;
                                    }
                                }
                                else
                                {
                                    num++;
                                    if (num == 1)
                                    {
                                        if (IsStartMorning == IsEndMorning && IsStartMorning)
                                        {
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                        }
                                        else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                        {//上午
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                        else
                                        {
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                    }
                                    else if (num == ARecordList.Count)
                                    {
                                        if (IsEndMorning)
                                        {//上午
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                        }
                                        else
                                        {
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                    }
                                    else
                                    {
                                        item.BeOnStatus = AttendanceEnum.QK;
                                        item.OffStatus = AttendanceEnum.QK;
                                        item.BeOnRelevance = null;
                                        item.BeOnRelevanceType = null;
                                        item.OffRelevance = null;
                                        item.OffRelevanceType = null;
                                    }
                                }
                            }
                            RecordRepository.UpdateBatch(ARecordList, trans);
                        }
                        //同时回滚每月请假时长表
                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AffairLeave || askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave || askmodel.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                        {
                            if (askmodel.StartTime.Value.ToString("yyyy-MM") == askmodel.EndTime.Value.ToString("yyyy-MM"))
                            {
                                //请假在一个月里  直接操作加
                                var LTmodel = attendance_LeaveTimeRepository.Get(askmodel.CreateBy.Value, askmodel.StartTime.Value.ToString("yyyy-MM"), (int)askmodel.AskforleaveType);
                                if (LTmodel != null)
                                {
                                    List<LeaveTimeHistory> LTHList = JsonConvert.DeserializeObject<List<LeaveTimeHistory>>(LTmodel.History);
                                    var lthmodel = LTHList.Where(x => x.WorkFlowId == askmodel.Id).FirstOrDefault();
                                    if (lthmodel != null)
                                    {
                                        LTmodel.Duration -= lthmodel.Duration;
                                        LTHList.Remove(lthmodel);
                                        LTmodel.History = JsonConvert.SerializeObject(LTHList);
                                        attendance_LeaveTimeRepository.Update(LTmodel);
                                    }
                                }
                            }
                            else
                            {
                                int num = 1;
                                while (true)
                                {
                                    if (askmodel.StartTime.Value.AddMonths(num).ToString("yyyy-MM") == askmodel.EndTime.Value.ToString("yyyy-MM"))
                                    {
                                        var LTmodel = attendance_LeaveTimeRepository.Get(askmodel.CreateBy.Value, askmodel.StartTime.Value.AddMonths(num - 1).ToString("yyyy-MM"), (int)askmodel.AskforleaveType);
                                        if (LTmodel != null)
                                        {
                                            List<LeaveTimeHistory> LTHList = JsonConvert.DeserializeObject<List<LeaveTimeHistory>>(LTmodel.History);
                                            var lthmodel = LTHList.Where(x => x.WorkFlowId == askmodel.Id).FirstOrDefault();
                                            if (lthmodel != null)
                                            {
                                                LTmodel.Duration -= lthmodel.Duration;
                                                LTHList.Remove(lthmodel);
                                                LTmodel.History = JsonConvert.SerializeObject(LTHList);
                                                attendance_LeaveTimeRepository.Update(LTmodel);
                                            }
                                        }
                                        LTmodel = attendance_LeaveTimeRepository.Get(askmodel.CreateBy.Value, askmodel.StartTime.Value.AddMonths(num).ToString("yyyy-MM"), (int)askmodel.AskforleaveType);
                                        if (LTmodel != null)
                                        {
                                            List<LeaveTimeHistory> LTHList = JsonConvert.DeserializeObject<List<LeaveTimeHistory>>(LTmodel.History);
                                            var lthmodel = LTHList.Where(x => x.WorkFlowId == askmodel.Id).FirstOrDefault();
                                            if (lthmodel != null)
                                            {
                                                LTmodel.Duration -= lthmodel.Duration;
                                                LTHList.Remove(lthmodel);
                                                LTmodel.History = JsonConvert.SerializeObject(LTHList);
                                                attendance_LeaveTimeRepository.Update(LTmodel);
                                            }
                                        }
                                        break;
                                    }
                                    else
                                    {
                                        var LTmodel = attendance_LeaveTimeRepository.Get(askmodel.CreateBy.Value, askmodel.StartTime.Value.AddMonths(num - 1).ToString("yyyy-MM"), (int)askmodel.AskforleaveType);
                                        if (LTmodel != null)
                                        {
                                            List<LeaveTimeHistory> LTHList = JsonConvert.DeserializeObject<List<LeaveTimeHistory>>(LTmodel.History);
                                            var lthmodel = LTHList.Where(x => x.WorkFlowId == askmodel.Id).FirstOrDefault();
                                            if (lthmodel != null)
                                            {
                                                LTmodel.Duration -= lthmodel.Duration;
                                                LTHList.Remove(lthmodel);
                                                LTmodel.History = JsonConvert.SerializeObject(LTHList);
                                                attendance_LeaveTimeRepository.Update(LTmodel);
                                            }
                                        }
                                    }
                                    num++;
                                }
                            }
                        }
                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave && emodel != null)
                        {
                            emodel.AnnualLeaveDay += AnnualNum;
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Account.AnnualLeaveDay),emodel.AnnualLeaveDay}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Account.Id),
                                      FiledValue=emodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            accountRepository.Update(keyValues, wheres, trans);
                        }
                    }
                    else
                    {
                        if (ARecordList.Count > 0)
                        {
                            int num = 0;
                            foreach (var item in ARecordList)
                            {
                                #region//新增历史记录
                                var listH = new List<RB_Attendance_Record_Extend>();
                                var Nmodel = item.RefMapperTo<RB_Attendance_Record_Extend>();
                                Nmodel.TemplateType = TemplateType;
                                Nmodel.WorkFlowId = WorkFlowId;
                                Nmodel.Date = DateTime.Now;
                                if (!string.IsNullOrWhiteSpace(item.History))
                                {//继续追加
                                    listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(item.History);
                                }
                                listH.Add(Nmodel);
                                string History = JsonConvert.SerializeObject(listH.Select(x => new
                                {
                                    x.BeOnDutyTime,
                                    x.BeOnStatus,
                                    x.OffStatus,
                                    x.OffDutyTime,
                                    x.Date,
                                    x.TemplateType,
                                    x.WorkFlowId,
                                    x.BeOnRelevance,
                                    x.BeOnRelevanceType,
                                    x.OffRelevance,
                                    x.OffRelevanceType
                                }));
                                item.History = History;
                                #endregion
                                num++;
                                if (num == 1)
                                {
                                    if (IsStartMorning == IsEndMorning && IsStartMorning)
                                    {
                                        item.BeOnStatus = AttendanceEnum.QJ;
                                        item.BeOnRelevance = askmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                    }
                                    else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                    {//上午
                                        item.BeOnStatus = AttendanceEnum.QJ;
                                        item.OffStatus = AttendanceEnum.QJ;
                                        item.BeOnRelevance = askmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                        item.OffRelevance = askmodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                    }
                                    else
                                    {
                                        item.OffStatus = AttendanceEnum.QJ;
                                        item.OffRelevance = askmodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                    }
                                }
                                else if (num == ARecordList.Count)
                                {
                                    if (IsEndMorning)
                                    {//上午
                                        item.BeOnStatus = AttendanceEnum.QJ;
                                        item.BeOnRelevance = askmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                    }
                                    else
                                    {
                                        item.BeOnStatus = AttendanceEnum.QJ;
                                        item.OffStatus = AttendanceEnum.QJ;
                                        item.BeOnRelevance = askmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                        item.OffRelevance = askmodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                    }
                                }
                                else
                                {
                                    item.BeOnStatus = AttendanceEnum.QJ;
                                    item.OffStatus = AttendanceEnum.QJ;
                                    item.BeOnRelevance = askmodel.Id;
                                    item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                    item.OffRelevance = askmodel.Id;
                                    item.OffRelevanceType = (int)WFTTemplateTypeEnum.AskForLeave;
                                }
                            }
                            RecordRepository.UpdateBatch(ARecordList, trans);
                        }
                        //同时更新每月请假时长表
                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AffairLeave || askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave || askmodel.AskforleaveType == AskforleaveTypeEnum.SickLeave)
                        {
                            if (askmodel.StartTime.Value.ToString("yyyy-MM") == askmodel.EndTime.Value.ToString("yyyy-MM"))
                            {
                                //请假在一个月里  直接操作加
                                var LTmodel = attendance_LeaveTimeRepository.Get(askmodel.CreateBy.Value, askmodel.StartTime.Value.ToString("yyyy-MM"), (int)askmodel.AskforleaveType);
                                if (LTmodel == null)
                                {//新增
                                    RB_Attendance_LeaveTime ltm = new RB_Attendance_LeaveTime()
                                    {
                                        AskforleaveMonth = askmodel.StartTime.Value.ToString("yyyy-MM"),
                                        AskforleaveType = (int)askmodel.AskforleaveType,
                                        EmployeeId = askmodel.CreateBy.Value,
                                        Duration = askmodel.Duration
                                    };
                                    LeaveTimeHistory lth = new LeaveTimeHistory()
                                    {
                                        Duration = askmodel.Duration,
                                        WorkFlowId = askmodel.Id
                                    };
                                    List<LeaveTimeHistory> LTHList = new List<LeaveTimeHistory>
                                    {
                                        lth
                                    };
                                    ltm.History = JsonConvert.SerializeObject(LTHList);
                                    attendance_LeaveTimeRepository.Insert(ltm);
                                }
                                else
                                {
                                    LTmodel.Duration += askmodel.Duration;
                                    List<LeaveTimeHistory> LTHList = JsonConvert.DeserializeObject<List<LeaveTimeHistory>>(LTmodel.History);
                                    LeaveTimeHistory lth = new LeaveTimeHistory()
                                    {
                                        Duration = askmodel.Duration,
                                        WorkFlowId = askmodel.Id
                                    };
                                    LTHList.Add(lth);
                                    LTmodel.History = JsonConvert.SerializeObject(LTHList);
                                    attendance_LeaveTimeRepository.Update(LTmodel);
                                }
                            }
                            else
                            {
                                int num = 1;
                                while (true)
                                {
                                    if (askmodel.StartTime.Value.AddMonths(num).ToString("yyyy-MM") == askmodel.EndTime.Value.ToString("yyyy-MM"))
                                    {
                                        Double DNum1 = 0;
                                        Double DNum2 = 0;
                                        if (num == 1)
                                        {//求出该月的请假时长
                                            DNum1 = Convert.ToDouble(CalculateDuration(askmodel.CreateBy.Value, askmodel.TemplateId, askmodel.StartTime.Value, Convert.ToDateTime(askmodel.StartTime.Value.AddMonths(num).ToString("yyyy-MM") + "-01").AddSeconds(-1), askmodel.LunchTime));
                                        }
                                        else
                                        {
                                            DNum1 = Convert.ToDouble(CalculateDuration(askmodel.CreateBy.Value, askmodel.TemplateId, Convert.ToDateTime(askmodel.StartTime.Value.AddMonths(num - 1).ToString("yyyy-MM") + "-01"), Convert.ToDateTime(askmodel.StartTime.Value.AddMonths(num).ToString("yyyy-MM") + "-01").AddSeconds(-1), askmodel.LunchTime));
                                        }
                                        DNum2 = Convert.ToDouble(CalculateDuration(askmodel.CreateBy.Value, askmodel.TemplateId, Convert.ToDateTime(askmodel.EndTime.Value.ToString("yyyy-MM") + "-01"), askmodel.EndTime.Value, askmodel.LunchTime));
                                        //请假在一个月里  直接操作加
                                        LeaveTimeUpdate(askmodel, num, DNum1);
                                        //最后一个月
                                        LeaveTimeUpdate(askmodel, num, DNum2);
                                        break;
                                    }
                                    else
                                    {
                                        Double DNum = 0;
                                        if (num == 1)
                                        {//求出该月的请假时长
                                            DNum = Convert.ToDouble(CalculateDuration(askmodel.CreateBy.Value, askmodel.TemplateId, askmodel.StartTime.Value, Convert.ToDateTime(askmodel.StartTime.Value.AddMonths(1).ToString("yyyy-MM") + "-01").AddSeconds(-1), askmodel.LunchTime));
                                        }
                                        else
                                        {
                                            DNum = Convert.ToDouble(CalculateDuration(askmodel.CreateBy.Value, askmodel.TemplateId, Convert.ToDateTime(askmodel.StartTime.Value.AddMonths(num - 1).ToString("yyyy-MM") + "-01"), Convert.ToDateTime(askmodel.StartTime.Value.AddMonths(num).ToString("yyyy-MM") + "-01").AddSeconds(-1), askmodel.LunchTime));
                                        }
                                        //请假在一个月里  直接操作加
                                        LeaveTimeUpdate(askmodel, num, DNum);
                                    }
                                    num++;
                                }
                            }
                        }
                        if (askmodel.AskforleaveType == AskforleaveTypeEnum.AnnualLeave && emodel != null)
                        {
                            emodel.AnnualLeaveDay -= AnnualNum;
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Account.AnnualLeaveDay),emodel.AnnualLeaveDay}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Account.Id),
                                      FiledValue=emodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            accountRepository.Update(keyValues, wheres, trans);
                        }
                    }
                    break;
                case (int)WFTTemplateTypeEnum.Evection:
                    Rb_Workflow_Evection_Extend evemodel = GetEvectionModel(WorkFlowId);
                    List<Rb_Workflow_Travel> TravelList = wfTravelRepository.GetTravelList(WorkFlowId);
                    foreach (var trave in TravelList)
                    {
                        StartTime = trave.StartTime.Value.ToString("yyyy-MM-dd");
                        EndTime = trave.EndTime.Value.ToString("yyyy-MM-dd");
                        //true  上午   false   下午
                        IsStartMorning = DateTime.Compare(trave.StartTime.Value, Convert.ToDateTime(StartTime + " 13:00")) < 0;
                        IsEndMorning = DateTime.Compare(trave.EndTime.Value, Convert.ToDateTime(EndTime + " 13:00")) <= 0;
                        //查询出所有在出差范围里的打卡记录表
                        ARecordList = RecordRepository.GetAttendanceRecordForTimeList(StartTime, EndTime, evemodel.CreateBy.Value);
                        if (evemodel.IsCancel == WFAuditCancelStatus.Cancel)//回滚以前的数据
                        {
                            if (ARecordList.Count > 0)
                            {
                                int num = 0;
                                foreach (var item in ARecordList)
                                {
                                    var listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(item.History);
                                    listH = listH.Where(x => x.WorkFlowId == WorkFlowId && x.TemplateType == TemplateType).OrderByDescending(x => x.Date).ToList();
                                    if (listH.Count > 0)
                                    {//有可用的撤回
                                        var Hmodel = listH[0];
                                        num++;
                                        if (num == 1)
                                        {
                                            if (IsStartMorning == IsEndMorning && IsStartMorning)
                                            {
                                                item.BeOnStatus = Hmodel.BeOnStatus;
                                                item.BeOnRelevance = Hmodel.BeOnRelevance;
                                                item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            }
                                            else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                            {//上午
                                                item.BeOnStatus = Hmodel.BeOnStatus;
                                                item.OffStatus = Hmodel.OffStatus;
                                                item.BeOnRelevance = Hmodel.BeOnRelevance;
                                                item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                                item.OffRelevance = Hmodel.OffRelevance;
                                                item.OffRelevanceType = Hmodel.OffRelevanceType;
                                            }
                                            else
                                            {
                                                item.OffStatus = Hmodel.OffStatus;
                                                item.OffRelevance = Hmodel.OffRelevance;
                                                item.OffRelevanceType = Hmodel.OffRelevanceType;
                                            }
                                        }
                                        else if (num == ARecordList.Count)
                                        {
                                            if (IsEndMorning)
                                            {//上午
                                                item.BeOnStatus = Hmodel.BeOnStatus;
                                                item.BeOnRelevance = Hmodel.BeOnRelevance;
                                                item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            }
                                            else
                                            {
                                                item.BeOnStatus = Hmodel.BeOnStatus;
                                                item.OffStatus = Hmodel.OffStatus;
                                                item.BeOnRelevance = Hmodel.BeOnRelevance;
                                                item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                                item.OffRelevance = Hmodel.OffRelevance;
                                                item.OffRelevanceType = Hmodel.OffRelevanceType;
                                            }
                                        }
                                        else
                                        {
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                    }
                                    else
                                    {
                                        num++;
                                        if (num == 1)
                                        {
                                            if (IsStartMorning == IsEndMorning && IsStartMorning)
                                            {
                                                item.BeOnStatus = AttendanceEnum.QK;
                                                item.BeOnRelevance = null;
                                                item.BeOnRelevanceType = null;
                                            }
                                            else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                            {//上午
                                                item.BeOnStatus = AttendanceEnum.QK;
                                                item.OffStatus = AttendanceEnum.QK;
                                                item.BeOnRelevance = null;
                                                item.BeOnRelevanceType = null;
                                                item.OffRelevance = null;
                                                item.OffRelevanceType = null;
                                            }
                                            else
                                            {
                                                item.OffStatus = AttendanceEnum.QK;
                                                item.OffRelevance = null;
                                                item.OffRelevanceType = null;
                                            }
                                        }
                                        else if (num == ARecordList.Count)
                                        {
                                            if (IsEndMorning)
                                            {//上午
                                                item.BeOnStatus = AttendanceEnum.QK;
                                                item.BeOnRelevance = null;
                                                item.BeOnRelevanceType = null;
                                            }
                                            else
                                            {
                                                item.BeOnStatus = AttendanceEnum.QK;
                                                item.OffStatus = AttendanceEnum.QK;
                                                item.BeOnRelevance = null;
                                                item.BeOnRelevanceType = null;
                                                item.OffRelevance = null;
                                                item.OffRelevanceType = null;
                                            }
                                        }
                                        else
                                        {
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                    }
                                }
                                RecordRepository.UpdateBatch(ARecordList, trans);
                            }
                        }
                        else
                        {
                            if (ARecordList.Count > 0)
                            {
                                int num = 0;
                                foreach (var item in ARecordList)
                                {
                                    #region//新增历史记录
                                    var listH = new List<RB_Attendance_Record_Extend>();
                                    var Nmodel = item.RefMapperTo<RB_Attendance_Record_Extend>();
                                    Nmodel.TemplateType = TemplateType;
                                    Nmodel.WorkFlowId = WorkFlowId;
                                    Nmodel.Date = DateTime.Now;
                                    if (!string.IsNullOrWhiteSpace(item.History))
                                    {//继续追加
                                        listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(item.History);
                                    }
                                    listH.Add(Nmodel);
                                    string History = JsonConvert.SerializeObject(listH.Select(x => new
                                    {
                                        x.BeOnDutyTime,
                                        x.BeOnStatus,
                                        x.OffStatus,
                                        x.OffDutyTime,
                                        x.Date,
                                        x.TemplateType,
                                        x.WorkFlowId,
                                        x.BeOnRelevance,
                                        x.BeOnRelevanceType,
                                        x.OffRelevance,
                                        x.OffRelevanceType
                                    }));
                                    item.History = History;
                                    #endregion
                                    num++;
                                    if (num == 1)
                                    {
                                        if (IsStartMorning == IsEndMorning && IsStartMorning)
                                        {
                                            item.BeOnStatus = AttendanceEnum.CC;
                                            item.BeOnRelevance = evemodel.Id;
                                            item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                        }
                                        else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                        {//上午
                                            item.BeOnStatus = AttendanceEnum.CC;
                                            item.OffStatus = AttendanceEnum.CC;
                                            item.BeOnRelevance = evemodel.Id;
                                            item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                            item.OffRelevance = evemodel.Id;
                                            item.OffRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                        }
                                        else
                                        {
                                            item.OffStatus = AttendanceEnum.CC;
                                            item.OffRelevance = evemodel.Id;
                                            item.OffRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                        }
                                    }
                                    else if (num == ARecordList.Count)
                                    {
                                        if (IsEndMorning)
                                        {//上午
                                            item.BeOnStatus = AttendanceEnum.CC;
                                            item.BeOnRelevance = evemodel.Id;
                                            item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                        }
                                        else
                                        {
                                            item.BeOnStatus = AttendanceEnum.CC;
                                            item.OffStatus = AttendanceEnum.CC;
                                            item.BeOnRelevance = evemodel.Id;
                                            item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                            item.OffRelevance = evemodel.Id;
                                            item.OffRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                        }
                                    }
                                    else
                                    {
                                        item.BeOnStatus = AttendanceEnum.CC;
                                        item.OffStatus = AttendanceEnum.CC;
                                        item.BeOnRelevance = evemodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                        item.OffRelevance = evemodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.Evection;
                                    }
                                }
                                RecordRepository.UpdateBatch(ARecordList, trans);
                            }
                        }
                    }
                    break;
                case (int)WFTTemplateTypeEnum.Goout:
                    Rb_Workflow_GoOut_Extend gooutmodel = GetGooutModel(WorkFlowId);
                    StartTime = gooutmodel.StartTime.Value.ToString("yyyy-MM-dd");
                    EndTime = gooutmodel.EndTime.Value.ToString("yyyy-MM-dd");
                    //true  上午   false   下午
                    IsStartMorning = DateTime.Compare(gooutmodel.StartTime.Value, Convert.ToDateTime(StartTime + " 13:00")) < 0;
                    IsEndMorning = DateTime.Compare(gooutmodel.EndTime.Value, Convert.ToDateTime(EndTime + " 13:00")) <= 0;
                    //查询出所有在出差范围里的打卡记录表
                    ARecordList = RecordRepository.GetAttendanceRecordForTimeList(StartTime, EndTime, gooutmodel.CreateBy.Value);
                    if (gooutmodel.IsCancel == WFAuditCancelStatus.Cancel)//回滚以前的数据
                    {
                        if (ARecordList.Count > 0)
                        {
                            int num = 0;
                            foreach (var item in ARecordList)
                            {
                                var listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(item.History);
                                listH = listH.Where(x => x.WorkFlowId == WorkFlowId && x.TemplateType == TemplateType).OrderByDescending(x => x.Date).ToList();
                                if (listH.Count > 0)
                                {//有可用的撤回
                                    var Hmodel = listH[0];
                                    num++;
                                    if (num == 1)
                                    {
                                        if (IsStartMorning == IsEndMorning && IsStartMorning)
                                        {
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                        }
                                        else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                        {//上午
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                        else
                                        {
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                    }
                                    else if (num == ARecordList.Count)
                                    {
                                        if (IsEndMorning)
                                        {//上午
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                        }
                                        else
                                        {
                                            item.BeOnStatus = Hmodel.BeOnStatus;
                                            item.OffStatus = Hmodel.OffStatus;
                                            item.BeOnRelevance = Hmodel.BeOnRelevance;
                                            item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                            item.OffRelevance = Hmodel.OffRelevance;
                                            item.OffRelevanceType = Hmodel.OffRelevanceType;
                                        }
                                    }
                                    else
                                    {
                                        item.BeOnStatus = Hmodel.BeOnStatus;
                                        item.OffStatus = Hmodel.OffStatus;
                                        item.BeOnRelevance = Hmodel.BeOnRelevance;
                                        item.BeOnRelevanceType = Hmodel.BeOnRelevanceType;
                                        item.OffRelevance = Hmodel.OffRelevance;
                                        item.OffRelevanceType = Hmodel.OffRelevanceType;
                                    }
                                }
                                else
                                {
                                    num++;
                                    if (num == 1)
                                    {
                                        if (IsStartMorning == IsEndMorning && IsStartMorning)
                                        {
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                        }
                                        else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                        {//上午
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                        else
                                        {
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                    }
                                    else if (num == ARecordList.Count)
                                    {
                                        if (IsEndMorning)
                                        {//上午
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                        }
                                        else
                                        {
                                            item.BeOnStatus = AttendanceEnum.QK;
                                            item.OffStatus = AttendanceEnum.QK;
                                            item.BeOnRelevance = null;
                                            item.BeOnRelevanceType = null;
                                            item.OffRelevance = null;
                                            item.OffRelevanceType = null;
                                        }
                                    }
                                    else
                                    {
                                        item.BeOnStatus = AttendanceEnum.QK;
                                        item.OffStatus = AttendanceEnum.QK;
                                        item.BeOnRelevance = null;
                                        item.BeOnRelevanceType = null;
                                        item.OffRelevance = null;
                                        item.OffRelevanceType = null;
                                    }
                                }
                            }
                            RecordRepository.UpdateBatch(ARecordList, trans);
                        }
                    }
                    else
                    {
                        if (ARecordList.Count > 0)
                        {
                            int num = 0;
                            foreach (var item in ARecordList)
                            {
                                #region//新增历史记录
                                var listH = new List<RB_Attendance_Record_Extend>();
                                var Nmodel = item.RefMapperTo<RB_Attendance_Record_Extend>();
                                Nmodel.TemplateType = TemplateType;
                                Nmodel.WorkFlowId = WorkFlowId;
                                Nmodel.Date = DateTime.Now;
                                if (!string.IsNullOrWhiteSpace(item.History))
                                {//继续追加
                                    listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(item.History);
                                }
                                listH.Add(Nmodel);
                                string History = JsonConvert.SerializeObject(listH.Select(x => new
                                {
                                    x.BeOnDutyTime,
                                    x.BeOnStatus,
                                    x.OffStatus,
                                    x.OffDutyTime,
                                    x.Date,
                                    x.TemplateType,
                                    x.WorkFlowId,
                                    x.BeOnRelevance,
                                    x.BeOnRelevanceType,
                                    x.OffRelevance,
                                    x.OffRelevanceType
                                }));
                                item.History = History;
                                #endregion
                                num++;
                                if (num == 1)
                                {
                                    if (IsStartMorning == IsEndMorning && IsStartMorning)
                                    {
                                        item.BeOnStatus = AttendanceEnum.WQ;
                                        item.BeOnRelevance = gooutmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                    }
                                    else if (IsStartMorning != IsEndMorning && IsStartMorning)
                                    {//上午
                                        item.BeOnStatus = AttendanceEnum.WQ;
                                        item.OffStatus = AttendanceEnum.WQ;
                                        item.BeOnRelevance = gooutmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                        item.OffRelevance = gooutmodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                    }
                                    else
                                    {
                                        item.OffStatus = AttendanceEnum.WQ;
                                        item.OffRelevance = gooutmodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                    }
                                }
                                else if (num == ARecordList.Count)
                                {
                                    if (IsEndMorning)
                                    {//上午
                                        item.BeOnStatus = AttendanceEnum.WQ;
                                        item.BeOnRelevance = gooutmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                    }
                                    else
                                    {
                                        item.BeOnStatus = AttendanceEnum.WQ;
                                        item.OffStatus = AttendanceEnum.WQ;
                                        item.BeOnRelevance = gooutmodel.Id;
                                        item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                        item.OffRelevance = gooutmodel.Id;
                                        item.OffRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                    }
                                }
                                else
                                {
                                    item.BeOnStatus = AttendanceEnum.WQ;
                                    item.OffStatus = AttendanceEnum.WQ;
                                    item.BeOnRelevance = gooutmodel.Id;
                                    item.BeOnRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                    item.OffRelevance = gooutmodel.Id;
                                    item.OffRelevanceType = (int)WFTTemplateTypeEnum.Goout;
                                }
                            }
                            RecordRepository.UpdateBatch(ARecordList, trans);
                        }
                    }
                    break;
                case (int)WFTTemplateTypeEnum.ReissueCard:
                    Rb_Workflow_Reissuecard_Extend ReissueCardmodel = GetReissuecarModel(WorkFlowId);

                    //查询出所有在出差范围里的打卡记录表
                    var rmodel = RecordRepository.GetEntity(ReissueCardmodel.AttendanceRecordId);
                    if (ReissueCardmodel.IsCancel == WFAuditCancelStatus.Cancel)
                    {
                        var listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(rmodel.History);
                        listH = listH.Where(x => x.WorkFlowId == WorkFlowId && x.TemplateType == TemplateType).OrderByDescending(x => x.Date).ToList();
                        if (listH.Count > 0)
                        {//有可用的撤回
                            var Hmdoel = listH[0];
                            if (ReissueCardmodel.ReissuecardType == 1)
                            {
                                //上班打卡  
                                rmodel.BeOnStatus = Hmdoel.BeOnStatus;
                                rmodel.BeOnDutyTime = Hmdoel.BeOnDutyTime;
                                rmodel.BeOnRelevance = Hmdoel.BeOnRelevance;
                                rmodel.BeOnRelevanceType = Hmdoel.BeOnRelevanceType;
                            }
                            else
                            {
                                //下班打卡
                                rmodel.OffStatus = Hmdoel.OffStatus;
                                rmodel.OffDutyTime = Hmdoel.OffDutyTime;
                                rmodel.OffRelevance = Hmdoel.BeOnRelevance;
                                rmodel.OffRelevanceType = Hmdoel.BeOnRelevanceType;
                            }
                        }
                        else
                        {
                            if (ReissueCardmodel.ReissuecardType == 1)
                            {
                                //上班打卡  
                                rmodel.BeOnStatus = AttendanceEnum.QK;
                                rmodel.BeOnRelevance = null;
                                rmodel.BeOnRelevanceType = null;
                            }
                            else
                            {
                                //下班打卡
                                rmodel.OffStatus = AttendanceEnum.QK;
                                rmodel.OffRelevance = null;
                                rmodel.OffRelevanceType = null;
                            }
                        }
                    }
                    else
                    {
                        #region//新增历史记录
                        var Nmodel = rmodel.RefMapperTo<RB_Attendance_Record_Extend>();
                        var listH = new List<RB_Attendance_Record_Extend>();
                        Nmodel.TemplateType = TemplateType;
                        Nmodel.WorkFlowId = WorkFlowId;
                        Nmodel.Date = DateTime.Now;
                        if (!string.IsNullOrWhiteSpace(rmodel.History))
                        {//继续追加
                            listH = JsonConvert.DeserializeObject<List<RB_Attendance_Record_Extend>>(rmodel.History);
                        }
                        listH.Add(Nmodel);
                        string History = JsonConvert.SerializeObject(listH.Select(x => new
                        {
                            x.BeOnDutyTime,
                            x.BeOnStatus,
                            x.OffStatus,
                            x.OffDutyTime,
                            x.Date,
                            x.TemplateType,
                            x.WorkFlowId,
                            x.BeOnRelevance,
                            x.BeOnRelevanceType,
                            x.OffRelevance,
                            x.OffRelevanceType
                        }));
                        rmodel.History = History;
                        #endregion
                        if (ReissueCardmodel.ReissuecardType == 1)
                        {
                            //上班打卡  
                            rmodel.BeOnStatus = AttendanceEnum.BK;
                            rmodel.BeOnDutyTime = ReissueCardmodel.ReissueCardTime;
                            rmodel.BeOnRelevance = ReissueCardmodel.Id;
                            rmodel.BeOnRelevanceType = (int)WFTTemplateTypeEnum.ReissueCard;
                        }
                        else
                        {
                            //下班打卡
                            rmodel.OffStatus = AttendanceEnum.BK;
                            rmodel.OffDutyTime = ReissueCardmodel.ReissueCardTime;
                            rmodel.OffRelevance = ReissueCardmodel.Id;
                            rmodel.OffRelevanceType = (int)WFTTemplateTypeEnum.ReissueCard;
                        }
                    }
                    RecordRepository.Update(rmodel, trans);
                    break;
            }
            return "";
        }

        private RB_Attendance_LeaveTime LeaveTimeUpdate(Rb_Workflow_Askforleave_Extend askmodel, int num, double DNum1)
        {
            var LTmodel = attendance_LeaveTimeRepository.Get(askmodel.CreateBy.Value, askmodel.StartTime.Value.AddMonths(num - 1).ToString("yyyy-MM"), (int)askmodel.AskforleaveType);
            if (LTmodel == null)
            {//新增
                RB_Attendance_LeaveTime ltm = new RB_Attendance_LeaveTime()
                {
                    AskforleaveMonth = askmodel.StartTime.Value.AddMonths(num - 1).ToString("yyyy-MM"),
                    AskforleaveType = (int)askmodel.AskforleaveType,
                    EmployeeId = askmodel.CreateBy.Value,
                    Duration = DNum1
                };
                List<LeaveTimeHistory> LTHList = new List<LeaveTimeHistory>();
                LeaveTimeHistory lth = new LeaveTimeHistory()
                {
                    Duration = DNum1,
                    WorkFlowId = askmodel.Id
                };
                LTHList.Add(lth);
                ltm.History = JsonConvert.SerializeObject(LTHList);
                attendance_LeaveTimeRepository.Insert(ltm);
            }
            else
            {
                LTmodel.Duration += DNum1;
                List<LeaveTimeHistory> LTHList = JsonConvert.DeserializeObject<List<LeaveTimeHistory>>(LTmodel.History);
                LeaveTimeHistory lth = new LeaveTimeHistory()
                {
                    Duration = DNum1,
                    WorkFlowId = askmodel.Id
                };
                LTHList.Add(lth);
                LTmodel.History = JsonConvert.SerializeObject(LTHList);
                attendance_LeaveTimeRepository.Update(LTmodel);
            }

            return LTmodel;
        }

        /// <summary>
        /// 根据员工id获取所在部门
        /// </summary>
        /// <param name="eid"></param>
        /// <returns></returns>
        public string GetDepartmentForEmplyoeeId(int eid)
        {
            return accountRepository.GetEmployeeInfo(eid)?.DeptName ?? "";
        }

        /// <summary>
        /// 添加拷贝审核节点
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="wfId">工作流id</param>
        /// <param name="wFTTemplateTypeEnum">工作模板</param>
        /// <param name="modelNext">审核关联</param>
        /// <param name="trans"></param>
        /// <param name="AuditAccountList"></param>
        private bool InsertAuditRelevanceNext(int empId, int wfId, WFTTemplateTypeEnum wFTTemplateTypeEnum, Rb_Workflow_AuditRelevance_Extend modelNext, System.Data.IDbTransaction trans, out List<EmAccoutIdModel> AuditAccountList)
        {
            #region 添加初始审核人
            switch ((int)wFTTemplateTypeEnum)
            {
                case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                    var askm = askforleaveRepository.GetModel(wfId);
                    empId = askm.CreateBy.Value;
                    break;
                case (int)WFTTemplateTypeEnum.Evection:
                    var evem = wfEvectionRepository.GetModel(wfId);
                    empId = evem.CreateBy.Value;
                    break;
                case (int)WFTTemplateTypeEnum.Goout:
                    var gooutm = wfGoOutRepository.GetModel(wfId);
                    empId = gooutm.CreateBy.Value;
                    break;
                case (int)WFTTemplateTypeEnum.ReissueCard:
                    var reim = wfReissuecardRepository.GetModel(wfId);
                    empId = reim.CreateBy.Value;
                    break;
            }

            AuditAccountList = new List<EmAccoutIdModel>();
            if (empId <= 0)
            {
                return false;
            }
            Rb_Workflow_AuditRelevance auditRelevance = modelNext.RefMapperTo<Rb_Workflow_AuditRelevance>();
            //部门负责人审核
            if (auditRelevance.AuditType == WFTAuditTypeEnum.Director)
            {
                var empModel = accountRepository.GetEmployeeInfo(empId);
                var empList = GetEmployeeByDeptTierModule(new Employee_ViewModel() { DeptTier = auditRelevance.RoleOrInitiator ?? 0, Dept_Id = empModel.Dept_Id, Group_Id = empModel.Group_Id });
                if (empList.Any())
                {
                    List<int> empIds = empList.Select(x => x.Id).ToList();
                    InsertBatcheAuditRecord(empIds, wfId, wFTTemplateTypeEnum, trans, auditRelevance);
                    foreach (var item in empList)
                    {
                        AuditAccountList = new List<EmAccoutIdModel>() { new EmAccoutIdModel() { EmAccount = item.Account, EmployeeId = item.Id } };
                    }
                }
                else
                {
                    return false;
                }
            }
            else if (auditRelevance.AuditType == WFTAuditTypeEnum.Role)//角色审核
            {
                var empModel = accountRepository.GetEmployeeInfo(empId);
                var empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Post_Id = auditRelevance.RoleOrInitiator ?? 0, Group_Id = empModel.Group_Id });
                if (empList.Count > 0)
                {
                    List<int> empIds = empList.Select(t => t.Id).ToList();                    
                    AuditAccountList = empList.Select(t => new EmAccoutIdModel() { EmAccount = t.Account, EmployeeId = t.Id }).Distinct().ToList();
                    InsertBatcheAuditRecord(empIds, wfId, wFTTemplateTypeEnum, trans, auditRelevance);
                }
                else
                {
                    return false;
                }

            }
            else if (auditRelevance.AuditType == WFTAuditTypeEnum.SpecifiedMember)//指定人审核
            {
                var audituserList = auditUserRelevanceRepository.GetListForRelevanceId(auditRelevance.Id);
                //List<Rb_Workflow_Audituser_Extend> audituserList = auditUserRepository.GetConditionAuditUser(auditRelevance.OriginalAuditId.Value);
                if (audituserList.Count > 0)
                {
                    AuditAccountList = audituserList.Select(x => new EmAccoutIdModel() { EmAccount = x.EmLoginMobile, EmployeeId = x.EmployeeId ?? 0 }).Distinct().ToList();
                    List<int> empIds = audituserList.Select(t => t.EmployeeId.Value).ToList();
                    InsertBatcheAuditRecord(empIds, wfId, wFTTemplateTypeEnum, trans, auditRelevance);
                }
                else
                {
                    return false;
                }

            }

            #endregion
            return true;
        }
        /// <summary>
        /// 审核  不同意
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <param name="empId"></param>
        /// <param name="Description"></param>
        /// <param name="ImageStr"></param>
        /// <returns></returns>
        public ApiResult SetNotConsent(int WorkFlowId, int TemplateType, int empId, string Description, string ImageStr)
        {
            //HK 2020-04-15新增参数【勿删】
            string para = string.Format("WorkFlowId:{0} TemplateType:{1} empId:{2} Description:{3} ImageStr:{4}", WorkFlowId, TemplateType, empId, Description, ImageStr);
            var trans = wfReissuecardRepository.DbTransaction;
            try
            {
                //图片处理
                if (!string.IsNullOrWhiteSpace(ImageStr) && ImageStr != "[]")
                {
                    List<string> imgList = new List<string>();
                    ImageOperation(JsonConvert.DeserializeObject<string[]>(ImageStr), out imgList);
                    ImageStr = JsonConvert.SerializeObject(imgList);
                }
                //首先更改 审核关联  审核记录
                List<Rb_Workflow_AuditRelevance_Extend> arList = auditRelevanceRepository.GetAuditRelevanceList(WorkFlowId, TemplateType);
                List<Rb_Workflow_Auditrecord_Extend> aurList = auditrecordRepository.GetAuditRecordList(WorkFlowId, TemplateType);
                //找出当前审核
                int Notcount = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough).Count();
                if (Notcount > 0)
                {
                    wfReissuecardRepository.DBSession.Commit();
                    return ApiResult.Failed("该申请单已被拒绝！");
                }
                var ToAuditFlow = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit).OrderBy(x => x.Sort).ToList();
                if (ToAuditFlow.Count <= 0)
                {
                    wfReissuecardRepository.DBSession.Commit();
                    return ApiResult.Failed("该申请单审核已经完结！");
                }
                if (ToAuditFlow.Count > 0)
                {
                    var model = ToAuditFlow[0];
                    var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();

                    var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
                    if (amodel == null)
                    {
                        wfReissuecardRepository.DBSession.Commit();
                        return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
                    }
                    //同时  修改  审核记录状态 审核流程 
                    model.Stauts = WFRrocessStatus.AuditNotThrough;
                    if (!string.IsNullOrWhiteSpace(model.AuditedId))
                    {
                        model.AuditedId += "," + empId;
                    }
                    else
                    {
                        model.AuditedId = empId.ToString();
                    }
                    #region 更新审核记录表状态
                    IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.AuditNotThrough },
                            { nameof(Rb_Workflow_Auditrecord.Description),Description}
                            ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                        ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                        };
                    IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                    auditrecordRepository.Update(fileds, whereHelpers, trans);
                    #endregion
                    #region 更新审核关联表状态
                    fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.Stauts), model.Stauts },
                                { nameof(Rb_Workflow_AuditRelevance.AuditedId), model.AuditedId },
                            };
                    whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                FiledValue = model.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                    auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                    #endregion

                    var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != empId).ToList();
                    int AuditCount = list.Count();
                    if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                    {
                        foreach (var item in list)
                        {
                            fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.OtherHaveAudit },
                                        { nameof(Rb_Workflow_Auditrecord.Description),Description}
                                    ,{ nameof(Rb_Workflow_Auditrecord.Image),ImageStr}
                                ,{ nameof(Rb_Workflow_Auditrecord.UpdateTime),DateTime.Now}
                                    };
                            whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                        FiledValue = item.Id,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                            auditrecordRepository.Update(fileds, whereHelpers, trans);
                        }
                    }
                    switch (TemplateType)
                    {
                        case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                            fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Askforleave.Status), WFAuditStatus.NotThrough },
                                    };
                            whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Askforleave.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                            askforleaveRepository.Update(fileds, whereHelpers, trans);

                            break;
                        case (int)WFTTemplateTypeEnum.Evection:
                            fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Evection.Status), WFAuditStatus.NotThrough },
                                    };
                            whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Evection.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                            wfEvectionRepository.Update(fileds, whereHelpers, trans);
                            break;
                        case (int)WFTTemplateTypeEnum.Goout:
                            fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_GoOut.Status), WFAuditStatus.NotThrough },
                                    };
                            whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_GoOut.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                            wfGoOutRepository.Update(fileds, whereHelpers, trans);
                            break;
                        case (int)WFTTemplateTypeEnum.ReissueCard:
                            fileds = new Dictionary<string, object>
                                    {
                                        { nameof(Rb_Workflow_Reissuecard.Status), WFAuditStatus.NotThrough },
                                    };
                            whereHelpers = new List<WhereHelper>
                                {
                                    new WhereHelper()
                                    {
                                        FiledName = nameof(Rb_Workflow_Reissuecard.Id),
                                        FiledValue = WorkFlowId,
                                        OperatorEnum = OperatorEnum.Equal
                                    }
                                };
                            wfReissuecardRepository.Update(fileds, whereHelpers, trans);
                            break;
                    }
                }
                wfReissuecardRepository.DBSession.Commit();
                //发送推送信息                
                string EmAccout = "";
                string EmName = "";
                string AskforName = "";
                int EmId = 0;
                switch (TemplateType)
                {
                    case (int)WFTTemplateTypeEnum.AskForLeave://修改请假申请状态
                        var askm = askforleaveRepository.GetModel(WorkFlowId);
                        EmAccout = askm.EmLoginMobile;
                        EmName = askm.EmName;
                        AskforName = "请假申请";
                        EmId = askm.CreateBy.Value;
                        break;
                    case (int)WFTTemplateTypeEnum.Evection:
                        var evem = wfEvectionRepository.GetModel(WorkFlowId);
                        EmAccout = evem.EmLoginMobile;
                        EmName = evem.EmName;
                        AskforName = "出差申请";
                        EmId = evem.CreateBy.Value;
                        break;
                    case (int)WFTTemplateTypeEnum.Goout:
                        var gooutm = wfGoOutRepository.GetModel(WorkFlowId);
                        EmAccout = gooutm.EmLoginMobile;
                        EmName = gooutm.EmName;
                        AskforName = "外出申请";
                        EmId = gooutm.CreateBy.Value;
                        break;
                    case (int)WFTTemplateTypeEnum.ReissueCard:
                        var reim = wfReissuecardRepository.GetModel(WorkFlowId);
                        EmAccout = reim.EmLoginMobile;
                        EmName = reim.EmName;
                        AskforName = "补卡申请";
                        EmId = reim.CreateBy.Value;
                        break;
                }
                string EmpNowName = (accountRepository.GetEmployeeInfo(empId)?.EmployeeName ?? "");
                List<EmAccoutIdModel> EmNameList = new List<EmAccoutIdModel>() { new EmAccoutIdModel() { EmAccount = EmAccout, EmployeeId = EmId } };
                PushAuditMessage(EmNameList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您的{AskforName}已被{EmpNowName}拒绝！", "申请不通过", empId, SysTemPushTypeEnum.Audit);
                var ThroughList = aurList.Where(x => x.AuditStatus == WFRrocessStatus.AuditThrough).ToList();
                EmNameList = ThroughList.Select(x => new EmAccoutIdModel() { EmAccount = x.EmLoginMobile, EmployeeId = x.AuditEmId ?? 0 }).Distinct().ToList();
                PushAuditMessage(EmNameList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您参与{EmName}发起的{AskforName}已被上级{EmpNowName}拒绝！", "审核不通过", empId, SysTemPushTypeEnum.Audit);


                return ApiResult.Success("审核成功！");
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetNotConsent_parm:" + para);
                wfReissuecardRepository.DBSession.Rollback("SetNotConsent_parm:" + para);
                return ApiResult.Failed("申请提交失败");
            }
        }
        /// <summary>
        /// 审核  转交
        /// </summary>
        /// <param name="WorkFlowId"></param>
        /// <param name="TemplateType"></param>
        /// <param name="empId"></param>
        /// <param name="Description"></param>
        /// <param name="CareOfEmId"></param>
        /// <returns></returns>
        public ApiResult SetCareOf(int WorkFlowId, int TemplateType, int empId, string Description, int CareOfEmId)
        {
            //首先更改 审核关联  审核记录
            List<Rb_Workflow_AuditRelevance_Extend> arList = auditRelevanceRepository.GetAuditRelevanceList(WorkFlowId, TemplateType);
            List<Rb_Workflow_Auditrecord_Extend> aurList = auditrecordRepository.GetAuditRecordList(WorkFlowId, TemplateType);
            //找出当前审核
            int Notcount = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough).Count();
            if (Notcount > 0)
            {
                return ApiResult.Failed("该申请单已被拒绝！");
            }
            var ToAuditFlow = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit).OrderBy(x => x.Sort).ToList();
            if (ToAuditFlow.Count <= 0)
            {
                return ApiResult.Failed("该申请单审核已经完结！");
            }
            var model = ToAuditFlow[0];//获取得到当前审核的数据
            var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();//获取当前审核关联下的所有审核记录
            var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).FirstOrDefault();
            if (amodel == null)
            {
                return ApiResult.Failed("尚未匹配到审核相关信息，请联系管理员！");
            }
            var trans = wfReissuecardRepository.DbTransaction;
            try
            {
                var OldEmodel = accountRepository.GetEmployeeInfo(empId);
                var NewEmodel = accountRepository.GetEmployeeInfo(CareOfEmId);
                if (OldEmodel == null || NewEmodel == null)
                {
                    wfReissuecardRepository.DBSession.Commit();
                    return ApiResult.Failed("转交人或者当前审核人不存在，请联系管理员！");
                }
                List<SetCareOfModel> coModelList = new List<SetCareOfModel>();
                if (!string.IsNullOrWhiteSpace(amodel.CareOfRemarks))
                {
                    coModelList = JsonConvert.DeserializeObject<List<SetCareOfModel>>(amodel.CareOfRemarks);
                }
                SetCareOfModel comodel = new SetCareOfModel()
                {
                    BeFrom = OldEmodel.EmployeeName,
                    Target = NewEmodel.EmployeeName,
                    Remarks = Description
                };
                coModelList.Add(comodel);
                #region 更新审核记录表转交
                IDictionary<string, object> fileds = new Dictionary<string, object>
                        {
                            { nameof(Rb_Workflow_Auditrecord.AuditEmId), CareOfEmId },
                            { nameof(Rb_Workflow_Auditrecord.CareOfRemarks),JsonConvert.SerializeObject(coModelList)}
                        };
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(Rb_Workflow_Auditrecord.Id),
                                FiledValue = amodel.Id,
                                OperatorEnum = OperatorEnum.Equal
                            }
                        };
                auditrecordRepository.Update(fileds, whereHelpers, trans);
                #endregion
                string ToAuditStr = model.ToAuditId;
                if (!string.IsNullOrWhiteSpace(ToAuditStr))
                {
                    ToAuditStr = "," + ToAuditStr + ",";
                }
                else
                {
                    wfReissuecardRepository.DBSession.Rollback("SetCareOf");
                    return ApiResult.Failed("审核关联表审核人出错了~！请联系管理员！");
                }
                if (!ToAuditStr.Contains("," + empId + ","))
                {
                    wfReissuecardRepository.DBSession.Rollback("SetCareOf");
                    return ApiResult.Failed("当前审核人不存在，请核实后再试！");
                }
                ToAuditStr = ToAuditStr.Replace("," + empId + ",", "," + CareOfEmId + ",");
                ToAuditStr = ToAuditStr[1..^1];
                #region 更新审核关联表转交
                fileds = new Dictionary<string, object>
                            {
                                { nameof(Rb_Workflow_AuditRelevance.ToAuditId), ToAuditStr},
                            };
                whereHelpers = new List<WhereHelper>
                            {
                                new WhereHelper()
                                {
                                    FiledName = nameof(Rb_Workflow_AuditRelevance.Id),
                                    FiledValue = model.Id,
                                    OperatorEnum = OperatorEnum.Equal
                                }
                            };
                auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                #endregion
                wfReissuecardRepository.DBSession.Commit();
                //发送推送信息
                List<EmAccoutIdModel> EmNameList = new List<EmAccoutIdModel>() { new EmAccoutIdModel() { EmAccount = OldEmodel.Account, EmployeeId = OldEmodel.Id } };
                PushAuditMessage(EmNameList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您成功转交审核任务给{NewEmodel.EmployeeName}！", "转交成功", empId, SysTemPushTypeEnum.Audit);
                EmNameList = new List<EmAccoutIdModel>() { new EmAccoutIdModel() { EmAccount = NewEmodel.Account, EmployeeId = NewEmodel.Id } };
                PushAuditMessage(EmNameList, WorkFlowId, (WFTTemplateTypeEnum)TemplateType, $@"您有来自{OldEmodel.EmployeeName}的转交审核任务！", "转交审核", empId, SysTemPushTypeEnum.Audit);
                return ApiResult.Success("转交成功！");
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetCareOf");
                wfReissuecardRepository.DBSession.Rollback("SetCareOf");
                return ApiResult.Failed("转交失败");
            }
        }
        #endregion


        #region 审批列表

        #region 我的审批

        /// <summary>
        /// 我的审批
        /// </summary>
        /// <param name="searchKey">搜索关键字</param>
        /// <param name="empId">员工id</param>
        /// <param name="appAuditStatus">app获取审核状态</param>
        /// <param name="auditType">审核类型 1待我审批，2我已审批的</param>
        /// <param name="applyType">申请筛选模板类型</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="rowCount">总条数</param>
        /// <returns></returns>
        public List<Rb_Workflow_MyAuditRelation_Extend> MyAudit(string searchKey, int empId, AppAuditStatusEnum appAuditStatus, int auditType, int applyType, int pageIndex, int pageSize, out long rowCount)
        {
            List<Rb_Workflow_Auditrecord_Extend> auditrecordList = auditrecordRepository.MyAuditPageList(searchKey, empId, appAuditStatus, auditType, applyType, pageIndex, pageSize, out rowCount);
            List<Rb_Workflow_MyAuditRelation_Extend> myAuditRelationList = new List<Rb_Workflow_MyAuditRelation_Extend>();
            if (auditrecordList.Count > 0)
            {
                foreach (var item in auditrecordList)
                {
                    Rb_Workflow_MyAuditRelation_Extend myAuditRelation = new Rb_Workflow_MyAuditRelation_Extend
                    {
                        TemplateType = item.TemplateType,
                        WorkFlowId = item.WorkFlowId
                    };
                    switch (myAuditRelation.TemplateType)
                    {
                        case WFTTemplateTypeEnum.AskForLeave:
                            AskForLeaveAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Evection:
                            EvectionAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Goout:
                            GooutAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.ReissueCard:
                            ReissueCardAuditrecordDetial(myAuditRelation);
                            break;
                    }
                    if (item.AuditStatus == WFRrocessStatus.AuditThrough)
                    {
                        myAuditRelation.AuditStatusColor = "#00B06C";
                        myAuditRelation.AuditStatusStr = "审批通过";
                    }
                    else if (item.AuditStatus == WFRrocessStatus.NotAudit)
                    {
                        myAuditRelation.AuditStatusStr = "待审批";
                        myAuditRelation.AuditStatusColor = "#257BF1";
                    }
                    else if (item.AuditStatus == WFRrocessStatus.AuditNotThrough)
                    {
                        myAuditRelation.AuditStatusStr = "审批拒绝";
                        myAuditRelation.AuditStatusColor = "#F73939";
                    }
                    myAuditRelationList.Add(myAuditRelation);
                }
            }
            return myAuditRelationList;
        }

        /// <summary>
        /// 获取待我审批的数量
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="appAuditStatus"></param>
        /// <param name="auditType"></param>
        /// <returns></returns>
        public int MyAuditCount(int empId, AppAuditStatusEnum appAuditStatus, int auditType)
        {
            return auditrecordRepository.MyAuditCount(empId, appAuditStatus, auditType);
        }

        /// <summary>
        /// 我的发起的审批
        /// </summary>
        /// <param name="searchKey">搜索关键字</param>
        /// <param name="empId">员工id</param>
        /// <param name="appAuditStatus">app获取审核状态</param>
        /// <param name="applyType">申请筛选模板类型</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="rowCount">总条数</param>
        /// <returns></returns>
        public List<Rb_Workflow_MyAuditRelation_Extend> MyInitiateAudit(string searchKey, int empId, AppAuditStatusEnum appAuditStatus, int applyType, int pageIndex, int pageSize, out long rowCount)
        {
            List<Rb_Workflow_Auditrecord_Extend> auditrecordList = auditrecordRepository.MyInitiateAudit(searchKey, empId, appAuditStatus, applyType, pageIndex, pageSize, out rowCount);
            List<Rb_Workflow_MyAuditRelation_Extend> myAuditRelationList = new List<Rb_Workflow_MyAuditRelation_Extend>();
            if (auditrecordList.Count > 0)
            {
                foreach (var item in auditrecordList)
                {
                    Rb_Workflow_MyAuditRelation_Extend myAuditRelation = new Rb_Workflow_MyAuditRelation_Extend
                    {
                        TemplateType = item.TemplateType,
                        CreateTime = item.CreateTime,
                        WorkFlowId = item.WorkFlowId
                    };
                    switch (myAuditRelation.TemplateType)
                    {
                        case WFTTemplateTypeEnum.AskForLeave:
                            AskForLeaveAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Evection:
                            EvectionAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Goout:
                            GooutAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.ReissueCard:
                            ReissueCardAuditrecordDetial(myAuditRelation);
                            break;
                    }
                    if (item.Status == WFAuditStatus.InReview)
                    {
                        List<Rb_Workflow_AuditRelevance_Extend> auditList = auditRelevanceRepository.GetAuditRelevanceList(myAuditRelation.WorkFlowId.Value, (int)myAuditRelation.TemplateType.Value);
                        Rb_Workflow_AuditRelevance_Extend currentAudit = auditList.Where(t => t.Stauts == WFRrocessStatus.NotAudit).OrderBy(t => t.Sort).FirstOrDefault();
                        if (currentAudit != null)
                        {
                            if (!string.IsNullOrWhiteSpace(currentAudit.ToAuditId))
                            {
                                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                                List<string> toAuditIdList = currentAudit.ToAuditId.Split(',').ToList();
                                if (!string.IsNullOrWhiteSpace(currentAudit.AuditedId))
                                {
                                    List<string> auditIdList = currentAudit.AuditedId.Split(',').ToList();
                                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = string.Join(",", toAuditIdList.Except(auditIdList)) });
                                }
                                else
                                {
                                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = string.Join(",", currentAudit.ToAuditId.Trim(',')) });
                                }
                                List<string> userNameList = new List<string>();
                                foreach (var emp in empList)
                                {
                                    if (!string.IsNullOrWhiteSpace(emp.EmployeeName))
                                    {
                                        userNameList.Add(emp.EmployeeName);
                                    }
                                }
                                if (userNameList.Count > 0)
                                {
                                    myAuditRelation.AuditStatusStr = $"{string.Join(",", userNameList)}审批中";
                                }
                                else
                                {
                                    myAuditRelation.AuditStatusStr = $"审批中";
                                }
                            }
                            else
                            {
                                myAuditRelation.AuditStatusStr = "审批中";
                            }
                        }
                        else
                        {
                            myAuditRelation.AuditStatusStr = "审批中";
                        }
                        myAuditRelation.AuditStatusColor = "#257BF1";
                    }
                    else
                    {
                        if (item.Status == WFAuditStatus.NotThrough)
                        {
                            myAuditRelation.AuditStatusStr = "审批拒绝";
                            myAuditRelation.AuditStatusColor = "#F73939";
                        }
                        else if (item.Status == WFAuditStatus.ToWithdraw)
                        {
                            myAuditRelation.AuditStatusColor = "#F73939";
                            myAuditRelation.AuditStatusStr = "审批撤回";
                        }
                        else
                        {
                            myAuditRelation.AuditStatusColor = "#00B06C";
                            myAuditRelation.AuditStatusStr = "审批通过";
                        }
                    }
                    myAuditRelationList.Add(myAuditRelation);
                }
            }
            return myAuditRelationList;
        }

        /// <summary>
        /// 获取申请人历史记录
        /// </summary>
        /// <param name="searchKey"></param>
        /// <param name="empId"></param>
        /// <param name="appAuditStatus"></param>
        /// <param name="applyType"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public List<Rb_Workflow_MyAuditRelation_Extend> ProposerHostoryAudit(string searchKey, int empId, AppAuditStatusEnum appAuditStatus, int applyType, int pageIndex, int pageSize, out long rowCount)
        {
            List<Rb_Workflow_Auditrecord_Extend> auditrecordList = auditrecordRepository.MyInitiateAudit(searchKey, empId, appAuditStatus, applyType, pageIndex, pageSize, out rowCount);

            List<Rb_Workflow_MyAuditRelation_Extend> myAuditRelationList = new List<Rb_Workflow_MyAuditRelation_Extend>();
            if (auditrecordList.Count > 0)
            {
                //首先遍历所有记录  给记录附上条数
                List<string> MonthList = new List<string>();
                foreach (var item in auditrecordList)
                {
                    string str = item.CreateTime.Value.ToString("yyyy-MM");
                    MonthList.Add(str);
                }
                MonthList = MonthList.Distinct().ToList();
                List<Rb_Workflow_Auditrecord_Extend> MrModel = auditrecordRepository.ProposerHostoryMonthNum(searchKey, empId, appAuditStatus, applyType, MonthList);
                //在判断 查询出的第一条数据是否是当月第一条数据
                var model = auditrecordList[0];
                int BeforeNum = auditrecordRepository.ProposerHostoryMonthNumBeFore(searchKey, empId, appAuditStatus, applyType, model.CreateTime.Value);
                string MonthSN = "";
                int Num = 0;
                foreach (var item in auditrecordList)
                {
                    Num++;
                    Rb_Workflow_MyAuditRelation_Extend myAuditRelation = new Rb_Workflow_MyAuditRelation_Extend
                    {
                        TemplateType = item.TemplateType,
                        CreateTime = item.CreateTime,
                        WorkFlowId = item.WorkFlowId
                    };
                    if (Num == 1)
                    {
                        MonthSN = item.CreateTime.Value.ToString("yyyy-MM");
                        if (BeforeNum > 0)
                        {
                            myAuditRelation.MonthNum = "";
                        }
                        else
                        {
                            //在找出本月的条数
                            var mr = MrModel.Where(x => x.MonthStr == item.CreateTime.Value.ToString("yyyy-MM")).FirstOrDefault();
                            //先判断是否是本月
                            if (DateTime.Now.ToString("yyyy-MM") == item.CreateTime.Value.ToString("yyyy-MM"))
                            {
                                myAuditRelation.MonthNum = "本月 （" + mr.TotalCount + "）";
                            }
                            else
                            {
                                myAuditRelation.MonthNum = mr.MonthStr + " （" + mr.TotalCount + "）";
                            }
                        }
                    }
                    else
                    {
                        if (MonthSN != item.CreateTime.Value.ToString("yyyy-MM"))
                        {
                            //到了下一个月  
                            MonthSN = item.CreateTime.Value.ToString("yyyy-MM");
                            //在找出本月的条数
                            var mr = MrModel.Where(x => x.MonthStr == item.CreateTime.Value.ToString("yyyy-MM")).FirstOrDefault();
                            //先判断是否是本月
                            if (DateTime.Now.ToString("yyyy-MM") == item.CreateTime.Value.ToString("yyyy-MM"))
                            {
                                myAuditRelation.MonthNum = "本月 （" + mr.TotalCount + "）";
                            }
                            else
                            {
                                myAuditRelation.MonthNum = mr.MonthStr + " （" + mr.TotalCount + "）";
                            }
                        }
                        else
                        {
                            myAuditRelation.MonthNum = "";
                        }
                    }

                    switch (myAuditRelation.TemplateType)
                    {
                        case WFTTemplateTypeEnum.AskForLeave:
                            AskForLeaveAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Evection:
                            EvectionAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Goout:
                            GooutAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.ReissueCard:
                            ReissueCardAuditrecordDetial(myAuditRelation);
                            break;
                    }
                    if (item.Status == WFAuditStatus.InReview)
                    {
                        List<Rb_Workflow_AuditRelevance_Extend> auditList = auditRelevanceRepository.GetAuditRelevanceList(myAuditRelation.WorkFlowId.Value, (int)myAuditRelation.TemplateType.Value);
                        Rb_Workflow_AuditRelevance_Extend currentAudit = auditList.Where(t => t.Stauts == WFRrocessStatus.NotAudit).OrderBy(t => t.Sort).FirstOrDefault();
                        if (currentAudit != null)
                        {
                            if (!string.IsNullOrWhiteSpace(currentAudit.ToAuditId))
                            {
                                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                                List<string> toAuditIdList = currentAudit.ToAuditId.Split(',').ToList();
                                if (!string.IsNullOrWhiteSpace(currentAudit.AuditedId))
                                {
                                    List<string> auditIdList = currentAudit.AuditedId.Split(',').ToList();
                                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = string.Join(",", toAuditIdList.Except(auditIdList)) });
                                }
                                else
                                {
                                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = string.Join(",", currentAudit.ToAuditId.Trim(',')) });
                                }
                                List<string> userNameList = new List<string>();
                                foreach (var emp in empList)
                                {
                                    if (!string.IsNullOrWhiteSpace(emp.EmployeeName))
                                    {
                                        userNameList.Add(emp.EmployeeName);
                                    }
                                }
                                if (userNameList.Count > 0)
                                {
                                    myAuditRelation.AuditStatusStr = $"{string.Join(",", userNameList)}审批中";
                                }
                                else
                                {
                                    myAuditRelation.AuditStatusStr = $"审批中";
                                }
                            }
                            else
                            {
                                myAuditRelation.AuditStatusStr = "审批中";
                            }
                        }
                        else
                        {
                            myAuditRelation.AuditStatusStr = "审批中";
                        }
                        myAuditRelation.AuditStatusColor = "#257BF1";
                    }
                    else
                    {
                        if (item.Status == WFAuditStatus.NotThrough)
                        {
                            myAuditRelation.AuditStatusStr = "审批拒绝";
                            myAuditRelation.AuditStatusColor = "#F73939";
                        }
                        else if (item.Status == WFAuditStatus.ToWithdraw)
                        {
                            myAuditRelation.AuditStatusColor = "#F73939";
                            myAuditRelation.AuditStatusStr = "审批撤回";
                        }
                        else
                        {
                            myAuditRelation.AuditStatusColor = "#00B06C";
                            myAuditRelation.AuditStatusStr = "审批通过";
                        }
                    }
                    myAuditRelationList.Add(myAuditRelation);
                }
            }
            return myAuditRelationList;
        }

        /// <summary>
        /// 我的发起的审批
        /// </summary>
        /// <param name="searchKey">搜索关键字</param>
        /// <param name="empId">员工id</param>
        /// <param name="appAuditStatus">app获取审核状态</param>
        /// <param name="readeType">抄送我的阅读状态 0全部，1未读</param>
        /// <param name="applyType">申请筛选模板类型</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="rowCount">总条数</param>
        /// <returns></returns>
        public List<Rb_Workflow_MyAuditRelation_Extend> CopyToMyAudit(string searchKey, int empId, AppAuditStatusEnum appAuditStatus, int readeType, int applyType, int pageIndex, int pageSize, out long rowCount)
        {
            List<Rb_Workflow_CopyToPeople_Extend> auditrecordList = copyToPeopleRepository.CopyToMyAudit(searchKey, empId, appAuditStatus, readeType, applyType, pageIndex, pageSize, out rowCount);
            List<Rb_Workflow_MyAuditRelation_Extend> myAuditRelationList = new List<Rb_Workflow_MyAuditRelation_Extend>();
            if (auditrecordList.Count > 0)
            {
                foreach (var item in auditrecordList)
                {
                    Rb_Workflow_MyAuditRelation_Extend myAuditRelation = new Rb_Workflow_MyAuditRelation_Extend
                    {
                        TemplateType = item.TemplateType,
                        WorkFlowId = item.WorkFlowId,
                        ReadStauts = item.ReadStauts
                    };
                    switch (myAuditRelation.TemplateType)
                    {
                        case WFTTemplateTypeEnum.AskForLeave:
                            AskForLeaveAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Evection:
                            EvectionAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.Goout:
                            GooutAuditrecordDetial(myAuditRelation);
                            break;
                        case WFTTemplateTypeEnum.ReissueCard:
                            ReissueCardAuditrecordDetial(myAuditRelation);
                            break;
                    }
                    myAuditRelation.AuditStatusStr = "审批通过";
                    myAuditRelation.AuditStatusColor = "#00B06C";
                    myAuditRelationList.Add(myAuditRelation);
                }
            }
            return myAuditRelationList;
        }
        #endregion

        #region 审批数据详情组装
        /// <summary>
        /// 请假列表详情数据组装
        /// </summary>
        /// <param name="auditrecord"></param>
        public void AskForLeaveAuditrecordDetial(Rb_Workflow_MyAuditRelation_Extend auditrecord)
        {
            Rb_Workflow_Askforleave_Extend askforleave = askforleaveRepository.GetEntityDetial(auditrecord.WorkFlowId.Value);
            if (askforleave != null)
            {
                auditrecord.CreateTime = askforleave.CreateTime;
                auditrecord.Title = string.IsNullOrWhiteSpace(askforleave.EmName) ? "" : $"{askforleave.EmName}的" + auditrecord.TemplateType.ToName().Split('|')[0];
                if (askforleave.IsCancel == WFAuditCancelStatus.Cancel)
                {
                    auditrecord.Title += "(撤回)";
                }
                auditrecord.UserPhoto = askforleave.EmPhoto;
                List<string> content = new List<string>
                {
                    $"请假类型:{askforleave.AskforleaveType.ToName()}",
                    $"开始时间:{askforleave.StartTime.Value:yyyy-MM-dd HH:mm}",
                    $"结束时间:{askforleave.EndTime.Value:yyyy-MM-dd HH:mm}",
                   // $"请假时长:{askforleave.Duration}小时",
                    $"请假事由:{askforleave.Description}"
                };
                auditrecord.Detial = content;
            }
        }
        /// <summary>
        /// 出差列表详情数据组装
        /// </summary>
        /// <param name="auditrecord"></param>
        public void EvectionAuditrecordDetial(Rb_Workflow_MyAuditRelation_Extend auditrecord)
        {
            Rb_Workflow_Evection_Extend evection = wfEvectionRepository.GetEntityDetial(auditrecord.WorkFlowId.Value);
            if (evection != null)
            {
                auditrecord.CreateTime = evection.CreateTime;
                auditrecord.Title = string.IsNullOrWhiteSpace(evection.EmName) ? "" : $"{evection.EmName}的" + auditrecord.TemplateType.ToName().Split('|')[0];
                if (evection.IsCancel == WFAuditCancelStatus.Cancel)
                {
                    auditrecord.Title += "(撤回)";
                }
                auditrecord.UserPhoto = evection.EmPhoto;
                List<Rb_Workflow_Travel> travelList = wfTravelRepository.GetTravelList(evection.Id);
                string travelVehicle = "";
                if (travelList.Count() > 0)
                {
                    travelVehicle = string.Join("、", travelList.Select(t => t.Vehicle.ToName()).ToList());
                }
                List<string> content = new List<string>
                {
                    $"出差事由:{evection.Description}",
                    $"出差天数:{evection.Traveldays}天",
                    $"交通工具:{travelVehicle}"
                    //$"出差备注:{evection.Remark}"
                };
                auditrecord.Detial = content;
            }
        }

        /// <summary>
        /// 外出列表详情数据组装
        /// </summary>
        /// <param name="auditrecord"></param>
        public void GooutAuditrecordDetial(Rb_Workflow_MyAuditRelation_Extend auditrecord)
        {
            Rb_Workflow_GoOut_Extend goOut = wfGoOutRepository.GetEntityDetial(auditrecord.WorkFlowId.Value);
            if (goOut != null)
            {
                auditrecord.CreateTime = goOut.CreateTime;
                auditrecord.Title = string.IsNullOrWhiteSpace(goOut.EmName) ? "" : $"{goOut.EmName}的" + auditrecord.TemplateType.ToName().Split('|')[0];
                if (goOut.IsCancel == WFAuditCancelStatus.Cancel)
                {
                    auditrecord.Title += "(撤回)";
                }
                auditrecord.UserPhoto = goOut.EmPhoto;
                List<string> content = new List<string>
                {
                    $"开始时间:{goOut.StartTime.Value:yyyy-MM-dd HH:mm}",
                    $"结束时间:{goOut.EndTime.Value:yyyy-MM-dd HH:mm}"
                    //$"外出时长:{goOut.Duration}小时",
                    //$"外出事由:{goOut.Description}"
                };
                auditrecord.Detial = content;
            }
        }

        /// <summary>
        /// 补卡列表详情数据组装
        /// </summary>
        /// <param name="auditrecord"></param>
        public void ReissueCardAuditrecordDetial(Rb_Workflow_MyAuditRelation_Extend auditrecord)
        {
            Rb_Workflow_Reissuecard_Extend reissuecard = wfReissuecardRepository.GetEntityDetial(auditrecord.WorkFlowId.Value);
            if (reissuecard != null)
            {
                auditrecord.CreateTime = reissuecard.CreateTime;
                auditrecord.Title = string.IsNullOrWhiteSpace(reissuecard.EmName) ? "" : $"{reissuecard.EmName}的" + auditrecord.TemplateType.ToName().Split('|')[0];
                if (reissuecard.IsCancel == WFAuditCancelStatus.Cancel)
                {
                    auditrecord.Title += "(撤回)";
                }
                auditrecord.UserPhoto = reissuecard.EmPhoto;
                List<string> content = new List<string>
                {
                    $"缺卡原因:{reissuecard.Description}"
                };
                auditrecord.Detial = content;
            }
        }
        #endregion
        /// <summary>
        /// 修改抄送人已读状态
        /// </summary>
        /// <param name="templateType"></param>
        /// <param name="workFlowId"></param>
        public void UpdateCopyToPeopleReadStaut(int templateType, int workFlowId)
        {

            IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(Rb_Workflow_CopyToPeople.ReadStauts), 2 }
                };

            IList<WhereHelper> whereHelpers = new List<WhereHelper>
            {
                new WhereHelper()
                {
                    FiledName = nameof(Rb_Workflow_CopyToPeople.TemplateType),
                    FiledValue = templateType,
                    OperatorEnum = OperatorEnum.Equal
                },
                new WhereHelper()
                {
                    FiledName = nameof(Rb_Workflow_CopyToPeople.WorkFlowId),
                    FiledValue = workFlowId,
                    OperatorEnum = OperatorEnum.Equal
                }
            };
            copyToPeopleRepository.Update(fileds, whereHelpers);
        }

        /// <summary>
        /// 修改抄送人所有已读状态
        /// </summary>
        /// <param name="empId">员工id</param>
        public void UpdateCopyToPeopleAllReadStaut(int empId)
        {

            IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(Rb_Workflow_CopyToPeople.ReadStauts), 2 }
                };

            IList<WhereHelper> whereHelpers = new List<WhereHelper>
            {
                new WhereHelper()
                {
                    FiledName = nameof(Rb_Workflow_CopyToPeople.EmployeeId),
                    FiledValue = empId,
                    OperatorEnum = OperatorEnum.Equal
                }
            };
            copyToPeopleRepository.Update(fileds, whereHelpers);
        }
        #endregion

        #region 撤销申请
        /// <summary>
        /// 修改抄送人已读状态
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="templateType">模板类型</param>
        /// <param name="workFlowId">工作流id</param>
        public bool UndoAudit(int empId, WFTTemplateTypeEnum templateType, int workFlowId)
        {
            bool isSuccess = false;
            switch (templateType)
            {
                case WFTTemplateTypeEnum.AskForLeave:
                    isSuccess = AskForLeaveUndo(empId, workFlowId);
                    break;
                case WFTTemplateTypeEnum.Evection:
                    isSuccess = EvectionUndo(empId, workFlowId);
                    break;
                case WFTTemplateTypeEnum.Goout:
                    isSuccess = GooutUndo(empId, workFlowId);
                    break;
                case WFTTemplateTypeEnum.ReissueCard:
                    isSuccess = ReissueCardUndo(empId, workFlowId);
                    break;
            }
            return isSuccess;
        }

        #region 审批撤销
        /// <summary>
        /// 请假撤销
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="workFlowId">工作流id</param>
        public bool AskForLeaveUndo(int empId, int workFlowId)
        {
            Rb_Workflow_Askforleave askforleave = askforleaveRepository.GetEntity(workFlowId);
            if (askforleave != null && askforleave.CreateBy == empId)
            {
                var trans = askforleaveRepository.DbTransaction;

                try
                {
                    //要发送审核消息的账号
                    List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                    DeleteAuditInfo(workFlowId, (int)WFTTemplateTypeEnum.AskForLeave, askforleave.Status.Value, trans, out sendAccount);
                    WFAuditStatus auditStatus = askforleave.Status.Value;
                    if (askforleave.Status != WFAuditStatus.Through)
                    {
                        askforleave.Status = WFAuditStatus.ToWithdraw;
                        askforleaveRepository.Update(askforleave, trans);
                    }
                    else
                    {
                        askforleave.Status = WFAuditStatus.InReview;
                        askforleave.IsCancel = WFAuditCancelStatus.Cancel;
                        askforleaveRepository.Update(askforleave, trans);
                    }
                    askforleaveRepository.DBSession.Commit();
                    if (auditStatus != WFAuditStatus.Through)
                    {
                        PushAuditMessage(sendAccount, askforleave.Id, WFTTemplateTypeEnum.AskForLeave, "你有已审批的请假申请已撤销", "审批撤销通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    else
                    {
                        PushAuditMessage(sendAccount, askforleave.Id, WFTTemplateTypeEnum.AskForLeave, "你有待审批的请假申请", "审批通知", empId, SysTemPushTypeEnum.Audit);
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "AskForLeaveUndo_para:" + string.Format("empId:{0} workFlowId:{1}", empId, workFlowId));
                    askforleaveRepository.DBSession.Rollback("AskForLeaveUndo_para:" + string.Format("empId:{0} workFlowId:{1}", empId, workFlowId));
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 出差撤销
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="workFlowId">工作流id</param>
        public bool EvectionUndo(int empId, int workFlowId)
        {
            Rb_Workflow_Evection evection = wfEvectionRepository.GetEntity(workFlowId);
            if (evection != null && evection.CreateBy == empId)
            {
                var trans = wfEvectionRepository.DbTransaction;
                try
                {
                    //要发送审核消息的账号
                    List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                    DeleteAuditInfo(workFlowId, (int)WFTTemplateTypeEnum.Evection, evection.Status.Value, trans, out sendAccount);
                    WFAuditStatus auditStatus = evection.Status.Value;
                    if (evection.Status != WFAuditStatus.Through)
                    {
                        evection.Status = WFAuditStatus.ToWithdraw;
                        wfEvectionRepository.Update(evection, trans);
                    }
                    else
                    {
                        evection.Status = WFAuditStatus.InReview;
                        evection.IsCancel = WFAuditCancelStatus.Cancel;
                        wfEvectionRepository.Update(evection, trans);
                    }
                    wfEvectionRepository.DBSession.Commit();
                    if (auditStatus != WFAuditStatus.Through)
                    {
                        PushAuditMessage(sendAccount, evection.Id, WFTTemplateTypeEnum.Evection, "你有已审批的出差申请已撤销", "审批撤销通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    else
                    {
                        PushAuditMessage(sendAccount, evection.Id, WFTTemplateTypeEnum.Evection, "你有待审批的出差申请", "审批通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "EvectionUndo");
                    wfEvectionRepository.DBSession.Rollback("EvectionUndo");
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 外出撤销
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="workFlowId">工作流id</param>
        public bool GooutUndo(int empId, int workFlowId)
        {
            Rb_Workflow_GoOut goOut = wfGoOutRepository.GetEntity(workFlowId);
            if (goOut != null && goOut.CreateBy == empId)
            {
                var trans = wfGoOutRepository.DbTransaction;
                try
                {
                    //要发送审核消息的账号
                    List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                    DeleteAuditInfo(workFlowId, (int)WFTTemplateTypeEnum.Goout, goOut.Status.Value, trans, out sendAccount);
                    WFAuditStatus auditStatus = goOut.Status.Value;
                    if (goOut.Status != WFAuditStatus.Through)
                    {
                        goOut.Status = WFAuditStatus.ToWithdraw;
                        wfGoOutRepository.Update(goOut, trans);
                    }
                    else
                    {
                        goOut.Status = WFAuditStatus.InReview;
                        goOut.IsCancel = WFAuditCancelStatus.Cancel;
                        wfGoOutRepository.Update(goOut, trans);
                    }
                    wfGoOutRepository.DBSession.Commit();
                    if (auditStatus != WFAuditStatus.Through)
                    {
                        PushAuditMessage(sendAccount, goOut.Id, WFTTemplateTypeEnum.Goout, "你有已审批的外出申请已撤销", "审批撤销通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    else
                    {
                        PushAuditMessage(sendAccount, goOut.Id, WFTTemplateTypeEnum.Goout, "你有待审批的外出申请", "审批通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "GooutUndo");
                    wfGoOutRepository.DBSession.Rollback("GooutUndo");
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 补卡撤销
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="workFlowId">工作流id</param>
        public bool ReissueCardUndo(int empId, int workFlowId)
        {
            Rb_Workflow_Reissuecard reissuecard = wfReissuecardRepository.GetEntity(workFlowId);
            if (reissuecard != null && reissuecard.CreateBy == empId)
            {
                var trans = wfReissuecardRepository.DbTransaction;
                try
                {
                    //要发送审核消息的账号
                    List<EmAccoutIdModel> sendAccount = new List<EmAccoutIdModel>();
                    DeleteAuditInfo(workFlowId, (int)WFTTemplateTypeEnum.ReissueCard, reissuecard.Status.Value, trans, out sendAccount);
                    WFAuditStatus auditStatus = reissuecard.Status.Value;
                    if (reissuecard.Status != WFAuditStatus.Through)
                    {
                        reissuecard.Status = WFAuditStatus.ToWithdraw;
                        wfReissuecardRepository.Update(reissuecard, trans);
                    }
                    else
                    {
                        reissuecard.Status = WFAuditStatus.InReview;
                        reissuecard.IsCancel = WFAuditCancelStatus.Cancel;
                        wfReissuecardRepository.Update(reissuecard, trans);
                    }
                    wfReissuecardRepository.DBSession.Commit();
                    if (auditStatus != WFAuditStatus.Through)
                    {
                        PushAuditMessage(sendAccount, reissuecard.Id, WFTTemplateTypeEnum.ReissueCard, "你有已审批的补卡申请已撤销", "审批撤销通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    else
                    {
                        PushAuditMessage(sendAccount, reissuecard.Id, WFTTemplateTypeEnum.ReissueCard, "你有待审批的补卡申请", "审批通知", empId, SysTemPushTypeEnum.Audit);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "ReissueCardUndo");
                    wfReissuecardRepository.DBSession.Rollback("ReissueCardUndo");
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 撤销删除节点相关信息
        /// <summary>
        /// 删除审核关联节点信息
        /// </summary>
        /// <param name="workFlowId"></param>
        /// <param name="templateType">模板类型</param>
        /// <param name="wFAuditStatus">申请审批状态</param>
        /// <param name="trans">事务</param>
        /// <param name="sendAccount">推送信息账号</param>
        public void DeleteAuditInfo(int workFlowId, int templateType, WFAuditStatus wFAuditStatus, IDbTransaction trans, out List<EmAccoutIdModel> sendAccount)
        {
            sendAccount = new List<EmAccoutIdModel>();
            List<Rb_Workflow_AuditRelevance_Extend> auditRelevanceList = auditRelevanceRepository.GetAuditRelevanceList(workFlowId, templateType);
            //审批中撤销(删除未审核人记录信息)
            if (wFAuditStatus != WFAuditStatus.Through)
            {
                List<Rb_Workflow_Auditrecord_Extend> auditRecordList = auditrecordRepository.GetAuditRecordList(workFlowId, templateType);
                sendAccount = auditRecordList.Where(t => t.AuditStatus == WFRrocessStatus.AuditThrough).Select(t => new EmAccoutIdModel() { EmAccount = t.EmLoginMobile, EmployeeId = t.AuditEmId ?? 0 }).ToList();
                #region 删除未审核人记录
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_Auditrecord.WorkFlowId),
                        FiledValue = workFlowId,
                        OperatorEnum = OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_Auditrecord.TemplateType),
                        FiledValue = templateType,
                        OperatorEnum = OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_Auditrecord.AuditStatus),
                        FiledValue = (int)WFRrocessStatus.NotAudit,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                auditrecordRepository.Delete(whereHelpers, trans);
                #endregion
            }
            else//审批完成撤销
            {
                #region 修改除第一个审核节点外信息
                {

                    IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(Rb_Workflow_AuditRelevance.Stauts), WFRrocessStatus.NotAudit },
                    { nameof(Rb_Workflow_AuditRelevance.ToAuditId), "" },
                    { nameof(Rb_Workflow_AuditRelevance.AuditedId), "" }
                };

                    IList<WhereHelper> whereHelpers = new List<WhereHelper>
                    {
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_AuditRelevance.WorkFlowId),
                            FiledValue = workFlowId,
                            OperatorEnum = OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_AuditRelevance.TemplateType),
                            FiledValue = templateType,
                            OperatorEnum = OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_AuditRelevance.Sort),
                            FiledValue = 1,
                            OperatorEnum = OperatorEnum.NotEqual
                        }
                    };
                    auditRelevanceRepository.Update(fileds, whereHelpers, trans);
                }
                #endregion

                #region 删除审核人记录
                {                    
                    List<Rb_Workflow_Auditrecord_Extend> auditRecordList = auditrecordRepository.GetAuditRecordList(workFlowId, templateType);

                    #region 修改第一个节点信息
                    //第一个审核节点信息
                    Rb_Workflow_AuditRelevance_Extend firstAuditRelevance = auditRelevanceList.Where(t => t.Sort == 1).FirstOrDefault();
                    //第一个节点审核人信息
                    List<Rb_Workflow_Auditrecord_Extend> firstAuditRecordList = auditRecordList.Where(t => t.AuditId == firstAuditRelevance.Id).ToList();
                    sendAccount = auditRecordList.Where(t => t.AuditId == firstAuditRelevance.Id).Select(t => new EmAccoutIdModel() { EmAccount = t.EmLoginMobile, EmployeeId = t.AuditEmId ?? 0 }).ToList();
                    firstAuditRelevance.ToAuditId = string.Join(",", firstAuditRecordList.Select(t => t.AuditEmId));
                    firstAuditRelevance.AuditedId = "";
                    firstAuditRelevance.Stauts = WFRrocessStatus.NotAudit;
                    auditRelevanceRepository.Update(firstAuditRelevance, trans);
                    #endregion

                    #region 修改第一个节点审核人状态
                    IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(Rb_Workflow_Auditrecord.AuditStatus), WFRrocessStatus.NotAudit }
                };

                    IList<WhereHelper> auditrecordWhereHelpers = new List<WhereHelper>
                    {
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_Auditrecord.WorkFlowId),
                            FiledValue = workFlowId,
                            OperatorEnum = OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_Auditrecord.TemplateType),
                            FiledValue = templateType,
                            OperatorEnum = OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_Auditrecord.AuditId),
                            FiledValue = firstAuditRelevance.Id,
                            OperatorEnum = OperatorEnum.Equal
                        }
                    };
                    auditrecordRepository.Update(fileds, auditrecordWhereHelpers, trans);
                    #endregion

                    #region 删除除第一个节点外的审核人
                    IList<WhereHelper> whereHelpers = new List<WhereHelper>
                    {
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_Auditrecord.WorkFlowId),
                            FiledValue = workFlowId,
                            OperatorEnum = OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_Auditrecord.TemplateType),
                            FiledValue = templateType,
                            OperatorEnum = OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                            FiledName = nameof(Rb_Workflow_Auditrecord.AuditId),
                            FiledValue = firstAuditRelevance.Id,
                            OperatorEnum = OperatorEnum.NotEqual
                        }
                    };
                    auditrecordRepository.Delete(whereHelpers, trans);
                    #endregion

                }
                #endregion

            }

            #region 删除抄送人
            {
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditRelevance.WorkFlowId),
                        FiledValue = workFlowId,
                        OperatorEnum = OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_AuditRelevance.TemplateType),
                        FiledValue = templateType,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                copyToPeopleRepository.Delete(whereHelpers, trans);
            }
            #endregion
        }
        #endregion

        #endregion

        #region 审批消息推送
        /// <summary>
        /// 审批消息推送
        /// </summary>
        /// <param name="account">账号列表</param>
        /// <param name="workFlowId">工作id</param>
        /// <param name="templateType">模板类型</param>
        /// <param name="content">通知内容</param>
        /// <param name="title">标题</param>
        /// <param name="empId">当前操作人id</param>
        /// <param name="type">日志类型</param>
        public void PushAuditMessage(List<EmAccoutIdModel> account, int workFlowId, WFTTemplateTypeEnum templateType, string content, string title, int? empId, SysTemPushTypeEnum type)
        {
            if (account != null && account.Count > 0)
            {
                Dictionary<string, object> appExtras = new Dictionary<string, object>
                {
                    { "jumpUrl", $"vt://approvalDetail/view?title={title}&workFlowId={workFlowId}&templateType={(int)templateType}" }
                };
                //var url = new { workFlowId, templateType = (int)templateType };
                //Dictionary<string, object> webExtras = new Dictionary<string, object>
                //{
                //    { "jumpUrl",JsonConvert.SerializeObject(url) }
                //};
                Dictionary<string, object> webExtras = new Dictionary<string, object>
                {
                    { "jumpUrl",$"/forMyApproval?workFlowId={workFlowId}&templateType={(int)templateType}" }
                };
                //JPushService.PushMessage(account, empId, content, title, type, appExtras);
                //IMService.PushMessage(account, empId, content, title, type, SystemPushLogTypeEnum.XMApp, appExtras);
                //WebPushService.PushMessage(account, empId, content, title, type, SystemPushLogTypeEnum.Web, webExtras);
                //IMService.PushMessage(account, empId, content, title, type, SystemPushLogTypeEnum.Web, webExtras);
            }
        }
        #endregion
        /// <summary>
        /// 获取签到列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dmodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<Rb_Workflow_SignIn_Extend> GetSignInPageList(int pageIndex, int pageSize, Rb_Workflow_SignIn_Extend dmodel, out long count)
        {
            return SignInModule.GetPageList(pageIndex, pageSize, dmodel, out count);
        }
        /// <summary>
        /// 签到管理
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dmodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<Rb_Workflow_SignIn_Extend> GetSignInManagementPageList(int pageIndex, int pageSize, Rb_Workflow_SignIn_Extend dmodel, out long count)
        {
            return SignInModule.GetSignInManagementPageList(pageIndex, pageSize, dmodel, out count);
        }
        /// <summary>
        /// 新增修改签到
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public bool SetSignIn(Rb_Workflow_SignIn_Extend dmodel)
        {
            ImageOperation(dmodel.Images, out List<string> imgList);
            dmodel.Image = JsonConvert.SerializeObject(imgList);
            if (dmodel.Id > 0)
            {
                //修改
                IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(Rb_Workflow_SignIn_Extend.Image), dmodel.Image },
                    { nameof(Rb_Workflow_SignIn_Extend.Remarks),dmodel.Remarks}
                };
                IList<WhereHelper> whereHelpers = new List<WhereHelper>
                {
                    new WhereHelper()
                    {
                        FiledName = nameof(Rb_Workflow_SignIn_Extend.Id),
                        FiledValue = dmodel.Id,
                        OperatorEnum = OperatorEnum.Equal
                    }
                };
                return SignInModule.Update(fileds, whereHelpers);
            }
            else
            {//新增
                return SignInModule.Insert(dmodel.RefMapperTo<Rb_Workflow_SignIn>()) > 0;
            }
        }
        /// <summary>
        /// 根据id获取签到详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Rb_Workflow_SignIn_Extend GetSignIn(int Id)
        {
            var model = SignInModule.GetEntity(Id).RefMapperTo<Rb_Workflow_SignIn_Extend>();
            string Name = "";
            if (model != null)
            {
                var emodel = accountRepository.GetEmployeeInfo(model.EmployeeId ?? 0);
                Name = emodel.EmployeeName;
            }
            model.EmName = Name;
            return model;
        }

        /// <summary>
        /// 获取用户该月所有的签到
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="groupId">部门编号</param>
        /// <param name="Month">月份</param>
        /// <returns></returns>
        public List<SignInModel> GetSignInInfo(int uid, int groupId, string Month)
        {
            //查询出出差的
            var TraveList = wfEvectionRepository.GetSignInInfoForEvection(uid, Month);
            //查询出外出的
            var GooutList = wfGoOutRepository.GetSignInInfoForGoout(uid, Month);
            string StartTime = Convert.ToDateTime(Month).ToString("yyyy-MM") + "-01";
            string EndTime = Convert.ToDateTime(Convert.ToDateTime(Month).AddMonths(1).ToString("yyyy-MM") + "-01").AddDays(-1).ToString("yyyy-MM-dd");
            //在获取当月的所有签到记录
            Rb_Workflow_SignIn_Extend dmodel = new Rb_Workflow_SignIn_Extend()
            {
                EmployeeId = uid,
                RB_GroupId = groupId,
                StartTime = StartTime,
                EndTime = EndTime
            };
            var SignList = SignInModule.GetPageList(1, int.MaxValue, dmodel, out long count);
            List<string> TimeStr = new List<string>();
            string StartT = "";
            string EndT = "";
            foreach (var item in TraveList)
            {
                StartT = item.StartTime.Value.ToString("yyyy-MM-dd");
                EndT = item.EndTime.Value.ToString("yyyy-MM-dd");
                while (true)
                {
                    if (StartTime != EndTime && Convert.ToDateTime(EndT) > Convert.ToDateTime(StartT))
                    {
                        TimeStr.Add(StartT);
                        item.StartTime = item.StartTime.Value.AddDays(1);
                        StartT = item.StartTime.Value.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        TimeStr.Add(StartT);
                        break;
                    }
                }
            }
            foreach (var item in GooutList)
            {
                StartT = item.StartTime.Value.ToString("yyyy-MM-dd");
                EndT = item.EndTime.Value.ToString("yyyy-MM-dd");
                while (true)
                {
                    if (StartTime != EndTime && Convert.ToDateTime(EndT) > Convert.ToDateTime(StartT))
                    {
                        TimeStr.Add(StartT);
                        item.StartTime = item.StartTime.Value.AddDays(1);
                        StartT = item.StartTime.Value.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        TimeStr.Add(StartT);
                        break;
                    }
                }
            }
            //处理日期
            TimeStr = TimeStr.Where(x => x.Contains(Month)).Distinct().OrderBy(x => x).ToList();
            List<SignInModel> signInModels = new List<SignInModel>();
            foreach (var item in TimeStr)
            {
                SignInModel signInModel = new SignInModel()
                {
                    DateStr = item,
                    Count = SignList.Where(x => x.SignInTime.Value.ToString("yyyy-MM-dd") == item).Count()
                };
                signInModels.Add(signInModel);
            }
            return signInModels;
        }
        #endregion

        /// <summary>
        /// 通过条件查询模板列表
        /// </summary>
        /// <param name="GroupId"></param>
        /// <param name="Type"></param>
        /// <param name="TempLateClass"></param>
        /// <param name="TemplateType"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Template> GetTempateList(int GroupId, int Type, int TempLateClass, int TemplateType)
        {
            return workFlowTemplateRepository.GetTempateList(GroupId, Type, TempLateClass, TemplateType);
        }

    }
}
