using Edu.Common.Enum.User;
using Edu.Model.Entity.User;
using Edu.Model.ViewModel.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Edu.Repository.User
{
    /// <summary>
    /// 请假信息扩展表
    /// </summary>
    public partial class Rb_Workflow_AskforleaveRepository : BaseRepository<Rb_Workflow_Askforleave>
    {
        /// <summary>
        /// 获取请假列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dmodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Askforleave_Extend> GetAskforleavePageList(int pageIndex, int pageSize, Rb_Workflow_Askforleave_Extend dmodel, out long count)
        {
            string where = $@" where 1=1 and t.{nameof(Rb_Workflow_Askforleave.RB_GroupId)}={dmodel.RB_GroupId}";
            if (dmodel.RB_BranchId.HasValue && dmodel.RB_BranchId > -1)
            {
                where += $@" and t.{nameof(Rb_Workflow_Askforleave.RB_BranchId) }={dmodel.RB_BranchId}";
            }
            if (dmodel.CreateBy.HasValue && dmodel.CreateBy > 0)
            {
                where += $@" and t.{nameof(Rb_Workflow_Askforleave.CreateBy)}={dmodel.CreateBy}";
            }
            if (dmodel.Status.HasValue && (int)dmodel.Status > 0)
            {
                where += $@" and t.{nameof(Rb_Workflow_Askforleave.Status)}={(int)dmodel.Status}";
            }
            if (dmodel.ToAuditId.HasValue && dmodel.ToAuditId > 0)
            {
                where += $@" and CONCAT(',',t.ToAuditIdStr,',') like '%,{dmodel.ToAuditId},%'";
            }
            if (dmodel.AuditedId.HasValue && dmodel.AuditedId > 0)
            {
                where += $@" and CONCAT(',',t.AuditedIdStr,',') like '%,{dmodel.AuditedId},%'";
            }
            string sql = $@"SELECT * FROM(select e.EmName,
case when ask.`Status`=1 then
(select group_concat(EmName) from rb_employee where instr(concat(',',(select case when ToAuditId='' then '0' else ToAuditId END from rb_workflow_auditrelevance audr 
where audr.WorkFlowId=ask.Id and audr.TemplateType={(int)WFTTemplateTypeEnum.AskForLeave} and audr.Stauts=1 ORDER BY audr.Sort ASC limit 0,1),','),concat(',',EmployeeId,',')))
ELSE '' END as ToAuditName,
case when ask.`Status`=1 then
(select ToAuditId from rb_workflow_auditrelevance audr where audr.WorkFlowId=ask.Id and audr.TemplateType={(int)WFTTemplateTypeEnum.AskForLeave} and audr.Stauts=1 ORDER BY audr.Sort ASC limit 0,1)
ELSE '' END as ToAuditIdStr,
(select group_concat(AuditedId) from rb_workflow_auditrelevance audr where audr.WorkFlowId=ask.Id and audr.TemplateType={(int)WFTTemplateTypeEnum.AskForLeave} and audr.AuditedId!='' ORDER BY audr.Sort ASC) as AuditedIdStr
,ask.* from rb_workflow_askforleave ask left JOIN rb_employee e on ask.CreateBy=e.EmployeeId
)t {where}  ORDER BY t.CreateTime DESC";
            var pageList = GetPage<Rb_Workflow_Askforleave_Extend>(pageIndex, pageSize, out count, sql).ToList();
            return pageList;
        }


        /// <summary>
        /// 根据id 获取数据详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Rb_Workflow_Askforleave_Extend GetModel(int Id)
        {
            string where = $@" where 1=1 and ask.Id ={Id}";
            return Get<Rb_Workflow_Askforleave_Extend>($@"select ask.*,e.EmName,e.EmAccount,e.EmLoginMobile,e.EmPhoto from Rb_Workflow_Askforleave ask left join rb_employee e on ask.CreateBy=e.EmployeeId {where}").FirstOrDefault();
        }


        /// <summary>
        /// 根据id 获取请假及模板详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Rb_Workflow_Askforleave_Extend GetEntityDetial(int id)
        {
            return Get<Rb_Workflow_Askforleave_Extend>($@"SELECT a.*,e.EmName,e.EmPhoto,t.TemplateType from rb_workflow_askforleave a 
                    LEFT JOIN rb_employee e on a.CreateBy = e.EmployeeId
                    LEFT JOIN rb_workflow_template t on t.Id = a.TemplateId
                    where a.Id = {id}").FirstOrDefault();
        }
        /// <summary>
        /// 验证改时间段是否有重复数据
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>true 有重复数据，fasle没有重复数据</returns>
        public bool ValverifyTime(int empId, string startTime, string endTime)
        {
            return Get<Rb_Workflow_Askforleave_Extend>($"SELECT Id from rb_workflow_askforleave where CreateBy = {empId} and (('{startTime}'>=StartTime and '{startTime}'<=EndTime) or ('{endTime}'>=StartTime and '{endTime}'<=EndTime)) and (((`Status` = 1 or `Status` = 5) AND IsCancel = 1) or ((`Status` = 1 or `Status` = 4 ) AND IsCancel = 2))").Count() > 0 ? true : false;
        }

        /// <summary>
        /// 所有申请验证该时间段是否有重复数据
        /// </summary>
        /// <param name="empId">员工id</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>true 有重复数据，fasle没有重复数据</returns>
        public List<Rb_Workflow_Askforleave_Extend> AllAuditValverifyTime(int empId, string startTime, string endTime)
        {
            return Get<Rb_Workflow_Askforleave_Extend>($@"select t.Id,t.TemplateType from ((SELECT Id, {(int)WFTTemplateTypeEnum.AskForLeave} as TemplateType from rb_workflow_askforleave where CreateBy = {empId} and (('{startTime}'>=StartTime and '{startTime}'<=EndTime) or ('{endTime}'>=StartTime and '{endTime}'<=EndTime)) and (((`Status` = {(int)WFAuditStatus.InReview} or `Status` = {(int)WFAuditStatus.Through}) AND IsCancel = {(int)WFAuditCancelStatus.Normal}) or ((`Status` = {(int)WFAuditStatus.InReview} or `Status` = {(int)WFAuditStatus.NotThrough} ) AND IsCancel = {(int)WFAuditCancelStatus.Cancel})))
              union 
            (SELECT e.Id, {(int)WFTTemplateTypeEnum.Evection} as TemplateType from rb_workflow_evection e INNER JOIN rb_workflow_travel t on e.Id = t.EvectionId  where e.CreateBy = {empId} and (('{startTime}'>=t.StartTime and '{startTime}'<=t.EndTime) or ('{endTime}'>=t.StartTime and '{endTime}'<=t.EndTime)) and (((e.`Status` = {(int)WFAuditStatus.InReview} or e.`Status` = {(int)WFAuditStatus.Through}) AND e.IsCancel = {(int)WFAuditCancelStatus.Normal}) or ((e.`Status` = {(int)WFAuditStatus.InReview} or e.`Status` = {(int)WFAuditStatus.NotThrough} ) AND e.IsCancel = {(int)WFAuditCancelStatus.Cancel})))
             union
            (SELECT Id,{(int)WFTTemplateTypeEnum.Goout} as TemplateType from rb_workflow_goout where CreateBy = {empId} and (('{startTime}'>=StartTime and '{startTime}'<=EndTime) or ('{endTime}'>=StartTime and '{endTime}'<=EndTime)) and (((`Status` = {(int)WFAuditStatus.InReview} or `Status` = {(int)WFAuditStatus.Through}) AND IsCancel = {(int)WFAuditCancelStatus.Normal}) or ((`Status` = {(int)WFAuditStatus.InReview} or `Status` = {(int)WFAuditStatus.NotThrough} ) AND IsCancel = {(int)WFAuditCancelStatus.Cancel})))) as t").ToList();
        }
        /// <summary>
        /// 月度统计请假时长详情
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="eid"></param>
        /// <param name="AskLeaveType"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Askforleave_Extend> GetAskLeaveInfo(string StartTime, string EndTime, int eid, int AskLeaveType) {
            string where = $@" where 1=1 and IsCancel=1 and {nameof(Rb_Workflow_Askforleave.Status)}={(int)WFAuditStatus.Through}";
            where += $@" and (({nameof(Rb_Workflow_Askforleave.StartTime)}>='{StartTime}' and {nameof(Rb_Workflow_Askforleave.EndTime)}<='{EndTime}') 
                         or ({nameof(Rb_Workflow_Askforleave.StartTime)}<'{StartTime}' and {nameof(Rb_Workflow_Askforleave.EndTime)}>'{StartTime}')
                         or ({nameof(Rb_Workflow_Askforleave.StartTime)}<'{EndTime}' and {nameof(Rb_Workflow_Askforleave.EndTime)}>'{EndTime}'))";
            where += $@" and {nameof(Rb_Workflow_Askforleave.CreateBy)}={eid}";
            where += $@" and {nameof(Rb_Workflow_Askforleave.AskforleaveType)}={AskLeaveType}";
            return Get<Rb_Workflow_Askforleave_Extend>($@" select * from rb_workflow_askforleave {where}").ToList();
        }
        /// <summary>
        /// 获取OA考勤分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dmodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<Rb_Workflow_Askforleave_Extend> GetOAPageList(int pageIndex, int pageSize, Rb_Workflow_Askforleave_Extend dmodel, out long count)
        {
            string where = $@" where 1=1 ";
            if (dmodel.ToAuditId.HasValue && dmodel.ToAuditId > 0)
            {
                where += $@" and CONCAT(',',t.ToAuditIdStr,',') like '%,{dmodel.ToAuditId},%'";
            }
            if (dmodel.AuditedId.HasValue && dmodel.AuditedId > 0)
            {
                where += $@" and CONCAT(',',t.AuditedIdStr,',') like '%,{dmodel.AuditedId},%'";
            }
            string WhereIn = "";
            if (dmodel.RB_BranchId.HasValue && dmodel.RB_BranchId > -1)
            {
                WhereIn += $@" and a.{nameof(Rb_Workflow_Askforleave.RB_BranchId) }={dmodel.RB_BranchId}";
            }
            if (dmodel.CreateBy.HasValue && dmodel.CreateBy > 0)
            {
                WhereIn += $@" and a.{nameof(Rb_Workflow_Askforleave.CreateBy)}={dmodel.CreateBy}";
            }
            if (dmodel.Status.HasValue && (int)dmodel.Status > 0)
            {
                WhereIn += $@" and a.{nameof(Rb_Workflow_Askforleave.Status)}={(int)dmodel.Status}";
            }
            if (dmodel.TemplateId.HasValue && dmodel.TemplateId > 0)
            {
                WhereIn += $@" and t.TemplateType={dmodel.TemplateId}";
            }
            if (dmodel.StartTime.HasValue) {
                WhereIn += $@" and a.CreateTime>='{dmodel.StartTime.Value.ToString("yyyy-MM-dd")+" 00:00:00"}'";
            }
            if (dmodel.EndTime.HasValue)
            {
                WhereIn += $@" and a.CreateTime<='{dmodel.EndTime.Value.ToString("yyyy-MM-dd")+" 23:59:59"}'";
            }
            string sql = $@"SELECT * FROM(select e.EmName,e.BName,
case when ask.`Status`=1 then
(select ToAuditId from rb_workflow_auditrelevance audr where audr.WorkFlowId=ask.Id and audr.TemplateType=ask.TemplateType and audr.Stauts=1 ORDER BY audr.Sort ASC limit 0,1)
ELSE '' END as ToAuditIdStr,
(select group_concat(AuditedId) from rb_workflow_auditrelevance audr where audr.WorkFlowId=ask.Id and audr.TemplateType=ask.TemplateType and audr.AuditedId!='' ORDER BY audr.Sort ASC) as AuditedIdStr
,ask.* from 
(
  (SELECT a.Id,a.`Status`,a.RB_BranchId,a.CreateBy,a.CreateTime,t.TemplateType,t.`Name` as TemplateName FROM rb_workflow_askforleave a INNER JOIN rb_workflow_template t on t.id = a.TemplateId where a.RB_GroupId={dmodel.RB_GroupId} {WhereIn}) UNION 
  (SELECT a.Id,a.`Status`,a.RB_BranchId,a.CreateBy,a.CreateTime,t.TemplateType,t.`Name` as TemplateName FROM rb_workflow_evection a INNER JOIN rb_workflow_template t on t.id = a.TemplateId where a.RB_GroupId={dmodel.RB_GroupId} {WhereIn}) UNION
  (SELECT a.Id,a.`Status`,a.RB_BranchId,a.CreateBy,a.CreateTime,t.TemplateType,t.`Name` as TemplateName FROM rb_workflow_goout a INNER JOIN rb_workflow_template t on t.id = a.TemplateId where a.RB_GroupId={dmodel.RB_GroupId} {WhereIn}) UNION 
  (SELECT a.Id,a.`Status`,a.RB_BranchId,a.CreateBy,a.CreateTime,t.TemplateType,t.`Name` as TemplateName FROM rb_workflow_reissuecard a INNER JOIN rb_workflow_template t on t.id = a.TemplateId where a.RB_GroupId={dmodel.RB_GroupId} {WhereIn}) 
)
ask left JOIN rb_employee e on ask.CreateBy=e.EmployeeId 
)t {where}  ORDER BY t.CreateTime DESC";
            var pageList = GetPage<Rb_Workflow_Askforleave_Extend>(pageIndex, pageSize, out count, sql).ToList();
            return pageList;
        }

        /// <summary>
        /// 根据查询条件获取请假信息
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public List<Rb_Workflow_Askforleave_Extend> GetListExt(Rb_Workflow_Askforleave_Extend where)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(" SELECT * FROM Rb_Workflow_Askforleave WHERE 1=1 AND IsCancel=1 ");
            if (where != null)
            {
                if (where.CreateBy > 0)
                {
                    builder.AppendFormat(" AND {0}={1} ", nameof(Rb_Workflow_Askforleave_Extend.CreateBy), where.CreateBy);
                }
                if (where.StartTime != null)
                {
                    builder.AppendFormat(" AND {0}>='{1}' ", nameof(Rb_Workflow_Askforleave_Extend.StartTime), Convert.ToDateTime(where.StartTime).ToString("yyyy-MM-dd"));
                }
            }
            return Get<Rb_Workflow_Askforleave_Extend>(builder.ToString()).ToList();
        }
    }
}
