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

namespace Edu.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class WorkFlowManagementController : BaseController
    {
        /// <summary>
        /// 流程管理处理类
        /// </summary>
        public WorkFlowManagementModule WorkflowManagementmodule = new WorkFlowManagementModule();



        /// <summary>
        /// 根据where条件 查询列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetTemplateList()
        {
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int BranchId = parms.GetInt("BranchId", -1);
            if (BranchId >= 0)
            {
                userInfo.School_Id = BranchId;
            }
            var list = WorkflowManagementmodule.GetTemplateList(userInfo);
            var AuditType = EnumHelper.EnumToList(typeof(WFTTemplateTypeEnum));
            foreach (var item in AuditType)
            {
                int count = list.Where(x => x.TemplateType == (WFTTemplateTypeEnum)(Convert.ToInt32(item.Id))).Count();
                if (count <= 0)
                {
                    Rb_Workflow_Template tmodel = new Rb_Workflow_Template();
                    string[] keyStr = item.Name.Split('|');
                    if (keyStr.Count() > 1)
                    {
                        tmodel = new Rb_Workflow_Template
                        {
                            Id = 0,
                            Icon = keyStr[1],
                            Name = keyStr[0],
                            GroupType = (WFTGroupTypeEnum)(Convert.ToInt32(keyStr[2])),
                            Status = 2,
                            TemplateType = (WFTTemplateTypeEnum)(Convert.ToInt32(item.Id))
                        };
                    }
                    list.Add(tmodel);
                }
            }
            list = list.OrderBy(x => x.TemplateType).ToList();
            var GroupList = Common.Plugin.EnumHelper.EnumToList(typeof(WFTGroupTypeEnum));
            DataTable dtR = new DataTable();
            dtR.Columns.Add("GroupName", typeof(string));
            dtR.Columns.Add("GroupNum", typeof(string));
            dtR.Columns.Add("List", typeof(object));
            dtR.AcceptChanges();
            foreach (var item in GroupList)
            {
                var dr = dtR.NewRow();
                int id = Convert.ToInt32(item.Id);
                var TList = list.Where(x => x.GroupType == (WFTGroupTypeEnum)id).ToList();
                dr["GroupName"] = item.Name;
                dr["GroupNum"] = TList.Count;
                dr["List"] = TList.Select(x => new
                {
                    Icon = Config.GetFileUrl(x.Icon),
                    GroupTypeName = x.GroupType.ToName(),
                    x.Id,
                    x.Name,
                    x.TemplateType,
                    x.GroupType,
                    x.Status,
                    UpdateTime = x.UpdateTime == null ? "" : x.UpdateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                });
                dtR.Rows.Add(dr);
            }
            return ApiResult.Success("", dtR);
        }

        /// <summary>
        /// 根据主键id获取数据
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetTemplate()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int TemplateId = parm.GetInt("TemplateId");
            Rb_Workflow_Template dmodel = WorkflowManagementmodule.GetTemplate(TemplateId);
            return ApiResult.Success("请求成功！", new
            {
                dmodel.AuditDistinct,
                dmodel.GroupType,
                dmodel.Icon,
                dmodel.Id,
                dmodel.Name,
                dmodel.NotificationCP,
                dmodel.Status
                ,
                dmodel.TemplateType
            });
        }

        /// <summary>
        /// 新增和修改
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult SetTemplate()
        {
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int BranchId = parms.GetInt("BranchId", -1);
            if (BranchId >= 0)
            {
                userInfo.School_Id = BranchId;
            }
            Rb_Workflow_Template demodel = JsonConvert.DeserializeObject<Rb_Workflow_Template>(RequestParm.Msg.ToString());
            if (!demodel.TemplateType.HasValue)
            {
                return ApiResult.ParamIsNull("模板类型不能为空！");
            }
            if (!demodel.Status.HasValue)
            {
                return ApiResult.ParamIsNull("状态参数不能为空！");
            }
            bool flag = WorkflowManagementmodule.SetTemplate(demodel, userInfo.Group_Id, userInfo.School_Id, userInfo.Id);
            if (flag)
                return ApiResult.Success();
            else
                return ApiResult.Failed("请求失败！");
        }

        /// <summary>
        /// 获取默认审核条件
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetDefaultCondition()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int TemplateId = parm.GetInt("TemplateId");
            if (TemplateId <= 0)
            {
                return ApiResult.ParamIsNull("参数不正确！");
            }
            var model = WorkflowManagementmodule.GetDefaultCondition(TemplateId);
            return ApiResult.Success("", new { AuditList = model.AuditList ?? new List<Rb_Workflow_Audit_Extend>(), AuditUserList = model.AuditUserList ?? new List<Rb_Workflow_Audituser_Extend>(), model.DayHour, model.Id, model.Sort, model.TemplateType, model.TemplateTypeName });
        }

        /// <summary>
        /// 获取分条件审核条件
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetOtherConditionList()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int TemplateId = parm.GetInt("TemplateId");
            if (TemplateId <= 0)
            {
                return ApiResult.ParamIsNull("参数不正确！");
            }
            var list = WorkflowManagementmodule.GetOtherConditionList(TemplateId);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 获取分条件审核详情
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetConditionAndAuditInfo()
        {
            JObject jObject = JObject.Parse(RequestParm.Msg.ToString());
            int ConditionId = jObject.GetInt("ConditionId", 0);
            if (ConditionId <= 0)
            {
                return ApiResult.ParamIsNull("参数不正确！");
            }
            var model = WorkflowManagementmodule.GetConditionAndAuditUser(ConditionId);
            return ApiResult.Success("", model);
        }

        /// <summary>
        /// 获取新增条件  
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetAskForLeaveType()
        {
            JObject jObject = JObject.Parse(RequestParm.Msg.ToString());
            int TemplateId = jObject.GetInt("TemplateId", 0);
            if (TemplateId <= 0)
            {
                return ApiResult.ParamIsNull("参数不正确！");
            }
            Rb_Workflow_Template dmodel = WorkflowManagementmodule.GetTemplate(TemplateId);
            if (dmodel == null)
            {
                return ApiResult.ParamIsNull("参数不正确！");
            }
            var AuditType = EnumHelper.EnumToList(typeof(AskforleaveTypeEnum));
            List<AskforleaveTypeList> asklist = new List<AskforleaveTypeList>();
            foreach (var item in AuditType)
            {
                AskforleaveTypeList askmodel = new AskforleaveTypeList
                {
                    Id = item.Id,
                    Name = item.Name
                };
                asklist.Add(askmodel);
            }
            int TemplateType = (int)dmodel.TemplateType;
            string TemplateTypeName = dmodel.Name;
            asklist = asklist.OrderBy(x => x.Id).ToList();
            return ApiResult.Success("", new { TemplateType, TemplateTypeName, askList = asklist });
        }

        /// <summary>
        /// 保存分条件
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult SetOtherCondition()
        {
            Rb_Workflow_Condition_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_Condition_Extend>(RequestParm.Msg.ToString());
            if (!demodel.TemplateId.HasValue)
            {
                return ApiResult.ParamIsNull("请传所属模版id!");
            }
            if (demodel.TemplateType == (int)WFTTemplateTypeEnum.AskForLeave && (demodel.AskforleaveType == "" || demodel.AskforleaveType == "[]"))
            {
                return ApiResult.ParamIsNull("请选择请假类型！");
            }
            if (!demodel.DayHour.HasValue)
            {
                return ApiResult.ParamIsNull("请选择时间类型！");
            }
            if (!demodel.ConditionType.HasValue)
            {
                return ApiResult.ParamIsNull("请选择等式类型！");
            }
            if (demodel.ConditionType == (int)EquationTypeEnum.InBetween)
            {
                if (!demodel.StartValue.HasValue)
                {
                    return ApiResult.ParamIsNull("请输入起始值！");
                }
                if (!demodel.StartType.HasValue)
                {
                    return ApiResult.ParamIsNull("请输入起始类型！");
                }
                if (!demodel.EndValue.HasValue)
                {
                    return ApiResult.ParamIsNull("请输入结束值！");
                }
                if (!demodel.EndType.HasValue)
                {
                    return ApiResult.ParamIsNull("请输入结束类型！");
                }
            }
            else
            {
                if (!demodel.StartValue.HasValue)
                {
                    return ApiResult.ParamIsNull("请输入起始值！");
                }
            }
            //if (demodel.Sort == 0)
            //{
            //    return ApiResult.ParamIsNull("默认条件排序不能为0！");
            //}
            if (demodel.AuditList != null && demodel.AuditList.Count > 0)
            {
                foreach (var item in demodel.AuditList)
                {
                    if (!item.AuditType.HasValue)
                    {
                        return ApiResult.ParamIsNull("请输入审核人类别！");
                    }
                    if (!item.AuditWay.HasValue)
                    {
                        return ApiResult.ParamIsNull("请选择审核方式！");
                    }
                    if (item.AuditType == 2)
                    {
                        if (item.AuditUserList.Count <= 0)
                        {
                            return ApiResult.ParamIsNull("指定成员尚未选择审核人！");
                        }
                    }
                    else
                    {
                        if (!item.RoleOrInitiator.HasValue)
                        {
                            return ApiResult.ParamIsNull("发起人的主管或者角色为空！");
                        }
                    }
                }
            }

            bool flag = WorkflowManagementmodule.SetOtherCondition(demodel);
            if (flag)
            {
                return ApiResult.Success("");
            }
            else
            {
                return ApiResult.Failed("请求失败！");
            }
        }

        /// <summary>
        /// 删除分条件
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult DelOtherCondition()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int ConditionId = parm.GetInt("ConditionId", 0);
            if (ConditionId <= 0)
            {
                return ApiResult.ParamIsNull("条件id不能为空！");
            }
            bool flag = WorkflowManagementmodule.DelOtherCondition(ConditionId);
            if (flag)
            {
                return ApiResult.Success("");
            }
            else
            {
                return ApiResult.Failed("请求失败！");
            }
        }

        /// <summary>
        /// 保存分条件
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult SetDefaultCondition()
        {
            Rb_Workflow_Condition_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_Condition_Extend>(RequestParm.Msg.ToString());
            if (!demodel.TemplateId.HasValue)
            {
                return ApiResult.ParamIsNull("所属模版id参数不存在！");
            }
            if (demodel.Id > 0)
            {
                if (WorkflowManagementmodule.GetDefaultConditionDistinct(demodel.TemplateId.Value, demodel.Id) > 0)
                {
                    return ApiResult.Failed("已存在多个默认条件！请核实");
                }
            }
            else
            {
                if (WorkflowManagementmodule.GetDefaultConditionDistinct(demodel.TemplateId.Value, 0) > 0)
                {
                    return ApiResult.Failed("条件id不存在！请核实");
                }
            }
            if (demodel.Sort != 0)
            {
                return ApiResult.ParamIsNull("默认条件排序需为0！");
            }
            if (demodel.AuditList != null && demodel.AuditList.Count > 0)
            {
                foreach (var item in demodel.AuditList)
                {
                    if (!item.AuditType.HasValue)
                    {
                        return ApiResult.ParamIsNull("请输入审核人类别！");
                    }
                    if (!item.AuditWay.HasValue)
                    {
                        return ApiResult.ParamIsNull("请选择审核类型！");
                    }
                    if (item.AuditType == 2)
                    {
                        if (item.AuditUserList.Count <= 0)
                        {
                            return ApiResult.ParamIsNull("指定成员尚未选择审核人！");
                        }
                    }
                    else
                    {
                        if (!item.RoleOrInitiator.HasValue)
                        {
                            return ApiResult.ParamIsNull("发起人的主管或者角色为空！");
                        }
                    }
                }
            }

            if (demodel.ConditionSortList != null && demodel.ConditionSortList.Count > 0)
            {
                int count = demodel.ConditionSortList.Where(x => x.Sort != 0).Select(x => x.Sort).Distinct().Count();
                if (count != demodel.ConditionSortList.Count)
                {
                    return ApiResult.ParamIsNull("分条件排序有重复！");
                }
            }

            bool flag = WorkflowManagementmodule.SetDefaultCondition(demodel);
            if (flag)
            {
                return ApiResult.Success("");
            }
            else
            {
                return ApiResult.Failed("请求失败！");
            }
        }

        /// <summary>
        /// 获取请假分页列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetAskforleavePageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            ResultPageModel pmodel = new ResultPageModel
            {
                PageIndex = JsonHelper.GetInt(parm, "PageIndex", 1),
                PageSize = JsonHelper.GetInt(parm, "PageSize", 20)
            };
            Rb_Workflow_Askforleave_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_Askforleave_Extend>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_Askforleave_Extend> data = WorkflowManagementmodule.GetAskforleavePageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.Id,
                AskforleaveType = x.AskforleaveType.ToName(),
                x.EmName,
                x.StartTime,
                x.EndTime,
                x.Duration,
                x.Description,
                x.Image,
                Status = x.Status.ToName(),
                x.ToAuditName,
                x.UpdateTime
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取出差分页列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetEvectionPageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            ResultPageModel pmodel = new ResultPageModel
            {
                PageIndex = JsonHelper.GetInt(parm, "PageIndex", 1),
                PageSize = JsonHelper.GetInt(parm, "PageSize", 20)
            };
            Rb_Workflow_Evection_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_Evection_Extend>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_Evection_Extend> data = WorkflowManagementmodule.GetEvectionPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.Id,
                x.EmName,
                x.Traveldays,
                x.Description,
                x.Remark,
                Status = x.Status.ToName(),
                x.ToAuditName,
                x.UpdateTime
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取外出分页列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetGoOutPageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            ResultPageModel pmodel = new ResultPageModel
            {
                PageIndex = JsonHelper.GetInt(parm, "PageIndex", 1),
                PageSize = JsonHelper.GetInt(parm, "PageSize", 20)
            };
            Rb_Workflow_GoOut_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_GoOut_Extend>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_GoOut_Extend> data = WorkflowManagementmodule.GetGoOutPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.Id,
                x.EmName,
                x.StartTime,
                x.EndTime,
                x.Duration,
                x.Description,
                x.Image,
                Status = x.Status.ToName(),
                x.ToAuditName,
                x.UpdateTime
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取补卡分页列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetReissuecardPageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            ResultPageModel pmodel = new ResultPageModel
            {
                PageIndex = JsonHelper.GetInt(parm, "PageIndex", 1),
                PageSize = JsonHelper.GetInt(parm, "PageSize", 20)
            };
            Rb_Workflow_Reissuecard_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_Reissuecard_Extend>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_Reissuecard_Extend> data = WorkflowManagementmodule.GetReissuecardPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.Id,
                x.EmName,
                x.AttendanceRecordId,
                x.ReissueCardTime,
                x.ReissuecardType,
                x.Description,
                x.Image,
                Status = x.Status.ToName(),
                x.ToAuditName,
                x.UpdateTime
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取OA考勤分页列表
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetOAPageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            ResultPageModel pmodel = new ResultPageModel
            {
                PageIndex = JsonHelper.GetInt(parm, "PageIndex", 1),
                PageSize = JsonHelper.GetInt(parm, "PageSize", 20)
            };
            Rb_Workflow_Askforleave_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_Askforleave_Extend>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_Askforleave_Extend> data = WorkflowManagementmodule.GetOAPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.Id,
                x.TemplateType,
                x.TemplateName,
                x.EmName,
                x.BName,
                ToAuditName = GetEmNameStr(x.ToAuditIdStr),
                AuditedName = x.Status == WFAuditStatus.Through ? "" : GetEmNameStr(x.AuditedIdStr),
                CreateTime = x.CreateTime != null ? x.CreateTime.Value.ToString("yyyy-MM-dd") : "",
                Status = x.Status.ToName()
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 根据id 获取员工姓名
        /// </summary>
        /// <param name="NameId"></param>
        /// <returns></returns>
        public string GetEmNameStr(string NameId)
        {
            if (!string.IsNullOrWhiteSpace(NameId))
            {
                var list = WorkflowManagementmodule.GetEmpList(NameId);
                return string.Join(",", list.Select(x => x.EmployeeName).ToList());
            }
            return "";
        }

        /// <summary>
        /// 根据模版id 获取可见范围的人
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult GetTempleteEmployee()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int TemplateId = parm.GetInt("TemplateId");
            var dmodel = WorkflowManagementmodule.GetTempleteEmployee(TemplateId);
            return ApiResult.Success("请求成功！", dmodel.Select(x => new { x.TypeId, x.Type }));
        }

        /// <summary>
        /// 设置模版可见范围
        /// </summary>
        /// <returns></returns>
        public virtual ApiResult SetTempleteEmployee()
        {
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int TemplateId = parm.GetInt("TemplateId");
            string EmployeeId = parm.GetStringValue("EmployeeIdArr");
            List<Rb_Workflow_Visualrange> list = JsonConvert.DeserializeObject<List<Rb_Workflow_Visualrange>>(EmployeeId);
            if (TemplateId <= 0)
            {
                return ApiResult.ParamIsNull("参数有误，请核实后再试！");
            }
            if (string.IsNullOrWhiteSpace(EmployeeId) || EmployeeId == "[]")
            {
                return ApiResult.ParamIsNull("选择的员工不能为空！");
            }
            if (list.Count <= 0)
            {
                return ApiResult.ParamIsNull("选择的员工不能为空！");
            }
            bool flag = WorkflowManagementmodule.AddTempleteEmployee(TemplateId, list);
            if (flag) return ApiResult.Success("");
            else
                return ApiResult.Failed("请求失败！");
        }

    }
}