using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.HM.WebApi.Controllers.Api
{
    /// <summary>
    ///  文件发布表
    /// </summary>
    [Route("api/HM/HMFilePublish")]
    public partial class FilePublishController : AuthorizeApiController<T_HM_FILE_PUBLISH>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// 作业任务分析
        /// </summary>
        public FilePublishController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_HM_FILE_PUBLISH> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                T_HM_FILE_PUBLISH main = new T_HM_FILE_PUBLISH();
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (!string.IsNullOrEmpty(id))
                {
                    var entity = this.GetEntity<T_HM_FILE_PUBLISH>(id,new string[] { "Nav_User", "Nav_User.Nav_Department", "Nav_Area", "Nav_Area.Nav_Department", "Nav_LicenseAnalysis", "Nav_LicenseAnalysis.Nav_Details", "Nav_LicenseAnalysis.Nav_Details.Nav_Area", "Nav_LicenseAnalysis.Nav_Details.Nav_OperationStep", "Nav_LicenseAnalysis.Nav_Details.Nav_DetailRisk",
                        "Nav_LicenseAnalysis.Nav_Details.Nav_WorkPermitType", "Nav_LicenseAnalysis.Nav_Details.Nav_DetailRisk.Nav_EvaluateRisk",
                        "Nav_LicenseAnalysis.Nav_Details.Nav_Files","Nav_LicenseAnalysis.Nav_Details.Nav_Files.Nav_ImgFile", "Nav_LicenseAnalysis.Nav_Details.Nav_Files.Nav_ImgFile.Nav_File",
                        "Nav_CrucialTaskAnalysis", "Nav_CrucialTaskAnalysis.Nav_Details", "Nav_CrucialTaskAnalysis.Nav_Details.Nav_Area", "Nav_CrucialTaskAnalysis.Nav_Details.Nav_OperationStep", "Nav_CrucialTaskAnalysis.Nav_Details.Nav_DetailRisk",
                        "Nav_CrucialTaskAnalysis.Nav_Details.Nav_DetailRisk.Nav_EvaluateRisk",
                        "Nav_CrucialTaskAnalysis.Nav_Details.Nav_Files","Nav_CrucialTaskAnalysis.Nav_Details.Nav_Files.Nav_ImgFile","Nav_CrucialTaskAnalysis.Nav_Details.Nav_Files.Nav_ImgFile.Nav_File",
                        "Nav_OrdinaryTaskAnalysis", "Nav_OrdinaryTaskAnalysis.Nav_Details", "Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_Area", "Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_OperationStep", "Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_DetailRisk",
                        "Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_DetailRisk.Nav_EvaluateRisk",
                         "Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_Files","Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_Files.Nav_ImgFile", "Nav_OrdinaryTaskAnalysis.Nav_Details.Nav_Files.Nav_ImgFile.Nav_File"
                        });
                    if (entity != null)
                    {
                        main = entity;
                        entity.Nav_License_Details = new List<T_HM_LICENSE_ANALYSIS_DETAIL>();
                        entity.Nav_Crucial_Details = new List<T_HM_CRUCIAL_TASK_DETAIL>();
                        entity.Nav_Ordinary_Details = new List<T_HM_ORDINARY_TASK_DETAIL>();
                        if (entity.Nav_LicenseAnalysis != null && entity.Nav_LicenseAnalysis.Nav_Details.Any())
                            main.Nav_License_Details = entity.Nav_LicenseAnalysis.Nav_Details.ToList();
                        if (entity.Nav_CrucialTaskAnalysis != null && entity.Nav_CrucialTaskAnalysis.Nav_Details.Any())
                            main.Nav_Crucial_Details = entity.Nav_CrucialTaskAnalysis.Nav_Details.ToList();
                        if (entity.Nav_OrdinaryTaskAnalysis != null && entity.Nav_OrdinaryTaskAnalysis.Nav_Details.Any())
                            main.Nav_Ordinary_Details = entity.Nav_OrdinaryTaskAnalysis.Nav_Details.ToList();
                    }
                }
                return main;
            });
        }
        /// <summary>
        /// 分析表下拉带出分析明细数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzeDetail")]
        public JsonActionResult<T_HM_FILE_PUBLISH> GetAnalyzeDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_HM_FILE_PUBLISH main = new T_HM_FILE_PUBLISH();
                //传入CODE不为空
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    if (!string.IsNullOrEmpty(filter.Parameter1) && filter.Parameter1 == "1")
                    {
                        //许可作业明细
                        var license = GetEntity<T_HM_LICENSE_ANALYSIS>(t => t.CODE == filter.Keyword, false, "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_EvaluateRisk");
                        if (license != null)
                            main.Nav_LicenseAnalysis = license;
                    }
                    if (!string.IsNullOrEmpty(filter.Parameter1) && filter.Parameter1 == "2")
                    {
                        //许可作业明细
                        var crucial = GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(t => t.CODE == filter.Keyword, false, "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_EvaluateRisk");
                        if (crucial != null)
                            main.Nav_CrucialTaskAnalysis = crucial;
                    }
                    if (!string.IsNullOrEmpty(filter.Parameter1) && filter.Parameter1 == "3")
                    {
                        //许可作业明细
                        var ordinary = GetEntity<T_HM_ORDINARY_TASK_ANALYSIS>(t => t.CODE == filter.Keyword, false, "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_EvaluateRisk");
                        if (ordinary != null)
                            main.Nav_OrdinaryTaskAnalysis = ordinary;
                    }
                }
                return main;
            });
        }

        /// <summary>
        /// 单条删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("FullDelete")]
        public JsonActionResult<bool> FullDelete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                T_HM_FILE_PUBLISH entity = GetEntity<T_HM_FILE_PUBLISH>(t => t.ID.ToString() == id, false, "Nav_Area");
                List<Guid> areaIds = new List<Guid>();
                if (entity.Nav_Area != null && entity.Nav_Area.Any())
                {
                    var areaIdList = entity.Nav_Area.Select(t => t.ID).ToList();
                    areaIds.AddRange(areaIdList);
                }
                UnifiedCommit(() =>
                {
                    if (areaIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_FILE_PUBLISH_AREA>(areaIds);
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });
                return true;
            });
        }

        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_FILE_PUBLISH entity)
        {
            return SafeExecute(() =>
            {
                var areas = entity.Nav_Area.Where(t=>!t.IS_DELETED).ToList();
                if (areas == null || !areas.Any())
                    this.ThrowError("030015");
                entity.PUBLISH_DATE = DateTime.Now;
                entity.IS_PUBLISH = 0;
                if (entity.Nav_CreateUser != null && entity.Nav_CreateUser.Nav_Department != null)
                    entity.DEPARTMENT_ID = entity.Nav_CreateUser.Nav_Department.ID;
                else
                    entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                if (areas != null && areas.Any())
                {
                    areas.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.FILE_PUBLISH_ID = entity.ID;
                        t.Nav_Department = null;
                    });
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        entity.IS_PUBLISH = FOPreMeetingStatusEnum.签到中;
                        //获取选中部门的所有人
                        var allUsers = GetDepartmentUsers(entity);
                        var UserNames = new List<string>();
                        var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && allUsers.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                        foreach (var u in allUsers)
                        {
                            var current = user.FirstOrDefault(t => t.ID == u);
                            UserNames.Add(current?.NAME);
                        }
                        //发消息
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, entity.ORG_ID.Value, DateTime.Now, null, null);
                        notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务分析文件发布", entity.ID, entity.ORG_ID, allUsers, UserNames,DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "HM123_SHOWPRINT");
                        //查询消息表
                        if (entity.TaskID != Guid.Empty)
                        {
                            task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                            task.SOURCE_FORMCODE = "HM123_SHOWPRINT";
                        }
                    }
                }
               
                entity.Nav_Area = null;
                entity.Nav_License_Details = null;
                entity.Nav_Ordinary_Details = null;
                entity.Nav_Crucial_Details = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (areas != null && areas.Any())
                        this.BantchSaveEntityNoCommit(areas);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 发布给分析人确认
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PublishToIdentify")]
        public JsonActionResult<bool> PublishToIdentify(Guid id)
        {
            return SafeExecute<bool>(() =>
            {
                var entity = GetEntity<T_HM_FILE_PUBLISH>(t => t.ID == id, false, "Nav_Area", "Nav_Area.Nav_Department");
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                entity.IS_PUBLISH = FOPreMeetingStatusEnum.签到中;
                //发布给选中部门的所有人
                if (entity.Nav_Area != null && entity.Nav_Area.Any())
                {
                    var allUsers = GetDepartmentUsers(entity).Distinct().ToList();
                    var UserNames = new List<string>();
                    var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && allUsers.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                    foreach (var u in allUsers)
                    {
                        var current = user.FirstOrDefault(t => t.ID == u);
                        UserNames.Add(current?.NAME);
                    }
                    //发消息
                    notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务分析文件发布", entity.ID, entity.ORG_ID, allUsers, UserNames, DateTime.Now,
                    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM123_SHOWPRINT");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notices.Any())
                        this.BantchAddEntityNoCommit(notices);
                });
                return true;
            });
        }
        /// <summary>
        /// 更新状态为已阅
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("ChangeStatus")]
        public JsonActionResult<bool> ChangeStatus([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    //查询消息表更新状态为已阅
                    var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID.ToString() == filter.Keyword && i.USER_ID == loginUserId
                    && i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt(), false);
                    if (task != null)
                    {
                        task.SOURCE_FORMCODE = "HM123_SHOWPRINT";
                        if (DateTime.Now > task.TASK_ENDDT)
                            task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                        else
                            task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        //task.NOTICE_STATUS = FMNoticeStatusEnum.已阅.GetInt();
                        task.TASK_DT = DateTime.Now;
                    }
                    //是否有其他人未阅读
                    var taskAnathor = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID.ToString() == filter.Keyword && i.USER_ID != loginUserId
                    && i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt(), false);
                    //只要不存在，就更新
                    if (taskAnathor == null)
                    {
                        var entity = this.GetEntity<T_HM_FILE_PUBLISH>(t => t.ID == taskAnathor.SOURCE_DATA_ID);
                        entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
                    }
                    UnifiedCommit(() =>
                    {
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 查找部门下的所有人
        /// </summary>
        /// <param name="entity"></param>
        [HttpPost, Route("GetDepartmentUsers")]
        public List<Guid> GetDepartmentUsers(T_HM_FILE_PUBLISH entity)
        {
            var allUsers = new List<Guid>();
            if (entity != null && entity.Nav_Area != null && entity.Nav_Area.Any())
            {
                var departmentIds = entity.Nav_Area.Where(t=>t.DEPARTMENT_ID!=null).Select(x => (Guid)x.DEPARTMENT_ID).Distinct().ToList();
                var departments = this.GetEntities<T_FM_DEPARTMENT>(t => departmentIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                //先查询选中部门有没有公司级
                var departmentInfos = departments.Where(x => x.DEPARTMENT_TYPE == (int)FMDepartmentType.公司).ToList();
                //发给所有人
                if (departmentInfos != null && departmentInfos.Any())
                {
                    var allUsers1 = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID)).Select(t=>t.ID).Distinct().ToList();
                    allUsers.AddRange(allUsers1);
                }
                else
                {
                    List<Guid> outputDepartmentIds = new List<Guid>();
                    GetDepartmentIds(departmentIds, ref outputDepartmentIds);
                    //选中的部门人员
                    var allUsers1 = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0 && i.DEPARTMENT_ID!=null && outputDepartmentIds.Contains((Guid)i.DEPARTMENT_ID), new BaseFilter(entity.ORG_ID)).Select(t => t.ID).Distinct().ToList();
                    allUsers.AddRange(allUsers1);
                }
            }
            return allUsers;
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_HM_FILE_PUBLISH> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_HM_FILE_PUBLISH>();
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var loginUserCode = APT.Infrastructure.Api.AppContext.CurrentSession.UserCode;
            //安环部负责人departmentID
            var manageDepartId = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
            if (loginUserCode == "admin" || loginDepartmentId == manageDepartId)
            {
                result = this.GetOrderPageEntities<T_HM_FILE_PUBLISH>(null, pageFilter);
            }
            else
            {
                List<Guid> departmentId = new List<Guid>() { loginDepartmentId.Value };
                List<Guid> departmentIds = new List<Guid>() { loginDepartmentId.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_HM_FILE_PUBLISH>(t => (t.DEPARTMENT_ID != null && departmentIds.Contains(t.DEPARTMENT_ID.Value)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }
        /// <summary>
        /// 返回所有部门节点
        /// <returns></returns>
        private void GetDepartmentIds(List<Guid> departmentIdList, ref List<Guid> departmentIds)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            departmentIds.AddRange(departmentIdList);
            var departmentTemps = GetEntities<T_FM_DEPARTMENT>(t => t.PARENT_ID!= null && departmentIdList.Contains((Guid)t.PARENT_ID),new BaseFilter(orgId));
            if (departmentTemps != null && departmentTemps.Any())
            {
                var temp = departmentTemps.Select(t => t.ID).Distinct().ToList();
                GetDepartmentIds(temp, ref departmentIds);
            }
        }
        /// <summary>
        /// 自动生成CODE
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("GetFileCode")]
        public JsonActionResult<string> GetFileCode([FromBody] KeywordFilter filter)
        {
            return SafeExecute<string>(() =>
            {
                var fileCode = "";
                var nextCodeInfo = this.GetEntities<T_HM_FILE_PUBLISH>(t => !t.IS_DELETED && t.CREATE_TIME >= DateTime.Now, new BaseFilter(filter.OrgId)).OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                var year = DateTime.Now.Year;
                var month = DateTime.Now.Month.PadLeft(2, '0');
                var day = DateTime.Now.Day.PadLeft(2, '0');
                if (nextCodeInfo == null)
                {
                    fileCode = "RWFX" + year + month + day + "00001";
                }
                else
                {
                    //取最后五位序列号
                    var serial = nextCodeInfo.CODE.Substring(nextCodeInfo.CODE.Length - 5);
                    //序列号+1，不足五位补0
                    var num = (int.Parse(serial) + 1).ToString().PadLeft(5, '0');
                    fileCode = "RWFX" + year+ month + day + num;
                }
                return fileCode;
            });
        }
    }
}
