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.Entities.SK;
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");
                T_FM_NOTIFICATION_TASK finishTask = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != null && entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userID = currTask.USER_ID;
                    }
                }
                if (entity.USER_ID == null)
                {
                    entity.USER_ID = userID;
                }
                if (entity.TEAM_ID == Guid.Empty|| entity.TEAM_ID == null)
                {
                    var currUser = GetEntity<T_FM_USER>(t=>t.ID==userID && t.ENABLE_STATUS==0);
                    var currTeam = GetEntity<T_FM_TEAM>(t=>t.DEPARTMENT_ID==currUser.DEPARTMENT_ID && t.ENABLE_STATUS == 0);
                    if (currTeam != null)
                    {
                        entity.TEAM_ID = currTeam.ID;
                    }
                    else
                    {
                        throw new Exception("请通过班组长发起班组安全活动!");
                    }
                }
                if (string.IsNullOrEmpty(entity.ADDRESS))
                {
                    throw new Exception("请填写活动地点");
                }
                if (string.IsNullOrEmpty(entity.DURATION))
                {
                    throw new Exception("请填写活动时长");
                }
                if (string.IsNullOrEmpty(entity.ACTIVITY_CONTENT))
                {
                    throw new Exception("请填写活动内容");
                }
                if (entity.ACTIVITY_TIME == DateTime.MinValue)
                {
                    throw new Exception("请修改活动日期!");
                }
                var users = entity.Nav_TeamActivityUser.Where(t => t.USER_ID != Guid.Empty);
                var files = entity.Nav_TeamActivityFile;
                entity.Nav_TeamActivityUser = null;
                entity.Nav_TeamActivityFile = null;
                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)
                {
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishTask = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO010_SHOWPRINT");
                        UpdateEntity(finishTask);
                    }
                    throw new Exception(entity.ACTIVITY_TIME.ToDateString() + "已存在班组安全活动记录!");
                }
                if (entity.OpType==0)
                {
                    entity.TA_STATUS = (int)FOTeamActivityState.签到中; //更新状态为签到中
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishTask = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO010_SHOWPRINT");
                    }
                    if (files == null || files.Count() == 0)
                    {
                        throw new Exception("请上传附件!");
                    }
                    //通知参会人员签到
                    var baseFilter = new BaseFilter(entity.ORG_ID);
                    baseFilter.SelectField = new string[] { "ID", "NAME" };   //指定字段，包括导航属性
                    var sendUsers = users.Where(t => t.IS_DELETED == false && t.ATTEND_STATUS == (int)FOAttendState.参与).ToList();
                    var userIds = sendUsers.Select(t => t.USER_ID);
                    var TeamUser = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID), baseFilter).ToList();
                    var noticeTitles = new List<string>();
                    var noticeUserIds = new List<Guid>();
                    var noticeUserNames = new List<string>();
                    var noticeDataIds = new List<Guid>();

                    foreach (var rs in sendUsers)   //按记录集进行循环写消息表
                    {
                        //当前登录人不用签到通知，默认已签到
                        if (rs.USER_ID == userID)
                        {
                            rs.SIGN_IN_STATUS = 1;
                            continue;
                        }
                        //if (rs.ATTEND_STATUS == (int)FOAttendState.请假 || rs.ATTEND_STATUS == 0)
                        //{
                        //    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);
                    }
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Now.AddHours(24), 0, "FO010_SHOWPRINT");
                };
                entity.Nav_User = null;
                entity.Nav_MainUser = null;
                //事务控制
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);   //更新主表
                    if(sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);   //保存用户子表                    
                    if (users.Any())
                        BantchSaveEntityNoCommit(users);   //保存用户子表                    
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);   //保存附件
                    if(finishTask!=null)
                        UpdateEntityNoCommit(finishTask);   //更新主表
                });
                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;
                if (entity.TaskID != null && entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userID = currTask.USER_ID;
                    }
                }
                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)
        {
            
            pageFilter.Include.Add("Nav_Taem");
            var result = new PagedActionResult<T_FO_TEAM_ACTIVITY>();
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var loginUserCode = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId && t.ENABLE_STATUS == 0)?.CODE;
            //安环部负责人departmentID
            var departStatus = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == loginDepartmentId && t.ENABLE_STATUS == 0)?.DEPARTMENT_STATUS;
            var ahRole = this.GetEntity<T_FM_USER_BELONG_ROLE>(t => t.Nav_BelongRole != null && t.Nav_BelongRole.NAME.Contains("安环") && t.USER_ID == loginUserId);
            if ((!string.IsNullOrEmpty(loginUserCode) && loginUserCode.Contains("admin")) || departStatus != (int)FMDepartmentStatus.生产部门 || ahRole != null)
            {
                pageFilter.IgnoreDataRule = true;
            }
            else
            {
                pageFilter.IgnoreDataRule = false;
            }
            result = this.GetOrderPageEntities<T_FO_TEAM_ACTIVITY>(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_FO_TEAM_ACTIVITY>(t => t.Nav_Taem != null && departmentIds.Contains((Guid)t.Nav_Taem.DEPARTMENT_ID), pageFilter);//|| dataIds.Contains(t.ID)
            //    }
            //    else
            //        result.Data = null;
            //}
            return result;
        }

        /// <summary>
        /// 根据主键删除数据
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet, Route("FullDelete")]
        public JsonActionResult<bool> FullDelete(string id)
        {
            return SafeExecute(() =>
            {
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var approves = new List<T_PF_APPROVE>();
                var tasks = new List<T_FM_NOTIFICATION_TASK>();
                var notices = new List<T_FO_TEAM_ACTIVITY>();
                var notice = this.GetEntity<T_FO_TEAM_ACTIVITY>(id);
                if (notice != null)
                {
                    notice.IS_DELETED = true;
                    notices.Add(notice);
                    approves = this.GetEntities<T_PF_APPROVE>(t => t.DATA_ID != null && t.DATA_ID == notice.ID, new BaseFilter(notice.ORG_ID)).ToList();
                    approves.ForEach(t => t.IS_DELETED = true);
                    var approveIds = approves.Select(t => t.ID).ToList();
                    tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID != null && (t.SOURCE_DATA_ID == notice.ID || approveIds.Contains((Guid)t.SOURCE_DATA_ID)), new BaseFilter(notice.ORG_ID)).ToList();
                    tasks.ForEach(t => t.IS_DELETED = true);
                }
                UnifiedCommit(() =>
                {
                    if (notices != null && notices.Any())
                        this.BantchUpdateEntity_noneBase(notices);
                    if (approves != null && approves.Any())
                        this.BantchUpdateEntity_noneBase(approves);
                    if (tasks != null && tasks.Any())
                        this.BantchUpdateEntity_noneBase(tasks);
                });
                return true;
            });
        }
    }
}
