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

namespace APT.SC.WebApi.Controllers.Api.PR
{
    /// <summary>
    ///  内部设计文件审核表
    /// </summary>
    [Route("api/PR/PRDesignDocumentReview")]
    public partial class DesignDocumentReviewController : AuthorizeApiController<T_PR_DESIGN_DOCUMENT_REVIEW>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 内部设计文件审核表
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public DesignDocumentReviewController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PR_DESIGN_DOCUMENT_REVIEW entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Requirements;
                var files = entity.Nav_Files;
                var pictures = entity.Nav_Pictures;
                entity.STATUS = PFStandardStatus.Draft;
                var loginUserId = 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)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                entity.USER_ID = loginUserId;
                var department = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId.Value && t.ENABLE_STATUS == 0, "Nav_Department");
                entity.DEPARTMENT_ID = department?.DEPARTMENT_ID;
                T_HM_RISK_TASK risk = null;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.DESIGN_DOCUMENT_REVIEW_ID = entity.ID;
                        t.Nav_Requirement = null;
                    });
                }
                if (files != null && files.Any())
                {
                    files.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.DESIGN_DOCUMENT_REVIEW_ID = entity.ID;
                    });
                }
                if (pictures != null && pictures.Any())
                {
                    pictures.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.DESIGN_DOCUMENT_REVIEW_ID = entity.ID;
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var user = this.GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == entity.DEPARTMENT_ID && t.Nav_ApproveRole != null && (t.Nav_ApproveRole.NAME == "部门安全员" || t.Nav_ApproveRole.NAME == "安环部安全员") && t.ENABLE_STATUS == 0);
                    if (user == null)
                    {
                        var userId = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.USER_ID;
                        user = this.GetEntity<T_FM_USER>(t => t.ID == userId && t.ENABLE_STATUS == 0);
                    }
                    if (user != null)
                    {
                        entity.STATUS = PFStandardStatus.Sign;
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("内部设计文件审核表", entity.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now,
                                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR003"));
                        risk = new T_HM_RISK_TASK();
                        risk.ORG_ID = entity.ORG_ID;
                        risk.STATUS = FOPreMeetingStatusEnum.草稿;
                        risk.INITIATING_DEPARTMENT = entity.DEPARTMENT_ID;
                        risk.LIABLE_USER_ID = entity.USER_ID;
                        var requst = this.GetEntity<T_HM_REQUEST>(t => true);
                        risk.REQUEST_ID = requst?.ID;
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("风险辨识任务", risk.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now,
                                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM062"));
                    }

                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "PR003_SHOWPRINT");
                        if (!task.SOURCE_DATA_ID.HasValue)
                        {
                            task.SOURCE_DATA_ID = entity.ID;
                        }
                    }
                }
                entity.Nav_Requirements = null;
                entity.Nav_Files = null;
                entity.Nav_Pictures = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (pictures != null && pictures.Any())
                        this.BantchSaveEntityNoCommit(pictures);
                    if (risk != null)
                        this.UpdateEntityNoCommit(risk);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }

        /// <summary>
        /// 新增/编辑(安全员)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("SafeFullUpdate")]
        public JsonActionResult<bool> SafeFullUpdate([FromBody] T_PR_DESIGN_DOCUMENT_REVIEW entity)
        {
            return SafeExecute(() =>
            {
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = PFStandardStatus.Approving;
                    entity.Nav_Requirements = null;
                    entity.Nav_Files = null;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    var param = entity.DESIGN_LEVEL.GetDescription();
                    MFlowPermitService.InsertApprove(serialCode[0], "PR003", param, entity.ID, "PR003_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (notices != null && notices.Any())
                            this.BantchSaveEntityNoCommit(notices);
                    }, null, null, null, null, null, "PR003_SHOWPRINT", null);
                    return true;
                }
                entity.Nav_Requirements = null;
                entity.Nav_Files = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_PR_DESIGN_DOCUMENT_REVIEW> 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_DESIGN_DOCUMENT_REVIEW>(id, new string[] { "Nav_User", "Nav_Department",
            "Nav_Requirements","Nav_Requirements.Nav_Requirement","Nav_Files","Nav_Files.Nav_ImgFile","Nav_Files.Nav_ImgFile"});
                return result;
            });
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("PR/PRDesignDocumentReview/BackUpdate", id);
            });
        }
    }
}
