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_SchoolRepository schoolRepository = new RB_SchoolRepository();

        /// <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>();
            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 });
                }
            }
            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.Substring(1);
                }
                item.ManagerName = persionName;
            }
            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="query">是否查询员工</param>
        /// <returns></returns>
        public List<DepartmentTree_ViewModel> GetDepartmentTreeModule(RB_Department_ViewModel query,bool isQueryEmployee=false)
        {
            //树形结构列表
            List<DepartmentTree_ViewModel> list = new List<DepartmentTree_ViewModel>();
            //所有的部门列表
            var deptList = GetDepartmentListModule(query);
            var schoolList = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = query.Group_Id });
            var empList = new List<Employee_ViewModel>();
            if (deptList == null)
            {
                deptList = new List<RB_Department_ViewModel>();
            }
            if(isQueryEmployee)
            {
                empList= accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = query.Group_Id });
            }
            //校区部门
            List<DepartmentTree_ViewModel> schoolDeptList = new List<DepartmentTree_ViewModel>();
            if (schoolList != null)
            {
                foreach (var item in schoolList)
                {
                    DepartmentTree_ViewModel tModel = new DepartmentTree_ViewModel()
                    {
                        DeptId = item.SId,
                        DeptName = item.SName,
                        ParentId = item.Dept_Id,
                        ChildList = new List<DepartmentTree_ViewModel>()
                    };
                    #region 添加员工信息
                    if (isQueryEmployee && item.ManagerId > 0)
                    {
                        var empModel = empList?.Where(qitem => qitem.Id == item.ManagerId)?.FirstOrDefault();
                        if (empModel!=null && !string.IsNullOrEmpty(empModel.EmployeeName))
                        {
                            tModel.ChildList.Add(new DepartmentTree_ViewModel()
                            {
                                DeptId = 0,
                                DeptName = empModel.EmployeeName,
                                ParentId = 0
                            }); 
                        }
                    }
                    #endregion

                    var currentSchoolDeptList = deptList.Where(qitem => qitem.School_Id ==item.SId).ToList();
                    if (currentSchoolDeptList != null && currentSchoolDeptList.Count > 0)
                    {
                        var currentSchoolDeptId = currentSchoolDeptList?.Min(qitem => qitem.ParentId) ?? 0;
                        tModel.ChildList = GetDeptTreeList(currentSchoolDeptId, currentSchoolDeptList, SchoolId: item.SId, schoolDeptList: null, empList: empList);
                    }
                    schoolDeptList.Add(tModel);
                }
            }

            if (deptList != null && deptList.Count > 0)
            {
                var firstList = deptList.Where(qitem => qitem.ParentId == 0 && qitem.School_Id==0).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>()
                        };

                        #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 = 0,
                                        DeptName = eItem.EmployeeName,
                                        ParentId = 0,
                                        ChildList = new List<DepartmentTree_ViewModel>()
                                    });
                                }
                            }
                        }
                        #endregion

                        tModel.ChildList = GetDeptTreeList(fItem.DeptId, deptList.Where(qitem => qitem.School_Id == 0).ToList(), SchoolId: 0, schoolDeptList: schoolDeptList, empList: empList);
                        if (schoolDeptList != null)
                        {
                            var newSchoolDeptList = schoolDeptList.Where(qitem => qitem.DeptId == fItem.DeptId)?.ToList();
                            if (newSchoolDeptList != null && newSchoolDeptList.Count>0)
                            {
                                tModel.ChildList.AddRange(newSchoolDeptList);
                            }
                        }
                        list.Add(tModel);
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 递归生成树形结构
        /// </summary>
        /// <param name="parentId">父节点编号</param>
        /// <param name="sourceList">数据源列表</param>
        /// <param name="SchoolId">学校编号</param>
        /// <param name="schoolDeptList">学校部门列表</param>
        /// <param name="empList">员工列表</param>
        private List<DepartmentTree_ViewModel> GetDeptTreeList(int parentId, List<RB_Department_ViewModel> sourceList,int SchoolId=0, List<DepartmentTree_ViewModel> schoolDeptList=null, List<Employee_ViewModel> empList=null)
        {
            List<DepartmentTree_ViewModel> treeList = new List<DepartmentTree_ViewModel>();
            foreach (var item in sourceList.Where(qitem => qitem.ParentId == parentId && qitem.School_Id== SchoolId))
            {
                DepartmentTree_ViewModel model = new DepartmentTree_ViewModel()
                {
                    DeptId = item.DeptId,
                    DeptName = item.DeptName,
                    ParentId = item.ParentId,
                    ChildList = new List<DepartmentTree_ViewModel>(),
                };
                #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 = 0,
                                DeptName = eItem.EmployeeName,
                                ParentId = 0,
                                ChildList = new List<DepartmentTree_ViewModel>()
                            });
                        }
                    }
                }
                #endregion

                model.ChildList = GetDeptTreeList(item.DeptId, sourceList, SchoolId, schoolDeptList);
                if (schoolDeptList != null)
                {
                    var newSchoolDeptList = schoolDeptList.Where(qitem => qitem.ParentId == item.DeptId)?.ToList();
                    if (newSchoolDeptList != null)
                    {
                        model.ChildList.AddRange(newSchoolDeptList);
                    }
                }
                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 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 },
                };
                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;
            }
            return flag;
        }

        /// <summary>
        /// 根据部门编号获取部门实体
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        public RB_Department_ViewModel GetDepartmentModule(object DeptId)
        {
            return departmentRepository.GetEntity<RB_Department_ViewModel>(DeptId);
        }

        /// <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));
        }
    }
}