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.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;

namespace APT.FO.WebApi.Controllers.Api.FO
{
    [Route("api/FO/FOTeamActivity")]
    public class TeamActivityController : AuthorizeApiController<T_FO_TEAM_ACTIVITY>
    {

        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }


        public TeamActivityController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;
            DepartmentService = departmentService;
        }

        /// <summary>
        /// 保存
        /// </summary>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_TEAM_ACTIVITY entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.Nav_TeamActivityUser == null || entity.Nav_TeamActivityUser.Count() == 0) this.ThrowError("040002");

                var users = entity.Nav_TeamActivityUser.Where(t => t.USER_ID != Guid.Empty);
                entity.Nav_TeamActivityUser = null;

                var files = entity.Nav_TeamActivityFile;
                entity.Nav_TeamActivityFile = null;
                
                if (entity.ACTIVITY_TIME == DateTime.MinValue)
                {
                    throw new Exception("请修改活动日期!");
                }
                HashSet<Guid> set = new HashSet<Guid>();
                foreach (var item in users.Where(t => t.IS_DELETED == false))
                {
                    if (!set.Add(item.USER_ID))
                    {
                        throw new Exception("人员存在重复!");
                    }
                }
                var isRepeat = GetEntity<T_FO_TEAM_ACTIVITY>(t => t.TEAM_ID == entity.TEAM_ID && t.ACTIVITY_TIME == entity.ACTIVITY_TIME && t.TA_STATUS != 0);
                if (isRepeat != null)
                {
                    throw new Exception(entity.ACTIVITY_TIME.ToDateString() + "已存在班组安全活动记录!");
                }
                T_FM_NOTIFICATION_TASK finishTask = null;
                if (entity.TaskID != Guid.Empty && entity.OpType != null && entity.OpType == 0)
                {
                    finishTask = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO010_SHOWPRINT");
                }
                //事务控制
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        if (entity != null && entity.OpType == 0) entity.TA_STATUS = (int)FOTeamActivityState.签到中; //更新状态为签到中

                    if (entity.ID == System.Guid.Empty)
                    {
                        AddEntityNoCommit(entity);      //新增主表
                    }
                    else
                    {
                        UpdateEntityNoCommit(entity);   //更新主表
                    }
                    if (users.Any()) BantchSaveEntityNoCommit(users);   //保存用户子表                    
                    if (files != null && files.Any()) BantchSaveEntityNoCommit(files);   //保存附件
                    UpdateEntityNoCommit(finishTask);   //更新主表
                });

                if (entity != null && entity.OpType == 0)
                {
                    if (files == null || files.Count() == 0)
                    {
                        throw new Exception("请上传附件!");
                    }
                    //通知参会人员签到
                    var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var baseFilter = new BaseFilter(entity.ORG_ID);
                    baseFilter.SelectField = new string[] { "ID", "NAME" };   //指定字段，包括导航属性
                    users = users.Where(t => t.IS_DELETED == false).ToList();
                    var userIds = users.Select(t => t.USER_ID);
                    var TeamUser = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID), baseFilter).ToList();
                    if (users.Count() > 0)    //判断是否有记录
                    {
                        var noticeTitles = new List<string>();
                        var noticeUserIds = new List<Guid>();
                        var noticeUserNames = new List<string>();
                        var noticeDataIds = new List<Guid>();

                        foreach (var rs in users)   //按记录集进行循环写消息表
                        {
                            //当前登录人不用签到通知，默认已签到
                            if (rs.USER_ID == userID)
                            {
                                rs.SIGN_IN_STATUS = 1;
                                continue;
                            }
                            if (rs.ATTEND_STATUS == (int)FOAttendState.缺席)
                            {
                                noticeTitles.Add("班组安全活动记录表-查阅确认");
                            }
                            else
                            {
                                noticeTitles.Add("班组安全活动记录表-签到确认");
                            }
                            noticeUserIds.Add(rs.USER_ID);
                            var userName = TeamUser.Where(t => t.ID == rs.USER_ID).FirstOrDefault().NAME;
                            noticeUserNames.Add(userName);
                            noticeDataIds.Add(entity.ID);
                        }
                        if (entity.TaskID != Guid.Empty)
                        {
                            //写消息表-增加消息
                            NotificationTaskService.SendAndFinishNotificationTask(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Now.AddHours(24), 0, "FO010_SHOWPRINT", entity.TaskID, () =>
                            {
                                if (users.Any())
                                    BantchSaveEntityNoCommit(users);
                            });
                        }
                        else
                        {
                            //写消息表-增加消息
                            NotificationTaskService.SendNotificationTask(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Now.AddHours(24), 0, "FO010_SHOWPRINT", () =>
                            {
                                if (users.Any())
                                    BantchSaveEntityNoCommit(users);
                            });
                        }
                    }
                };
                return true;
            });
        }
        /// <summary>
        /// 更新--已阅
        /// </summary>
        [HttpPost, Route("TeamActivityUserRead")]
        public JsonActionResult<bool> TeamActivityUserRead([FromBody] T_FO_TEAM_ACTIVITY entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.TaskID == Guid.Empty)
                {
                    throw new Exception("没有待办任务ID,请刷新重试!");
                }
                NotificationTaskService.NotificationTaskFinish(entity.TaskID, () =>
                {

                });
                return true;
            });
        }
        /// <summary>
        /// 更新--保存签到
        /// </summary>
        [HttpPost, Route("TeamActivityUserUpdate")]
        public JsonActionResult<bool> TeamActivityUserUpdate([FromBody] T_FO_TEAM_ACTIVITY entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.TaskID == Guid.Empty)
                {
                    throw new Exception("没有待办任务ID,请刷新重试!");
                }
                T_FM_NOTIFICATION_TASK task = null;
                var orgId = entity.ORG_ID;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_FO_TEAM_ACTIVITY_USER user = new T_FO_TEAM_ACTIVITY_USER();
                T_FO_TEAM_ACTIVITY Teams = null;
                user = GetEntity<T_FO_TEAM_ACTIVITY_USER>(t => t.TEAM_ACTIVITY_ID == entity.ID && t.USER_ID == userID.Value);
                if (user != null)
                {
                    user.SIGN_IN_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    task = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                    //判断是否全部已签到，更新表单状态为“已归档”
                    var TeamUser = this.GetEntities<T_FO_TEAM_ACTIVITY_USER>(t => t.TEAM_ACTIVITY_ID == entity.ID && t.SIGN_IN_STATUS == 0 && t.ATTEND_STATUS == 1 && t.USER_ID != userID.Value, new BaseFilter(orgId)).ToList();
                    if (TeamUser.Count == 0)
                    {
                        Teams = GetEntity<T_FO_TEAM_ACTIVITY>(b => b.ID == entity.ID);
                        Teams.TA_STATUS = (int)FOTeamActivityState.已归档;
                    }
                    this.UnifiedCommit(() =>
                    {
                        this.UpdateEntityNoCommit(user, "SIGN_IN_STATUS");  //更新子表的签到状态
                        //entity.OpType = 0;
                        //TaskUpdate(entity);     //更新对应消息表ID为已办状态 
                        if (task != null)
                            UpdateEntity(task);
                        if (Teams != null)
                            UpdateEntity(Teams);
                    });
                }
                else
                {
                    var deleteTask = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);
                    DeleteEntity(deleteTask);
                }
                return true;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FO_TEAM_ACTIVITY> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_TEAM_ACTIVITY>();
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity<T_FM_USER>(t => t.CODE.Contains("admin") && t.ENABLE_STATUS == 0)?.ID;
            var currDep = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var AHDepartment = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" || t.Nav_ApproveRole.NAME == "安环部安全员").DEPARTMENT_ID;
            if (loginUserId == null || loginUserId == admiId || currDep == AHDepartment)
            {
                result = this.GetOrderPageEntities<T_FO_TEAM_ACTIVITY>(null, pageFilter);
            }
            else
            {
                var loginDepartmentId = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
                List<Guid> departmentId = new List<Guid>();
                departmentId.Add((Guid)loginDepartmentId);
                List<Guid> departmentIds = new List<Guid>() { currDep };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_TEAM_ACTIVITY>(t => (departmentIds.Contains((Guid)t.Nav_Taem.DEPARTMENT_ID)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }
    }
}
