using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
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
{
    [Route("api/HM/HMNoticeRelease")]
    public partial class NoticeReleaseController : AuthorizeApiController<T_HM_NOTICE_RELEASE>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }

        public NoticeReleaseController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;

        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_NOTICE_RELEASE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var files = entity.Nav_Files;
                var departments = entity.Nav_ReleaseRange;
                entity.Nav_Files = null;
                if (entity.RELEASE_USER_ID == null)
                {
                    entity.RELEASE_USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                }
                if (entity.RELEAS_DEPARTMENT_ID == null)
                {
                    var user = GetEntity<T_FM_USER>(t => t.ID == entity.RELEASE_USER_ID);
                    if (user != null)
                        entity.RELEAS_DEPARTMENT_ID = user.DEPARTMENT_ID;
                }
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                Guid depId = Guid.Empty;
                Guid approveRoldId = Guid.Empty;
                List<T_HM_RISK_TASK> risks = new List<T_HM_RISK_TASK>();
                List<T_HM_RISK_TASK_AREA> listRiskArea = new List<T_HM_RISK_TASK_AREA>();
                List<T_HM_RISK_TASK_IDENTIFYING> listRiskIdentifyings = new List<T_HM_RISK_TASK_IDENTIFYING>();
                List<T_HM_RISK_TASK_DETAIL> listRiskDetails = new List<T_HM_RISK_TASK_DETAIL>();
                List<T_HM_HAZARD_TASK> hazards = new List<T_HM_HAZARD_TASK>();
                List<T_HM_HAZARD_TASK_DETAIL> listHazardDetails = new List<T_HM_HAZARD_TASK_DETAIL>();
                List<T_HM_HAZARD_TASK_IDENTIFYING> listHazardIdentifyings = new List<T_HM_HAZARD_TASK_IDENTIFYING>();
                List<T_HM_HAZARD_TASK_AREA> listHazardArea = new List<T_HM_HAZARD_TASK_AREA>();
                List<T_HM_RISK_TASK_USER> taskUsers = new List<T_HM_RISK_TASK_USER>();
                List<T_FM_NOTIFICATION_TASK> sendNoticeList = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.RELEASE_STATUS = FOPreMeetingStatusEnum.归档;
                    var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                    var departmentFilter = new BaseFilter(orgId);
                    var allUsers = GetDepartmentUsers(entity.Nav_ReleaseRange.Select(t => t.DEPARTMENT_ID).Distinct().ToList(), orgId);
                    var allUserNames = new List<string>();
                    var allFMUser = 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 = allFMUser.FirstOrDefault(t => t.ID == u);
                        allUserNames.Add(current?.NAME);
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels("风险评价计划发布通知", entity.ID, orgId, allUsers, allUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM001_SHOWPRINT");
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID,entity.ID);
                    }
                    else
                    {
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels("风险评价计划发布通知", entity.ID, orgId, allUsers, allUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM001_SHOWPRINT");
                    }
                    var evaluationPlan = GetEntity<T_HM_EVALUATION_PLAN>((Guid)entity.PLAN_ID, new string[] { "Nav_Details.Nav_Areas", "Nav_Details.Nav_Identifyings" });
                    var userIds = evaluationPlan.Nav_Details.Where(t => t.IS_DELETED == false).Select(t => t.CHARGE_USER_ID);
                    var users = GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) || t.APPROVE_ROLE_ID != null, new BaseFilter(entity.ORG_ID));
                    var depts = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, new BaseFilter(entity.ORG_ID));
                    var riskDetails = evaluationPlan.Nav_Details.Where(t => t.IS_DELETED == false && t.RISK_TYPE == HMRiskTypeEnmu.危险源辨识);
                    var hazardDetails = evaluationPlan.Nav_Details.Where(t => t.IS_DELETED == false && t.RISK_TYPE == HMRiskTypeEnmu.职业危害辨识);
                    var noticeTitles = new List<string>();
                    var noticeUserIds = new List<Guid>();
                    var noticeUserNames = new List<string>();
                    var noticeDataIds = new List<Guid>();
                    var noticeFormCodes = new List<string>();
                    SystemCodeFilter riskCode = new SystemCodeFilter
                    {
                        CodeType = (int)PFCodeRuleType.风险辨识任务编号,
                        Count = riskDetails.Count(),
                        OrgId = entity.ORG_ID
                    };
                    var riskCodes = CodeRuleService.NewGenSerial(riskCode);
                    var riskCodeList = riskCodes.Split(new char[] { ',' });
                    SystemCodeFilter hazardCode = new SystemCodeFilter
                    {
                        CodeType = (int)PFCodeRuleType.风险辨识任务编号,
                        Count = hazardDetails.Count(),
                        OrgId = entity.ORG_ID
                    };
                    var hazardCodes = CodeRuleService.NewGenSerial(hazardCode);
                    var hazardCodeList = hazardCodes.Split(new char[] { ',' });
                    int riskIndex = 0;
                    foreach (var riskDetail in riskDetails)
                    {
                        T_HM_RISK_TASK riskTask = new T_HM_RISK_TASK();
                        riskTask.ID = Guid.NewGuid();
                        var user = users.FirstOrDefault(t => t.ID == riskDetail.CHARGE_USER_ID);
                        if (user != null)
                            riskTask.INITIATING_DEPARTMENT = user.DEPARTMENT_ID;
                        riskTask.CODE = riskCodeList[riskIndex];
                        riskIndex++;
                        riskTask.START_TIME = (DateTime)riskDetail.START_TIME;
                        riskTask.END_TIME = (DateTime)riskDetail.END_TIME;
                        riskTask.LEVEL = riskDetail.LEVEL;
                        riskTask.ORG_ID = riskDetail.ORG_ID;
                        riskTask.LIABLE_USER_ID = riskDetail.CHARGE_USER_ID;
                        riskTask.REQUEST_ID = GetEntity<T_HM_REQUEST>(t => true).ID;
                        riskTask.PLAN_ID = entity.PLAN_ID;
                        if (riskDetail.Nav_Areas.Where(t => t.IS_DELETED == false).Any())
                        {
                            var levels = riskDetail.LEVEL.Split("_").Where(t => t != "");
                            var Nav_Areas = riskDetail.Nav_Areas.Where(t => t.IS_DELETED == false);
                            foreach (var Area in Nav_Areas)
                            {
                                T_HM_RISK_TASK_AREA area = new T_HM_RISK_TASK_AREA();
                                area.ORG_ID = entity.ORG_ID;
                                area.AREA_ID = Area.AREA_ID;
                                area.TASK_ID = riskTask.ID;
                                listRiskArea.Add(area);
                                foreach (var level in levels)
                                {
                                    var sendUsers = GetEntities<T_HM_EVALUATE_RISK>(t => t.AREA_ID == Area.AREA_ID &&t.Nav_DepartmentLiable.IS_DELETED==false && t.DEPARTMENT_LIABLE_ID != null && t.LEVEL == (FMDepartmentType)int.Parse(level), new BaseFilter(entity.ORG_ID)).Select(t => new { t.DEPARTMENT_LIABLE_ID }).Distinct();
                                    if (sendUsers.Any())
                                    {
                                        T_HM_RISK_TASK_DETAIL taskDetail = new T_HM_RISK_TASK_DETAIL();
                                        taskDetail.ORG_ID = riskDetail.ORG_ID;
                                        taskDetail.AREA_ID = Area.AREA_ID;
                                        taskDetail.LEVEL = (FMDepartmentType)int.Parse(level);
                                        taskDetail.TASK_ID = riskTask.ID;
                                        taskDetail.ID = Guid.NewGuid();
                                        var record_user = Guid.Empty;
                                        var index = 0;
                                        foreach (var sendUser in sendUsers)
                                        {
                                            T_HM_RISK_TASK_USER taskUser = new T_HM_RISK_TASK_USER();
                                            taskUser.TASK_DETAIL_ID = taskDetail.ID;
                                            depId = (Guid)sendUser.DEPARTMENT_LIABLE_ID;
                                            var depChargeUser = depts.FirstOrDefault(t => t.ID == depId);
                                            if (depChargeUser.USER_ID == null)
                                            {
                                                throw new Exception(depChargeUser.NAME + "在组织架构中未找到负责人!");
                                            }
                                            taskUser.USER_ID = (Guid)depChargeUser.USER_ID;
                                            var taskUsersCount = taskUsers.Count(t => t.TASK_DETAIL_ID == taskDetail.ID && t.USER_ID == taskUser.USER_ID);//查询是否有插入避免豫鹭有重复人员添加
                                            if (taskUsersCount == 0)
                                            {
                                                taskUser.ORG_ID = entity.ORG_ID;
                                                taskUser.ROW_NO = index;
                                                if (index == 0)
                                                {
                                                    record_user = taskUser.USER_ID;
                                                }
                                                index++;
                                                taskUsers.Add(taskUser);
                                            }
                                        }
                                        taskDetail.RECORD_USER_ID = record_user;
                                        taskDetail.DEAL_STATUS = (int)FOUserShiftStatusEnum.待处理;
                                        listRiskDetails.Add(taskDetail);
                                    }
                                }

                            }

                            riskDetail.Nav_Identifyings.ForEach(t =>
                            {
                                T_HM_RISK_TASK_IDENTIFYING identifying = new T_HM_RISK_TASK_IDENTIFYING();
                                identifying.ORG_ID = entity.ORG_ID;
                                identifying.IDENTIFYING_ID = t.IDENTIFYING_ID;
                                identifying.TASK_ID = riskTask.ID;
                                listRiskIdentifyings.Add(identifying);

                            });
                        }
                        noticeTitles.Add("危险源辨识任务");
                        noticeDataIds.Add(riskTask.ID);
                        noticeUserIds.Add((Guid)riskDetail.CHARGE_USER_ID);
                        noticeUserNames.Add(user.NAME);
                        noticeFormCodes.Add("HM062");
                        risks.Add(riskTask);
                    }
                    int hazardIndex = 0;
                    foreach (var hazardDetail in hazardDetails)
                    {
                        T_HM_HAZARD_TASK hazardTask = new T_HM_HAZARD_TASK();
                        hazardTask.ID = Guid.NewGuid();
                        var user = users.FirstOrDefault(t => t.ID == hazardDetail.CHARGE_USER_ID);
                        if (user != null)
                            hazardTask.INITIATING_DEPARTMENT = user.DEPARTMENT_ID;
                        hazardTask.CODE = hazardCodeList[hazardIndex];
                        hazardTask.START_TIME = (DateTime)hazardDetail.START_TIME;
                        hazardTask.END_TIME = (DateTime)hazardDetail.END_TIME;
                        hazardTask.LEVEL = "0";
                        hazardTask.ORG_ID = entity.ORG_ID;
                        hazardTask.LIABLE_USER_ID = hazardDetail.CHARGE_USER_ID;
                        hazardTask.PLAN_ID = entity.PLAN_ID;
                        hazardDetail.Nav_Areas.ForEach(t =>
                        {
                            T_HM_HAZARD_TASK_AREA area = new T_HM_HAZARD_TASK_AREA();
                            area.ORG_ID = entity.ORG_ID;
                            area.AREA_ID = t.AREA_ID;
                            area.TASK_ID = hazardTask.ID;
                            listHazardArea.Add(area);
                            T_HM_HAZARD_TASK_DETAIL taskDetail = new T_HM_HAZARD_TASK_DETAIL();
                            taskDetail.ORG_ID = entity.ORG_ID;
                            taskDetail.AREA_ID = t.AREA_ID;
                            taskDetail.TASK_ID = hazardTask.ID;
                            taskDetail.RECORD_USER_ID = null;
                            taskDetail.DEAL_STATUS = (int)FOUserShiftStatusEnum.待处理;
                            listHazardDetails.Add(taskDetail);
                        });

                        if (hazardDetail.Nav_Identifyings != null && hazardDetail.Nav_Identifyings.Any())
                        {
                            hazardDetail.Nav_Identifyings.ForEach(t =>
                            {
                                T_HM_HAZARD_TASK_IDENTIFYING identifying = new T_HM_HAZARD_TASK_IDENTIFYING();
                                identifying.ORG_ID = entity.ORG_ID;
                                identifying.IDENTIFYING_ID = t.IDENTIFYING_ID;
                                identifying.TASK_ID = hazardTask.ID;
                                listHazardIdentifyings.Add(identifying);
                            });
                        }
                        noticeTitles.Add("职业危害辨识任务");
                        noticeDataIds.Add(hazardTask.ID);
                        noticeUserIds.Add((Guid)hazardDetail.CHARGE_USER_ID);
                        noticeUserNames.Add(user.NAME);
                        noticeFormCodes.Add("HM102");
                        hazards.Add(hazardTask);
                    }
                    sendNoticeList = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, noticeFormCodes);
                }
                entity.Nav_ReleaseRange = null;
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (departments.Any())
                        BantchSaveEntityNoCommit(departments);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (risks.Any())
                        BantchAddEntityNoCommit(risks);
                    if (listRiskArea.Any())
                        BantchAddEntityNoCommit(listRiskArea);
                    if (listRiskIdentifyings.Any())
                        BantchAddEntityNoCommit(listRiskIdentifyings);
                    if (listRiskDetails.Any())
                        BantchAddEntityNoCommit(listRiskDetails);
                    if (hazards.Any())
                        BantchAddEntityNoCommit(hazards);
                    if (listHazardArea.Any())
                        BantchAddEntityNoCommit(listHazardArea);
                    if (listHazardIdentifyings.Any())
                        BantchAddEntityNoCommit(listHazardIdentifyings);
                    if (listHazardDetails.Any())
                        BantchAddEntityNoCommit(listHazardDetails);
                    if (taskUsers.Any())
                        BantchAddEntityNoCommit(taskUsers);
                    if (sendNoticeList != null && sendNoticeList.Any())
                        BantchAddEntityNoCommit(sendNoticeList);
                });
                return true;
            });
        }
        /// <summary>
        /// 收到
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_HM_NOTICE_RELEASE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        ///// <summary>
        ///// 查询责任人
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpPost, Route("searchChargeUser")]
        //public JsonActionResult<string> searchChargeUser([FromBody] KeywordFilter pageFilter)
        //{
        //    return SafeExecute<string>(() =>
        //    {
        //        var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
        //        string user = "";
        //        if (pageFilter.Keyword != null && pageFilter.Parameter1 != null)
        //        {
        //            var arealistGuids = new List<Guid>();
        //            var arealistStrs = pageFilter.Keyword.Split(',');
        //            foreach (var item in arealistStrs)
        //            {
        //                arealistGuids.Add(Guid.Parse(item));
        //            }
        //            BaseFilter baseFilter = new BaseFilter(orgId);
        //            baseFilter.Include = new string[] { "Nav_PersonLiable" };
        //            if (pageFilter.Parameter1.Equals("0"))
        //            {
        //                var chargeUsers = GetEntities<T_HM_EVALUATE_RISK>(t => arealistGuids.Contains((Guid)t.AREA_ID), baseFilter);
        //                foreach (var item in arealistGuids)
        //                {
        //                    if (chargeUsers.Where(t => t.AREA_ID == item).Count() == 0)
        //                    { 
        //                        throw new Exception("所选区域可能不存在责任人!");
        //                    }
        //                }
        //                chargeUsers = chargeUsers.DistinctBy(t => t.PERSON_LIABLE_ID);
        //                if (chargeUsers.Count() > 1)
        //                {
        //                    throw new Exception("所选区域负责人不是同一个人!");
        //                }
        //                else if (chargeUsers.Count() == 0)
        //                {
        //                    throw new Exception("未能找到所选区域负责人!");
        //                }
        //                else
        //                {
        //                    user = chargeUsers.FirstOrDefault().Nav_PersonLiable.NAME;
        //                }
        //            }
        //            else
        //            {
        //                var chargeUsers = GetEntities<T_HM_EVALUATE_HAZARD>(t => arealistGuids.Contains((Guid)t.AREA_ID), baseFilter);
        //                foreach (var item in arealistGuids)
        //                {
        //                    if (chargeUsers.Where(t => t.AREA_ID == item).Count() == 0)
        //                    {
        //                        throw new Exception("所选区域可能不存在责任人!");
        //                    }
        //                }
        //                chargeUsers = chargeUsers.DistinctBy(t => t.PERSON_LIABLE_ID);
        //                if (chargeUsers.Count() > 1)
        //                {
        //                    throw new Exception("所选区域负责人不是同一个人!");
        //                }
        //                else if (chargeUsers.Count() == 0)
        //                {
        //                    throw new Exception("未能找到所选区域负责人!");
        //                }
        //                else
        //                {
        //                    user = chargeUsers.
        //                    FirstOrDefault().Nav_PersonLiable.NAME;
        //                }
        //            }
        //        }
        //        return user;
        //    });
        //}
        /// <summary>
        /// 查找部门下的所有人
        /// </summary>
        /// <param name="entity"></param>
        [HttpPost, Route("GetDepartmentUsers")]
        public List<Guid> GetDepartmentUsers(List<Guid> departmentIDs, Guid? orgId)
        {
            var allUsers = new List<Guid>();
            var departments = GetEntities<T_FM_DEPARTMENT>(t => departmentIDs.Contains(t.ID), new BaseFilter(orgId));
            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(orgId)).Select(t => t.ID).Distinct().ToList();
                allUsers.AddRange(allUsers1);
            }
            else
            {
                List<Guid> outputDepartmentIds = new List<Guid>();
                GetDepartmentIds(departmentIDs, orgId, ref outputDepartmentIds);
                var allUsers1 = GetEntities<T_FM_USER>(i => i.CODE != "admin" && i.ENABLE_STATUS == 0 && i.DEPARTMENT_ID != null && outputDepartmentIds.Contains((Guid)i.DEPARTMENT_ID), new BaseFilter(orgId)).Select(t => t.ID).ToList();
                allUsers.AddRange(allUsers1);
            }
            return allUsers;
        }
        /// <summary>
        /// 返回所有部门节点
        /// <returns></returns>
        private void GetDepartmentIds(List<Guid> departmentIdList, Guid? orgId, ref List<Guid> departmentIds)
        {
            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, orgId, ref departmentIds);
            }
        }
    }
}
