using APT.Infrastructure.Core;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using System.Collections.Generic;
using APT.Infrastructure.Api;
using System;
using System.Linq;
using APT.BaseData.Domain.Enums;
using APT.MS.Domain.Entities.SC.SC;
using NPOI.SS.Formula.Functions;
using APT.MS.Domain.Enums;

namespace APT.BaseData.Services.Services.FM
{
    public partial class FMDepartmentService : CommonService, IFMDepartmentService
    {
        public FMDepartmentService(IRepository repository)
            : base(repository)
        {
        }

        //public IEnumerable<TreeNode<T_FM_DEPARTMENT>> TreeData(KeywordFilter filter)
        // {
        //     return this.GetTreeOrderEntities<T_FM_DEPARTMENT>(null, filter);
        // }

        /// <summary>
        /// 返回所有下级部门节点
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="listDepIDInt"></param>
        /// <param name="departmentIdPs"></param>
        public void GetDepartmentIds(Guid orgId, List<Guid> listDepIDInt, ref List<Guid> departmentIdPs)
        {
            var listDep = GetEntities<T_FM_DEPARTMENT>(e => e.ORG_ID == orgId && !e.IS_DELETED && e.PARENT_ID.HasValue && listDepIDInt.Contains(e.PARENT_ID.Value));

            if (listDep != null && listDep.Any())
            {
                listDepIDInt = listDep.Select(e => e.ID).ToList();
                departmentIdPs.AddRange(listDepIDInt);
                GetDepartmentIds(orgId, listDepIDInt, ref departmentIdPs);
            }
        }
        /// <summary>
        /// 判断是否要权限限制
        /// 要返回所有下级部门节点
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="listDepIDInt"></param>
        /// <param name="departmentIdPs"></param>
        /// <param name="isAll">是否不限权限</param>
        public void GetDepartmentIds(Guid orgId, List<Guid> listDepIDInt, ref List<Guid> departmentIdPs, ref bool isAll)
        {
            isAll = false;
            if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName.StartsWith("admin"))//UserName == "admin"
            {
                isAll = true;
            }
            if (!isAll && APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.HasValue)
            {
                var dep = GetEntity<T_FM_DEPARTMENT>(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value);
                if (dep != null && dep.DEPARTMENT_STATUS == 2)
                {
                    isAll = true;
                }
            }
            if (!isAll)
            {
                List<Guid> departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                GetDepartmentIds(orgId, new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value }, ref departmentIds);
                //departmentIdPs.AddRange(departmentIds);
                //departmentIdPs = departmentIdPs.Distinct().ToList();
                foreach (var item in departmentIds)
                {
                    if (!departmentIdPs.Contains(item))
                    {
                        departmentIdPs.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// 返回所有上级部门节点
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="listDepIDInt"></param>
        /// <param name="departmentIdPs"></param>
        public void GetParentDepartmentIds(Guid orgId, List<Guid> listDepIDInt, ref List<Guid> departmentIdPs)
        {
            var listDep = GetEntities<T_FM_DEPARTMENT>(e => e.ORG_ID == orgId && !e.IS_DELETED && listDepIDInt.Contains(e.ID));
            if (listDep != null && listDep.Any())
            {
                listDepIDInt = listDep.Where(t => t.PARENT_ID.HasValue).Select(e => e.PARENT_ID.Value).ToList();
                departmentIdPs.AddRange(listDepIDInt);
                GetParentDepartmentIds(orgId, listDepIDInt, ref departmentIdPs);
            }
        }

        /// <summary>
        /// 获取组织ID的部门级组织
        /// </summary>
        /// <param name="DepartmentID"></param>
        /// <returns></returns>
        public T_FM_DEPARTMENT GetDEPARTMENTLevel(Guid DepartmentID)
        {
            if (DepartmentID != Guid.Empty)
            {
                var dep = GetEntity<T_FM_DEPARTMENT>(DepartmentID, new string[] { "Nav_Parent" });
                if (dep.DEPARTMENT_TYPE == 0)//FMDepartmentType.部门   3 公司//FMDepartmentType.公司
                {
                    return dep;
                }
                else if (dep.DEPARTMENT_TYPE == 3)
                {
                    return dep;
                }
                else if (dep.Nav_Parent.DEPARTMENT_TYPE == 0)
                {
                    return dep.Nav_Parent;
                }
                else
                {
                    if (!dep.Nav_Parent.PARENT_ID.HasValue)
                    {
                        return null;
                    }
                    else
                    {
                        return GetDEPARTMENTLevel(dep.Nav_Parent.PARENT_ID.Value);
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 获取人事部
        /// </summary>
        /// <param name="DepName"></param>
        /// <param name="paths"></param>
        /// <returns></returns>
        public T_FM_DEPARTMENT GetRSDep(string DepName = "企业管理部", params string[] paths)
        {
            T_FM_DEPARTMENT result = new T_FM_DEPARTMENT();
            result = GetEntity<T_FM_DEPARTMENT>(e => e.DEPARTMENT_TYPE == 0 && e.NAME.Contains(DepName), paths == null ? paths : null);//部门级
            return result;
        }
        /// <summary>
        /// 获取人事部
        /// </summary>
        /// <param name="DepName"></param>
        /// <param name="paths"></param>
        /// <returns></returns>
        public void AddDocument(string MODULE, string FORM, string FILE_NAME, string VALUE_FIELD, string FILE_TYPE, DateTime VALID_TIME, Guid DATA_ID, List<Guid?> IMG_FILE_IDs, Guid? USER_ID)
        {
            T_SC_DOCUMENT_LIBRARY document = null;
            T_SC_DOCUMENT_LIBRARY_DETAIL documentDetail = new T_SC_DOCUMENT_LIBRARY_DETAIL();
            T_SC_DOCUMENT_LIBRARY_DETAIL_FILE documentDetailFile = new T_SC_DOCUMENT_LIBRARY_DETAIL_FILE();
            List<T_SC_DOCUMENT_LIBRARY_DETAIL_FILE> documentDetailFiles = new List<T_SC_DOCUMENT_LIBRARY_DETAIL_FILE>();

            ICollection<T_SC_DOCUMENT_LIBRARY_DETAIL> Nav_Details = null;
            document = GetEntity<T_SC_DOCUMENT_LIBRARY>(t => t.MODULE == MODULE && t.FORM == FORM && t.FILE_NAME == FILE_NAME, "Nav_Details");
            decimal? versionNum = 1;
            Guid? orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            if (document == null)
            {
                document = new T_SC_DOCUMENT_LIBRARY();
                document.ID = Guid.NewGuid();
                document.MODULE = MODULE;
                document.FORM = FORM;
                document.FILE_NAME = FILE_NAME;
                document.VALUE_FIELD = VALUE_FIELD;
                document.FILE_TYPE = FILE_TYPE;
                document.VALID_TIME = VALID_TIME;
                document.ORG_ID = orgId;
            }
            else
            {
                document.VALID_TIME = VALID_TIME;
                if (document.Nav_Details != null)
                {
                    versionNum = document.Nav_Details.OrderByDescending(t => t.VERSION).FirstOrDefault().VERSION;
                }
                foreach (var item in document.Nav_Details)
                {
                    item.STATUS = SCStandardSystemEnums.失效;
                }
                Nav_Details = document.Nav_Details;
            }
            documentDetail.ID = Guid.NewGuid();
            documentDetail.DOCUMENT_LIBRARY_ID = document.ID;
            versionNum++;
            documentDetail.VERSION = versionNum;
            documentDetail.DATA_ID = DATA_ID;
            documentDetail.NAME = FILE_NAME;
            documentDetail.YEAR = DateTime.Now.Year.ToString();
            documentDetail.COMPILE_TIME = DateTime.Now;
            documentDetail.PUBLISH_TIME = DateTime.Now;
            documentDetail.ORG_ID = orgId;
            documentDetail.USER_ID = USER_ID;
            foreach (var IMG_FILE_ID in IMG_FILE_IDs)
            {
                documentDetailFile.DOCUMENT_LIBRARY_ID = documentDetail.ID;
                documentDetailFile.IMG_FILE_ID = IMG_FILE_ID;
                documentDetailFile.ORG_ID = orgId;
                documentDetailFiles.Add(documentDetailFile);
            }

            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(document);
                if (documentDetail != null)
                    AddEntityNoCommit(documentDetail);
                if (documentDetailFiles != null && documentDetailFiles.Any())
                    BantchAddEntityNoCommit(documentDetailFiles);
                if (Nav_Details != null && Nav_Details.Any())
                    BantchSaveEntityNoCommit(Nav_Details);
            });
        }
    }
}
