using Edu.Model.ViewModel.User;
using Edu.Repository.User;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.User
{
    /// <summary>
    /// 部门处理类
    /// </summary>
    public class DepartmentModule
    {
        /// <summary>
        /// 部门仓储层对象
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();

        /// <summary>
        /// 账号仓储层对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 岗位仓储层对象
        /// </summary>
        private readonly RB_PostRepository postRepository = new RB_PostRepository();

        /// <summary>
        /// 部门岗位关联表仓储层对象
        /// </summary>
        private readonly RB_Department_PostRepository department_PostRepository = new RB_Department_PostRepository();

        /// <summary>
        /// 获取部门分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Department_ViewModel> GetDepartmentPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Department_ViewModel query)
        {
            var list = departmentRepository.GetDepartmentPageListRepository(pageIndex, pageSize, out rowsCount, query);
            List<RB_Department_ViewModel> parentList = new List<RB_Department_ViewModel>();
            List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
            List<RB_Department_Post_ViewModel> deptPostList = new List<RB_Department_Post_ViewModel>();
            if (list != null && list.Count > 0)
            {
                //查询部门列表
                string Ids = string.Join(",", list.Where(qitem => qitem.ParentId > 0).Select(qitem => qitem.ParentId));
                if (!string.IsNullOrEmpty(Ids))
                {
                    parentList = GetDepartmentListModule(new RB_Department_ViewModel() { QDeptIds = Ids });
                }
                //查询员工列表
                string persion = string.Join(",", list.Where(qitem => !string.IsNullOrEmpty(qitem.ManagerIds)).Select(qitem => qitem.ManagerIds));
                if (!string.IsNullOrEmpty(persion))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = persion });
                }

                string qDeptIds = string.Join(",", list.Select(qitem => qitem.DeptId));
                if (!string.IsNullOrEmpty(qDeptIds))
                {
                    deptPostList = department_PostRepository.GetDepartmentPostListRepository(new RB_Department_Post_ViewModel() { QDeptIds = qDeptIds });
                }
            }
            foreach (var item in list)
            {
                //部门
                item.ParentDeptName = parentList?.Where(qitem => qitem.DeptId == item.ParentId)?.FirstOrDefault()?.DeptName ?? "";
                //负责人
                string persionName = "";
                if (item.ManagerList != null && item.ManagerList.Count > 0)
                {
                    foreach (var subItem in item.ManagerList)
                    {
                        persionName += "、" + empList?.Where(qitem => qitem.Id == subItem)?.FirstOrDefault()?.EmployeeName ?? "";
                    }
                }
                if (!string.IsNullOrEmpty(persionName) && persionName != "")
                {
                    persionName = persionName[1..];
                }
                item.ManagerName = persionName;
                item.DeptPostList = deptPostList?.Where(qitem => qitem.Dept_Id == item.DeptId)?.ToList() ?? new List<RB_Department_Post_ViewModel>();
            }
            return list;
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Department_ViewModel> GetDepartmentListModule(RB_Department_ViewModel query)
        {
            return departmentRepository.GetDepartmentListRepository(query);
        }

        /// <summary>
        /// 获取当前部门的所有上级部门
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        public List<RB_Department_ViewModel> GetAllSuperiorDepartmentListModule(object DeptId)
        {
            return departmentRepository.GetAllSuperiorDepartmentListRepository(DeptId);
        }


        /// <summary>
        /// 获取当前部门的所有上级部门编号【例如:1,2,3...】
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        public string GetAllSuperiorDepartmentIdsModule(object DeptId)
        {
            return departmentRepository.GetAllSuperiorDepartmentIdsRepository(DeptId);
        }


        /// <summary>
        /// 获取当前部门和当前部门所有的下级部门列表
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        public List<RB_Department_ViewModel> GetCurrentAndChildDepartmentListModule(object DeptId)
        {
            return departmentRepository.GetCurrentAndChildDepartmentListRepository(DeptId);
        }

        /// <summary>
        /// 获取当前部门和当前部门所有的下级部门【例如:1,2,3...】
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        public string GetCurrentAndChildDepartmentIdsModule(object DeptId)
        {
            return departmentRepository.GetCurrentAndChildDepartmentIdsRepository(DeptId);
        }

        /// <summary>
        /// 获取部门结构树
        /// </summary>
        /// <param name="query"></param>
        /// <param name="isQueryEmployee">是否查询员工</param>
        /// <param name="isQueryPost">是否查询岗位</param>
        /// <returns></returns>
        public List<DepartmentTree_ViewModel> GetDepartmentTreeModule(RB_Department_ViewModel query, bool isQueryEmployee = false, bool isQueryPost = false)
        {
            //树形结构列表
            List<DepartmentTree_ViewModel> list = new List<DepartmentTree_ViewModel>();
            //所有的部门列表
            var deptList = GetDepartmentListModule(query);
            //员工列表
            var empList = new List<Employee_ViewModel>();
            //岗位列表
            var postList = new List<RB_Post_ViewModel>();
            if (deptList == null)
            {
                deptList = new List<RB_Department_ViewModel>();
            }
            //查询员工
            if (isQueryEmployee)
            {
                empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
                {
                    Group_Id = query.Group_Id,
                    School_Id = query.School_Id
                });
            }
            if (isQueryPost)
            {
                postList = postRepository.GetPostListExtRepository(new RB_Post_ViewModel()
                {
                    Group_Id = query.Group_Id,
                });
            }
            if (deptList != null && deptList.Count > 0)
            {
                var firstList = new List<RB_Department_ViewModel>();
                if (query.School_Id == 0)
                {
                    firstList = deptList.Where(qitem => qitem.ParentId == 0 && qitem.School_Id == 0).ToList();
                }
                else
                {
                    var minParentId = deptList.Where(qitem => qitem.School_Id == query.School_Id).Min(qitem => qitem.ParentId);
                    firstList = deptList.Where(qitem => qitem.ParentId == minParentId && qitem.School_Id == query.School_Id).ToList();
                }
                if (firstList != null && firstList.Count > 0)
                {
                    foreach (var fItem in firstList)
                    {
                        DepartmentTree_ViewModel tModel = new DepartmentTree_ViewModel()
                        {
                            DeptId = fItem.DeptId,
                            DeptName = fItem.DeptName,
                            ParentId = fItem.ParentId,
                            ChildList = new List<DepartmentTree_ViewModel>(),
                            School_Id = fItem.School_Id,
                            IsCompany = fItem.IsCompany,
                            DataType = 1,
                        };
                        #region 添加员工信息
                        if (isQueryEmployee)
                        {
                            var tempEmpList = empList?.Where(qitem => qitem.Dept_Id == fItem.DeptId)?.ToList();
                            if (tempEmpList != null && tempEmpList.Count > 0)
                            {
                                foreach (var eItem in tempEmpList)
                                {
                                    tModel.ChildList.Add(new DepartmentTree_ViewModel()
                                    {
                                        DeptId = eItem.Id,
                                        DeptName = eItem.EmployeeName,
                                        ParentId = 0,
                                        ChildList = new List<DepartmentTree_ViewModel>(),
                                        School_Id = eItem.School_Id,
                                        DataType = 2,
                                    });
                                }
                            }
                        }
                        #endregion

                        #region 添加岗位
                        if (isQueryPost)
                        {
                            var tempPostList = postList?.Where(qitem => qitem.Dept_Id == fItem.DeptId)?.ToList();
                            if (tempPostList != null && tempPostList.Count > 0)
                            {
                                foreach (var pItem in tempPostList)
                                {
                                    tModel.ChildList.Add(new DepartmentTree_ViewModel()
                                    {
                                        DeptId = pItem.PostId,
                                        DeptName = pItem.PostName,
                                        ParentId = 0,
                                        ChildList = new List<DepartmentTree_ViewModel>(),
                                        School_Id = fItem.School_Id,
                                        DataType = 3,
                                    });
                                }
                            }
                        }
                        #endregion

                        var childList = GetDeptTreeList(fItem.DeptId, deptList, empList: empList, postList: postList);
                        if (childList != null && childList.Count > 0)
                        {
                            tModel.ChildList.AddRange(childList);
                        }
                        list.Add(tModel);
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 递归生成树形结构
        /// </summary>
        /// <param name="parentId">父节点编号</param>
        /// <param name="sourceList">数据源列表</param>
        /// <param name="empList">员工列表</param>
        private List<DepartmentTree_ViewModel> GetDeptTreeList(int parentId, List<RB_Department_ViewModel> sourceList, List<Employee_ViewModel> empList = null, List<RB_Post_ViewModel> postList = null)
        {
            List<DepartmentTree_ViewModel> treeList = new List<DepartmentTree_ViewModel>();
            foreach (var item in sourceList.Where(qitem => qitem.ParentId == parentId))
            {
                DepartmentTree_ViewModel model = new DepartmentTree_ViewModel()
                {
                    DeptId = item.DeptId,
                    DeptName = item.DeptName,
                    ParentId = item.ParentId,
                    ChildList = new List<DepartmentTree_ViewModel>(),
                    School_Id = item.School_Id,
                    IsCompany = item.IsCompany,
                    DataType = 1,
                };

                #region 添加员工信息
                if (empList != null && empList.Count > 0)
                {
                    var tempEmpList = empList?.Where(qitem => qitem.Dept_Id == item.DeptId)?.ToList();
                    if (tempEmpList != null && tempEmpList.Count > 0)
                    {
                        foreach (var eItem in tempEmpList)
                        {
                            model.ChildList.Add(new DepartmentTree_ViewModel()
                            {
                                DeptId = eItem.Id,
                                DeptName = eItem.EmployeeName,
                                ParentId = 0,
                                School_Id = eItem.School_Id,
                                ChildList = new List<DepartmentTree_ViewModel>(),
                                DataType = 2,
                            });
                        }
                    }
                }
                #endregion

                #region 添加岗位
                if (postList != null && postList.Count > 0)
                {
                    var tempPostList = postList?.Where(qitem => qitem.Dept_Id == item.DeptId)?.ToList();
                    if (tempPostList != null && tempPostList.Count > 0)
                    {
                        foreach (var pItem in tempPostList)
                        {
                            model.ChildList.Add(new DepartmentTree_ViewModel()
                            {
                                DeptId = pItem.PostId,
                                DeptName = pItem.PostName,
                                ParentId = 0,
                                ChildList = new List<DepartmentTree_ViewModel>(),
                                School_Id = item.School_Id,
                                DataType = 3,
                            });
                        }
                    }
                }
                #endregion

                //添加下级部门
                var childList = GetDeptTreeList(item.DeptId, sourceList, empList: empList, postList: postList);
                if (childList != null && childList.Count > 0)
                {
                    model.ChildList.AddRange(childList);
                }
                treeList.Add(model);
            }
            return treeList;
        }

        /// <summary>
        /// 获取组织机构
        /// </summary>
        /// <param name="groupModel"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public object GetOrganizationChartModule(RB_Group_ViewModel groupModel, RB_Department_ViewModel query)
        {
            List<object> nodeList = new List<object>();
            List<object> linkList = new List<object>();
            var list = GetDepartmentTreeModule(query);
            //根节点
            nodeList.Add(new
            {
                id = groupModel.GId,
                text = groupModel.GroupName,
                color = "#2E4E8F",

            });
            foreach (var item in list)
            {
                nodeList.Add(new
                {
                    id = item.DeptId,
                    text = item.DeptName,
                });
                linkList.Add(new
                {
                    from = groupModel.GId.ToString(),
                    to = item.DeptId.ToString(),
                });
                GetChildDept(item, ref nodeList, ref linkList);
            }
            var obj = new
            {
                rootId = groupModel.GId,
                nodes = nodeList,
                links = linkList
            };
            return obj;
        }

        /// <summary>
        /// 获取下级部门
        /// </summary>
        /// <param name="item"></param>
        /// <param name="nodeList"></param>
        /// <param name="linkList"></param>
        public void GetChildDept(DepartmentTree_ViewModel item, ref List<object> nodeList, ref List<object> linkList)
        {
            if (item.ChildList != null && item.ChildList.Count > 0)
            {
                foreach (var subItem in item.ChildList)
                {
                    nodeList.Add(new
                    {
                        id = subItem.DeptId,
                        text = subItem.DeptName,
                    });
                    linkList.Add(new
                    {
                        from = item.DeptId.ToString(),
                        to = subItem.DeptId.ToString(),
                    });
                    GetChildDept(subItem, ref nodeList, ref linkList);
                }
            }
        }

        /// <summary>
        /// 新增修改部门
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public virtual bool SetDepartmentModule(RB_Department_ViewModel extModel)
        {
            bool flag;
            if (extModel.DeptId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Department_ViewModel.DeptName),extModel.DeptName },
                    {nameof(RB_Department_ViewModel.DeptTel),extModel.DeptTel },
                    {nameof(RB_Department_ViewModel.ManagerIds),extModel.ManagerIds },
                    {nameof(RB_Department_ViewModel.ParentId),extModel.ParentId },
                    {nameof(RB_Department_ViewModel.UpdateBy),extModel.UpdateBy },
                    {nameof(RB_Department_ViewModel.UpdateTime),extModel.UpdateTime },
                    {nameof(RB_Department_ViewModel.School_Id),extModel.School_Id },
                    {nameof(RB_Department_ViewModel.DeptTier),extModel.DeptTier },
                    {nameof(RB_Department_ViewModel.DeptSort),extModel.DeptSort },
                    {nameof(RB_Department_ViewModel.IsCompany),extModel.IsCompany }
                };
                flag = departmentRepository.Update(fileds, new WhereHelper(nameof(RB_Department_ViewModel.DeptId), extModel.DeptId));
            }
            else
            {
                var newId = departmentRepository.Insert(extModel);
                extModel.DeptId = newId;
                flag = newId > 0;
            }
            department_PostRepository.DeleteOne(new WhereHelper(nameof(RB_Department_Post_ViewModel.Dept_Id), extModel.DeptId));
            if (extModel.ChoosePostList != null && extModel.ChoosePostList.Count > 0)
            {
                foreach (var item in extModel.ChoosePostList)
                {
                    var deptPostModel = new RB_Department_Post_ViewModel()
                    {
                        Id = 0,
                        Dept_Id = extModel.DeptId,
                        PostId = item
                    };
                    department_PostRepository.Insert(deptPostModel);
                }
            }
            return flag;
        }

        /// <summary>
        /// 根据部门编号获取部门实体
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        public RB_Department_ViewModel GetDepartmentModule(object DeptId)
        {
            var extModel = departmentRepository.GetEntity<RB_Department_ViewModel>(DeptId);
            if (extModel != null && extModel.DeptId > 0)
            {
                var deptPostList = department_PostRepository.GetDepartmentPostListRepository(new RB_Department_Post_ViewModel()
                {
                    Dept_Id = extModel.DeptId
                });
                extModel.ChoosePostList = new List<int>();
                if (deptPostList != null && deptPostList.Count > 0)
                {
                    foreach (var item in deptPostList)
                    {
                        extModel.ChoosePostList.Add(item.PostId);
                    }
                }
                extModel.DeptPostList = deptPostList;
            }
            return extModel;
        }

        /// <summary>
        /// 修改部门状态
        /// </summary>
        /// <param name="DeptId">部门编号</param>
        /// <param name="Status">状态</param>
        /// <returns></returns>
        public bool RemoveDepartmentModule(int DeptId, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Department_ViewModel.Status),Status }
            };
            return departmentRepository.Update(fileds, new WhereHelper(nameof(RB_Department_ViewModel.DeptId), DeptId));
        }



        /// <summary>
        /// 获取组织机构
        /// </summary>
        /// <param name="groupModel"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<DepartmentTree_ViewModel> GetOrganizationOKRModule(RB_Department_ViewModel query, bool isQueryEmployee = false)
        {
            List<DepartmentTree_ViewModel> nodeList = new List<DepartmentTree_ViewModel>();
            //List<object> linkList = new List<object>();
            var list = GetDepartmentTreeModule(query, isQueryEmployee: true);
            //员工列表
            var empList = new List<Employee_ViewModel>();
            ////查询员工
            //if (isQueryEmployee)
            //{
            //    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
            //    {
            //        Group_Id = query.Group_Id,
            //        School_Id = query.School_Id
            //    });
            //}
            foreach (var item in list)
            {
                //DepartmentTree_ViewModel tModel = new DepartmentTree_ViewModel()
                //{
                //    DeptId = item.DeptId,
                //    DeptName = item.DeptName,
                //    ParentId = item.ParentId,
                //    ChildList = new List<DepartmentTree_ViewModel>(),
                //    School_Id = item.School_Id,
                //    IsCompany = item.IsCompany,
                //    DataType = 1,
                //};
                nodeList.Add(item);

                GetChildDeptOKR(item, ref nodeList);
            }
            return nodeList;
        }

        /// <summary>
        /// 获取下级部门
        /// </summary>
        /// <param name="item"></param>
        /// <param name="nodeList"></param>
        /// <param name="linkList"></param>
        public void GetChildDeptOKR(DepartmentTree_ViewModel item, ref List<DepartmentTree_ViewModel> nodeList)
        {
            if (item.ChildList != null && item.ChildList.Count > 0)
            {
                foreach (var subItem in item.ChildList)
                {
                    //DepartmentTree_ViewModel tModel = new DepartmentTree_ViewModel()
                    //{
                    //    DeptId = subItem.DeptId,
                    //    DeptName = subItem.DeptName,
                    //    ParentId = subItem.ParentId,
                    //    ChildList = new List<DepartmentTree_ViewModel>(),
                    //    School_Id = subItem.School_Id,
                    //    IsCompany = subItem.IsCompany,
                    //    DataType = 1,
                    //};
                    nodeList.Add(subItem);
                    GetChildDeptOKR(subItem, ref nodeList);
                }
            }
        }
    }
}