using APT.BaseData.Domain.Enums.PF;
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.SC.PR;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using APT.BaseData.Domain.Entities;
using System.Collections.Generic;
using APT.BaseData.Domain.Entities.FM;
using APT.MS.Domain.Entities.SC.PE;
using APT.MS.Domain.Entities.FO;

namespace APT.SC.WebApi.Controllers.Api.PRController
{
    /// <summary>
    ///  变化管理验收表
    /// </summary>
    [Route("api/PR/PRChangeAcceptance")]
    public partial class ChangeAcceptanceController : AuthorizeApiController<T_PR_CHANGE_ACCEPTANCE>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 变化管理验收表
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public ChangeAcceptanceController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_PR_CHANGE_ACCEPTANCE> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var result = this.GetEntity<T_PR_CHANGE_ACCEPTANCE>(id, new string[] { "Nav_User", "Nav_Department",
            "Nav_Change","Nav_Change.Nav_User","Nav_Change.Nav_Department","Nav_Change.Nav_Types.Nav_Type","Nav_Change.Nav_Tasks.Nav_Task"});
                if (result != null && result.Nav_Change != null)
                {
                    result.CODE = result.Nav_Change.CODE;
                    result.DESCRIPTION = result.Nav_Change.DESCRIPTION;
                    if (result.Nav_Change.Nav_Types != null && result.Nav_Change.Nav_Types.Any())
                    {
                        result.Nav_Types = result.Nav_Change.Nav_Types;
                    }
                    if (result.Nav_Change.Nav_Tasks != null && result.Nav_Change.Nav_Tasks.Any())
                    {
                        result.Nav_Tasks = result.Nav_Change.Nav_Tasks;
                    }
                    if (result.STATUS == PFStandardStatus.Archived)
                    {
                        var taskUserId = this.GetEntity<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == result.ID && t.NOTICE_TITLE == "变化管理验收表-确认")?.USER_ID;
                        if (taskUserId != null)
                        {
                            var safeUser = this.GetEntity<T_FM_USER>(t => t.ID == taskUserId && t.ENABLE_STATUS == 0);
                            if (safeUser != null)
                            {
                                result.Nav_SafeUser = safeUser;
                            }
                        }
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PR_CHANGE_ACCEPTANCE entity)
        {
            return SafeExecute(() =>
            {
                entity.TIME = DateTime.Now;
                entity.STATUS = PFStandardStatus.Draft;
                var tasks = entity.Nav_Tasks;
                entity.Nav_Tasks = null;
                entity.Nav_Types = null;
                if (tasks != null && tasks.Any())
                {
                    tasks.Where(t => !t.IS_DELETED).ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.CHANGE_IDENTIFY_EVALUATION_ID = entity.CHANGE_IDENTIFY_EVALUATION_ID.Value;
                        t.Nav_Task = null;
                        //if (t.ACCEPTANCE_OPINION == 0)
                        //    throw new Exception("请选择正确的验收意见");
                    });
                }
                var acceptType = tasks.FirstOrDefault(t => t.ACCEPTANCE_OPINION == 0 || t.ACCEPTANCE_OPINION == null);
                if (acceptType != null)
                    throw new Exception("请选择正确的验收意见");
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                T_PR_CHANGE_TASK_IMPLEMENT implement = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var noThrough = tasks.Where(t => t.ACCEPTANCE_OPINION == PRAcceptanceOpinionEnum.NG);
                    if (noThrough != null && noThrough.Any())
                    {
                        var opinionReason = noThrough.FirstOrDefault(t => string.IsNullOrEmpty(t.NOTHROUGH_REASON));
                        if (opinionReason != null)
                            throw new Exception("验收不通过项必须填写不通过原因");
                        entity.STATUS = PFStandardStatus.Rejected;
                        var userIds = noThrough.Select(t => t.USER_ID).Distinct().ToList();
                        var taskIds = noThrough.Select(t => t.TASK_ID).Distinct().ToList();
                        var implements = this.GetEntities<T_PR_CHANGE_TASK_IMPLEMENT>(t => t.CHANGE_IDENTIFY_EVALUATION_ID == entity.CHANGE_IDENTIFY_EVALUATION_ID && userIds.Contains(t.USER_ID) && taskIds.Contains(t.TASK_ID), new BaseFilter(entity.ORG_ID), "Nav_User").ToList();
                        foreach (var item in noThrough)
                        {
                            implement = implements.FirstOrDefault(t => t.USER_ID == item.USER_ID && t.TASK_ID == item.TASK_ID);
                            if (implement != null)
                            {
                                implement.NOTHROUGH_REASON = item.NOTHROUGH_REASON;
                                implement.STATUS = PFStandardStatus.Rejected;
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("变化管理任务落实表-已驳回", implement.ID, entity.ORG_ID, implement.USER_ID.Value, implement.Nav_User.NAME, DateTime.Now,
                                                  DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR026"));
                            }
                        }
                    }
                    else
                    {
                        entity.STATUS = PFStandardStatus.Sign;
                        //发给安环部负责人确认
                        var userInfo = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0);
                        if (userInfo == null && entity.ORG_ID.ToString() == "3efd5276-632b-e379-9ff3-7a7546591fca")
                        {
                            userInfo = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0);
                        }
                        if (userInfo != null)
                        {
                            notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("变化管理验收表-确认", entity.ID, entity.ORG_ID, userInfo.ID, userInfo.NAME, DateTime.Now,
                                                     DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR028_SHOWPRINT"));
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "PR028_SHOWPRINT";
                    }
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (implement != null)
                        this.UpdateEntityNoCommit(implement);
                    if (tasks != null && tasks.Any())
                        this.BantchSaveEntityNoCommit(tasks);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 识别人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_PR_CHANGE_ACCEPTANCE model)
        {
            return SafeExecute<bool>(() =>
            {
                var entity = this.GetEntity<T_PR_CHANGE_ACCEPTANCE>(model.ID);
                entity.STATUS = PFStandardStatus.Archived;
                T_FM_NOTIFICATION_TASK task = null;
                if (model.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(model.TaskID);
                    task.SOURCE_FORMCODE = "PR028_SHOWPRINT";
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != entity)
                        UpdateEntityNoCommit(entity);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
    }
}
