using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SK;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.Enums;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Enums.SK;
using System.Threading.Tasks;
using System.Linq;
using System;
using System.Collections.Generic;
namespace APT.SK.WebApi.Controllers.Api
{
    /// 
    ///  隐患确认单
    /// 
    [Route("api/SK/SKHiddenDangerConfirm")]
    public partial class HiddenDangerConfirmController : AuthorizeApiController
    {
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        public HiddenDangerConfirmController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
        }
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult FullUpdate([FromBody] T_SK_HIDDEN_DANGER_CONFIRM entity)
        {
            return SafeExecute(() =>
            {
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var departId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                if (entity.APPLY_USER_ID == null)
                    entity.APPLY_USER_ID = userId;
                if (entity.APPLY_DEPARTMENT_ID == null)
                    entity.APPLY_DEPARTMENT_ID = departId;
                if (entity.RECITIFY_USER_ID == null)
                    throw new Exception("整改责任人必须填写");
                var photos = entity.Nav_Photos;
                entity.Nav_Photos = null;
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                var basics = entity.Nav_Basics;
                entity.Nav_Basics = null;
                entity.ApplyDepartmentName = this.GetEntity(t => t.ID == departId).NAME;
                entity.ApplyPostName = this.GetEntity(t => t.ID == userId, "Nav_Person.Nav_Post")?.Nav_Person?.Nav_Post?.NAME;
                if (string.IsNullOrEmpty(entity.HIDDEN_DESCRIPTION))
                {
                    entity.HIDDEN_DESCRIPTION = entity.Nav_Question?.DESCREPTION;
                }
                if (photos != null && photos.Any())
                {
                    foreach (var item in photos)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_CONFIRM_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_CONFIRM_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (basics != null && basics.Any())
                {
                    foreach (var item in basics)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_CONFIRM_ID = entity.ID;
                        item.Nav_Law = null;
                    }
                }
                if (entity.RECITIFY_TIME.HasValue && entity.RECITIFY_TIME.Value.Date < DateTime.Now.Date)
                {
                    throw new Exception("整改期限不得早于当前时间");
                }
                var libraryIds = this.GetEntities(t => t.AREA_ID == entity.RISK_AREA_ID, new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                var libraryDetailIds = this.GetEntities(t => libraryIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                var contentIds = this.GetEntities(t => libraryDetailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(entity.ORG_ID)).Select(t => t.CHECK_CONTENTS_ID).Distinct().ToList();
                if (contentIds != null && contentIds.Any() && contentIds.Contains(entity.CHECK_CONTENTS_ID))
                {
                    entity.IS_STORE = SKIsStoreEnum.No;
                }
                else
                {
                    entity.IS_STORE = SKIsStoreEnum.Yes;
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var hiddenLevel = entity.HIDDEN_LEVEL;
                    var param = Enum.GetName(typeof(SKHiddenLevel), hiddenLevel);
                    var level = (param == "Major" || param == "重大") ? "重大" : "一般";
                    if (hiddenLevel == SKHiddenLevel.General)
                    {
                        var departmentType = this.GetEntity(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.DEPARTMENT_TYPE;
                        level = Enum.GetName(typeof(FMDepartmentType), departmentType);
                    }
                    //触发审批
                    entity.STATUS = PFStandardStatus.Approving;
                    //取审批流水码
                    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[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "SK018", level, entity.ID, "SK018_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);
                        if (photos != null && photos.Any())
                            BantchSaveEntityNoCommit(photos);
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);
                        if (basics != null && basics.Any())
                            BantchSaveEntityNoCommit(basics);
                    }, null, null, null, null, null, "SK018_SHOWPRINT", null, level + "隐患确认单审批");
                    return true;
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (photos != null && photos.Any())
                        BantchSaveEntityNoCommit(photos);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                });
                return true;
            });
        }
        [HttpPost, Route("FullUpdateYL")]
        public JsonActionResult FullUpdateYL([FromBody] T_SK_HIDDEN_DANGER_CONFIRM entity)
        {
            return SafeExecute(() =>
            {
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var departId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                if (entity.APPLY_USER_ID == null)
                    entity.APPLY_USER_ID = userId;
                if (entity.APPLY_DEPARTMENT_ID == null)
                    entity.APPLY_DEPARTMENT_ID = departId;
                if (entity.RECITIFY_USER_ID == null)
                    throw new Exception("整改责任人必须填写");
                var photos = entity.Nav_Photos;
                entity.Nav_Photos = null;
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                var basics = entity.Nav_Basics;
                entity.Nav_Basics = null;
                if (string.IsNullOrEmpty(entity.HIDDEN_DESCRIPTION))
                {
                    entity.HIDDEN_DESCRIPTION = entity.Nav_Question?.DESCREPTION;
                }
                if (photos != null && photos.Any())
                {
                    foreach (var item in photos)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_CONFIRM_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_CONFIRM_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (basics != null && basics.Any())
                {
                    foreach (var item in basics)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_CONFIRM_ID = entity.ID;
                        item.Nav_Law = null;
                    }
                }
                if (entity.RECITIFY_TIME.HasValue && entity.RECITIFY_TIME.Value.Date < DateTime.Now.Date)
                {
                    throw new Exception("整改期限不得早于当前时间");
                }
                //var libraryIds = this.GetEntities(t => t.AREA_ID == entity.RISK_AREA_ID, new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                //var libraryDetailIds = this.GetEntities(t => libraryIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                //var contentIds = this.GetEntities(t => libraryDetailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(entity.ORG_ID)).Select(t => t.CHECK_CONTENTS_ID).Distinct().ToList();
                //if (contentIds != null && contentIds.Any() && contentIds.Contains(entity.CHECK_CONTENTS_ID))
                //{
                //    entity.IS_STORE = SKIsStoreEnum.No;
                //}
                //else
                //{
                //    entity.IS_STORE = SKIsStoreEnum.Yes;
                //}
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var param = Enum.GetName(typeof(SKHiddenLevel), entity.HIDDEN_LEVEL);
                    var level = (param == "Major" || param == "重大") ? "重大" : "一般";
                    if (entity.HIDDEN_LEVEL == SKHiddenLevel.General)
                    {
                        var departmentId = this.GetEntity(t => t.ID == entity.RECITIFY_USER_ID && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
                        if (departmentId != null)
                        {
                            var departmentType = this.GetEntity(t => t.ID == departmentId && t.ENABLE_STATUS == 0)?.DEPARTMENT_TYPE;
                            level = Enum.GetName(typeof(FMDepartmentType), departmentType);
                        }
                        else
                        {
                            var departmentType = this.GetEntity(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.DEPARTMENT_TYPE;
                            level = Enum.GetName(typeof(FMDepartmentType), departmentType);
                        }
                    }
                    //触发审批
                    entity.STATUS = PFStandardStatus.Approving;
                    //取审批流水码
                    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[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "SK018", level, entity.ID, "SK018_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);
                        if (photos != null && photos.Any())
                            BantchSaveEntityNoCommit(photos);
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);
                        if (basics != null && basics.Any())
                            BantchSaveEntityNoCommit(basics);
                    }, null, entity.RECITIFY_USER_ID, null, null, null, "SK018_SHOWPRINT", null, level + "隐患审批");
                    return true;
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (photos != null && photos.Any())
                        BantchSaveEntityNoCommit(photos);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                });
                return true;
            });
        }
        /// 
        /// 获得单条实体数据
        /// 
        /// 过滤实体
        /// 
        [HttpPost, Route("SKGet")]
        public JsonActionResult SKGet([FromBody] KeywordFilter filter)
        {
            filter.IgnoreDataRule = true;
            var result = WitEntity(null, filter);
            if (result != null && result.Data != null && result.Data.STATUS == PFStandardStatus.Rejected)
            {
                result.Data.CONTEXT = ApproveCallBackService.RejectContent(result.Data.ID);
            }
            return result;
        }
        /// 
        /// 回调函数
        /// 
        /// 
        /// 
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("SK/SKHiddenDangerConfirm/BackUpdateNew", entity);
            });
        }
        /// 
        /// 驳回
        /// 
        /// 
        /// 
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(model, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败!");
                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败!");
                var entity = this.GetEntity(model.DATA_ID, new string[] { "Nav_ApplyUser" });
                entity.STATUS = PFStandardStatus.Rejected;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                if (entity.APPLY_USER_ID != null)
                {
                    //发消息
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患确认单审批被驳回", entity.ID, entity.ORG_ID, (Guid)entity.APPLY_USER_ID, entity.Nav_ApplyUser?.NAME, DateTime.Now,
               DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK018");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
                //return ApproveCallBackService.CallReject("HM/HMLicenseAnalysis/RejectUpdate", id);
            });
        }
    }
}