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.FO;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    ///  安全交底表
    /// </summary>
    [Route("api/FO/FOTechDisclosureFromSafe")]
    public partial class TechDisclosureFromSafeController : AuthorizeApiController<T_FO_TECH_DISCLOSURE_FROM_SAFE>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public TechDisclosureFromSafeController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_TECH_DISCLOSURE_FROM_SAFE> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var entity = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM_SAFE>(id, "Nav_OperationStep", "Nav_User.Nav_UserSignFiles.Nav_ImgFile", "Nav_Department","Nav_Files.Nav_ImgFile");
                if (entity != null)
                {
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "TECH_DISCLOSURE_FROM_ID", "USER_ID", "Nav_User.NAME", "Nav_User.CODE", "Nav_User.FILE_PATH", "Nav_User.Nav_UserSignFiles.Nav_ImgFile" };
                    var persons = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM_SAFE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, newFilter).ToList();
                    entity.Nav_Person = persons.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
                }
                return entity;
            });
        }
        /// <summary>
        /// 新增修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_TECH_DISCLOSURE_FROM_SAFE entity)
        {
            return SafeExecute<bool>(() =>
            {
                entity.FORM_STATUS = (int)FOTeamActivityState.草稿;
                var persons = entity.Nav_Person;
                var deleteIds = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM_SAFE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                if (persons != null && persons.Any())
                {
                    persons = persons.Where(t => !t.IS_DELETED && t.USER_ID != null).ToList();
                }
                entity.Nav_Person = null;
                var files = entity.Nav_Files;
                var deleteFileIds = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM_SAFE_FILE>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                if (files != null && files.Any())
                {
                    files = files.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Files = null;
                T_FO_FIRE_JOB job = null;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var departmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                entity.DEPARTMENT_ID = departmentId;
                if (string.IsNullOrEmpty(entity.DisclosureContent))
                {
                    throw new Exception("交底内容必需填写");
                }
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    entity.CODE = "AQJD" + DateTime.Now.ToShortDateString().Replace("/", "") + new Random().Next(1, 999);
                }
                entity.DisclosureContent = entity.DisclosureContent.Trim().Replace(" ", "");
                if (persons != null && persons.Any())
                {
                    persons.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.TECH_DISCLOSURE_FROM_ID = entity.ID;
                        t.Nav_User = null;
                    });
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.DISCLOSURE_DATE == null || entity.DISCLOSURE_DATE == DateTime.Parse("0001-01-01 00:00:00"))
                        throw new Exception("交底时间必需填写");

                    entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                    persons.ForEach(t =>
                    {
                        if (t.USER_ID == loginUserId)
                            t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                    });
                    //新增的消息通知
                    var userIds = persons.Where(m => m.USER_ID != null && m.USER_ID != loginUserId).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                    if (userIds != null && userIds.Any())
                    {
                        var UserNames = new List<string>();
                        var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                        foreach (var u in userIds)
                        {
                            var current = user.FirstOrDefault(t => t.ID == u);
                            UserNames.Add(current?.NAME);
                        }
                        //发消息
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                        notices = NotificationTaskService.InsertUserNoticeTaskModels("安全交底表确认" + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0'), entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "FO037_SHOWPRINT");
                    }
                    else
                    {
                        entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                        if (entity.FIRE_JOB_ID != null)
                        {
                            job = this.GetEntity<T_FO_FIRE_JOB>(t => t.ID == entity.FIRE_JOB_ID);
                            if (job != null)
                            {
                                job.IS_RUN = true;
                                job.FIRE_STATUS = FOFireStatus.Sign;
                                var jobUsers= this.GetEntities<T_FO_FIRE_JOB_USER>(t => t.FIRE_JOB_ID == job.ID,new BaseFilter(job.ORG_ID));
                                var userType = this.GetEntity<T_OG_RELATED_USER_TYPE>(t => t.NAME == "动火操作人员");
                                var sendUser = jobUsers.FirstOrDefault(t => t.USER_TYPE_ID == userType.ID);
                                if (sendUser != null)
                                {
                                    var userName = this.GetEntity<T_FM_USER>(t => t.ID == sendUser.USER_ID)?.NAME;
                                    var notice = NotificationTaskService.InsertUserNoticeTaskModel("动火作业现场条件验收", job.ID, job.ORG_ID, (Guid)sendUser.USER_ID, userName, DateTime.Now,
                                                         DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043_1");
                                    notices.Add(notice);
                                }
                            }
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "FO037_SHOWPRINT";
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (deleteIds != null && deleteIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_TECH_DISCLOSURE_FROM_SAFE_PERSON>(deleteIds);
                    if (deleteFileIds != null && deleteFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_TECH_DISCLOSURE_FROM_SAFE_FILE>(deleteFileIds);
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (persons != null && persons.Any())
                        this.BantchSaveEntityNoCommit(persons);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (job != null)
                        UpdateEntityNoCommit(job);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 签到同意
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_TECH_DISCLOSURE_FROM_SAFE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (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_FIRE_JOB job = null;
                T_FM_NOTIFICATION_TASK notice = null;
                var tech = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM_SAFE>(entity.ID);
                var user = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM_SAFE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == tech.ID && t.USER_ID == userID, new BaseFilter(orgId));
                user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                var todoCount = this.GetCount<T_FO_TECH_DISCLOSURE_FROM_SAFE_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == tech.ID && t.DEAL_STATUS == 0 && t.USER_ID != null && t.USER_ID != userID, new BaseFilter(orgId));
                if (todoCount == 0)
                {
                    tech.FORM_STATUS = (int)FOTeamActivityState.已归档;
                    if (tech.FIRE_JOB_ID != null)
                    {
                        job = this.GetEntity<T_FO_FIRE_JOB>(t => t.ID == tech.FIRE_JOB_ID);
                        if (job != null)
                        {
                            job.IS_RUN = true;
                            job.FIRE_STATUS = FOFireStatus.Sign;
                            var jobUsers = this.GetEntities<T_FO_FIRE_JOB_USER>(t => t.FIRE_JOB_ID == job.ID, new BaseFilter(job.ORG_ID));
                            var userType = this.GetEntity<T_OG_RELATED_USER_TYPE>(t => t.NAME == "动火操作人员");
                            var sendUser = jobUsers.FirstOrDefault(t => t.USER_TYPE_ID == userType.ID);
                            if (sendUser != null)
                            {
                                var userName = this.GetEntity<T_FM_USER>(t => t.ID == sendUser.USER_ID)?.NAME;
                                notice = NotificationTaskService.InsertUserNoticeTaskModel("动火作业现场条件验收", job.ID, job.ORG_ID, (Guid)sendUser.USER_ID, userName, DateTime.Now,
                                                     DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043_1");
                            }
                        }
                    }
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO037_SHOWPRINT";
                }
                this.UnifiedCommit(() =>
                {
                    if (tech != null)
                        UpdateEntityNoCommit(tech);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (job != null)
                        this.UpdateEntityNoCommit(job);
                    if (notice != null)
                        this.AddEntityNoCommit(notice);
                });
                return true;
            });
        }
    }
}
