using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SETrainSurvey")]
    public class SETrainSurveyController : AuthorizeApiController<T_SE_TRAIN_SURVEY>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SETrainSurveyController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TRAIN_SURVEY entity)
        {
            return SafeExecute(() =>
            {
                var currentUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.STATUS != SETrainSurveyStatus.草稿)
                {
                    throw new Exception("当前状态数据不可编辑");
                }
                if (entity.END_TIME == null)
                {
                    throw new Exception("请选择截止时间");
                }
                if (entity.LAUNCH_TIME == null)
                {
                    entity.LAUNCH_TIME = DateTime.Now;
                }
                if (entity.LAUNCH_TIME.Value.AddDays(1) > entity.END_TIME.Value)
                {
                    throw new Exception("截止时间至少比发起时间要大于一天");
                }
                if (entity.LAUNCH_USER_ID == Guid.Empty)
                {
                    entity.LAUNCH_USER_ID = (Guid)currentUserId;
                }
                var Nav_JoinDepartment = entity.Nav_JoinDepartment;
                var Nav_Points = entity.Nav_Points;
                if (Nav_JoinDepartment == null)
                {
                    throw new Exception("参与人员不可为空");
                }
                if (Nav_Points == null)
                {
                    throw new Exception("调查内容不可为空");
                }
                if (entity.LAUNCH_DEPARTMENT_ID == null)
                {
                    entity.LAUNCH_DEPARTMENT_ID = GetEntity<T_FM_USER>(entity.LAUNCH_USER_ID.ToString()).DEPARTMENT_ID;
                }
                List<T_SE_TRAIN_SURVEY_LIST_DEMAND> Nav_Demands = null;
                List<T_FM_NOTIFICATION_TASK> noticeTask = null;

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    Nav_Demands = new List<T_SE_TRAIN_SURVEY_LIST_DEMAND>();
                    entity.STATUS = SETrainSurveyStatus.调查中;
                    var allSendUserIds = GetDepartmentUsers(Nav_JoinDepartment.Where(t => t.IS_DELETED == false).Select(t => t.DEPARTMENT_ID).ToList(), entity.ORG_ID);
                    var currDep = GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.LAUNCH_DEPARTMENT_ID);
                    if (currDep != null && (currDep.NAME == "安全环保管理部" || currDep.NAME == "安全环保科" || currDep.NAME == "安全环保部" || currDep.NAME == "安环部"))
                    {
                        var manageUsers = GetEntities<T_FM_USER>(t => t.Nav_Department.DEPARTMENT_TYPE == 3 && t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(entity.ORG_ID)).Select(t => t.ID);
                        allSendUserIds.AddRange(manageUsers);
                    }
                    var allUsers = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && allSendUserIds.Contains(t.ID) && !t.CODE.Contains("admin"), new BaseFilter(entity.ORG_ID));
                    var allUserDepIds = new List<Guid?>();
                    var allSendUserNames = new List<string>();
                    var allSendDataIds = new List<Guid>();
                    var allSendTitles = new List<string>();

                    foreach (var user in allSendUserIds)
                    {
                        var current = allUsers.FirstOrDefault(t => t.ID == user);
                        allUserDepIds.Add(current?.DEPARTMENT_ID);
                        allSendUserNames.Add(current?.NAME);
                    }
                    for (int i = 0; i < allSendUserIds.Count; i++)
                    {
                        var newId = Guid.NewGuid();
                        Nav_Demands.Add(new T_SE_TRAIN_SURVEY_LIST_DEMAND
                        {
                            ID = newId,
                            SURVEY_ID = entity.ID,
                            USER_ID = allSendUserIds[i],
                            DEPARTMENT_ID = allUserDepIds[i],
                            OK = 0,
                            ORG_ID = entity.ORG_ID,
                        });
                        allSendDataIds.Add(newId);
                        allSendTitles.Add("培训需求调查填报");
                    }
                    noticeTask = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, entity.ORG_ID, allSendUserIds, allSendUserNames, DateTime.Now, entity.END_TIME.Value, (int)FMNoticeTypeEnum.消息, "SE007_INPUTPAGE");
                }
                Nav_JoinDepartment.ForEach(p =>
                p.Nav_Department = null
                );
                Nav_Points.ForEach(p =>
                p.Nav_Point = null
                );
                entity.Nav_JoinDepartment = null;
                entity.Nav_Points = null;
                entity.Nav_Demands = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (entity.TaskID != Guid.Empty)
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE007_SHOWPRINT");
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_JoinDepartment != null && Nav_JoinDepartment.Any())
                        BantchSaveEntityNoCommit(Nav_JoinDepartment);
                    if (Nav_Points != null && Nav_Points.Any())
                        BantchSaveEntityNoCommit(Nav_Points);
                    if (Nav_Demands != null && Nav_Demands.Any())
                        BantchAddEntityNoCommit(Nav_Demands);
                    if (noticeTask != null && noticeTask.Any())
                        BantchAddEntityNoCommit(noticeTask);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        /// <summary>
        /// 提交审阅
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("SubmitReport")]
        public JsonActionResult<bool> SubmitReport([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var finishId = new Guid(filter.Parameter2);
                var data = GetEntity<T_SE_TRAIN_SURVEY>(filter.Parameter1);
                if (data == null || data.STATUS != SETrainSurveyStatus.汇总中)
                {
                    throw new Exception("当前状记不可提交审阅");
                }
                data.STATUS = SETrainSurveyStatus.完成;
                var finishNoitice = NotificationTaskService.GetTaskFinishModel(finishId);
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(data, "STATUS");
                    if (finishNoitice != null)
                        UpdateEntityNoCommit(finishNoitice);
                });
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserDemand")]
        public JsonActionResult<T_SE_TRAIN_SURVEY_LIST_DEMAND> GetUserDemand([FromBody] KeywordFilter filter)
        {
            var uid = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var data = GetEntity<T_SE_TRAIN_SURVEY_LIST_DEMAND>(
                t => t.USER_ID == uid,
                filter);
            var ret = new JsonActionResult<T_SE_TRAIN_SURVEY_LIST_DEMAND>();
            ret.IsSuccessful = (data != null);
            ret.TotalCount = data == null ? 0 : 1;
            ret.Data = data;
            if (data == null)
            {
                ret.ErrorMessage = "未查到相应数据";
            }
            return ret;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("SubmitUserDemand")]
        public JsonActionResult<bool> SubmitUserDemand([FromBody] T_SE_TRAIN_SURVEY_LIST_DEMAND entity)
        {
            return SafeExecute(() =>
            {
                if (entity.OK == 1)
                {
                    throw new Exception("已提交的数据不可更改");
                }
                T_FM_NOTIFICATION_TASK finishNotice = null;
                var items = entity.Nav_Items;
                entity.Nav_Items = null;
                foreach (var item in items)
                {
                    item.Nav_DEMAND = null;
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var survry = GetEntity<T_SE_TRAIN_SURVEY>(t => t.ID == entity.SURVEY_ID);
                    if (survry != null)
                    {
                        if (DateTime.Now > survry.END_TIME)
                        {
                            finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                            UnifiedCommit(() =>
                            {
                                UpdateEntityNoCommit(finishNotice);
                            });
                            throw new Exception("已过截止时间!");

                        }
                    }
                    var currItemsCounts = items.Count(t => t.IS_DELETED == false);
                    if (currItemsCounts == 0 && entity.OTHER == null)
                    {
                        throw new Exception("请选择需求或填写其他");
                    }
                    entity.OK = 1;
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                }

                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    BantchSaveEntityNoCommit(items);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        private void GetUsersTree(List<T_FM_USER> users, Guid departID, bool getChild = false)
        {

            var us = GetEntities<T_FM_USER>(it => it.DEPARTMENT_ID == departID,
                new BaseFilter(null),
                new string[] { "Nav_Department" }).ToList();
            if (us != null && us.Count > 0)
            {
                users.AddRange(us);
            }
            if (getChild)
            {
                var dparts = GetEntities<T_FM_DEPARTMENT>(it => it.PARENT_ID == departID, new BaseFilter(null)).ToList();
                if (dparts != null && dparts.Count > 0)
                {
                    dparts.ForEach(d => GetUsersTree(users, d.ID, getChild));
                }
            }
        }
        /// <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 && !i.CODE.Contains("admin"), 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.ENABLE_STATUS == 0 && i.DEPARTMENT_ID != null && outputDepartmentIds.Contains((Guid)i.DEPARTMENT_ID) && !i.CODE.Contains("admin"), 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);
            }
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_SE_TRAIN_SURVEY> OrderPaged([FromBody] BasePageFilter filter)
        {
            var result =  WitOrderPaged(t=>t.TASK_ID!=null, filter);

            return result;
        }
    }
}
