using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.IServices;
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.Infrastructure.Core;
using APT.MS.Domain.Enums.SK;
using APT.MS.Domain.Enums;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SK.WebApi.Controllers.Api
{
    [Route("api/SK/SKHiddenDangerRectifyDelayApply")]
    public partial class HiddenDangerRectifyDelayApplyController : AuthorizeApiController<T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY>
    {
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        public HiddenDangerRectifyDelayApplyController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
        }
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY entity)
        {
            return SafeExecute<bool>(() =>
            {
                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;
                entity.ApplyDepartmentName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == departId).NAME;
                entity.ApplyPostName = this.GetEntity<T_FM_USER>(t => t.ID == userId, "Nav_Person.Nav_Post")?.Nav_Person?.Nav_Post?.NAME;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Rejected)
                {
                    var taskId = entity.TaskID;
                    if (taskId == Guid.Empty)
                    {
                        var taskTemp = GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userId
                && i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() && i.SOURCE_FORMCODE == "SK024");
                        if (taskTemp != null)
                        {
                            taskTemp.NOTICE_STATUS = 1;
                            taskTemp.SOURCE_FORMCODE = "SK024_SHOWPRINT";
                            finishNotice = taskTemp;
                        }
                    }
                    if (taskId != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(taskId, entity.ID, "SK024_SHOWPRINT");
                    }
                    UpdateEntity(finishNotice);
                    throw new Exception("你已提交,请勿重复提交!");
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var record = this.GetEntity<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(t => t.ID == entity.HIDDEN_DANGER_RECTIFY_RECORD_ID);
                    if (record != null)
                    {
                        var hiddenLevel = record.HIDDEN_LEVEL;
                        var param = Enum.GetName(typeof(SKHiddenLevel), hiddenLevel);
                        var level = param == "Major" ? "重大" : "一般";
                        if (hiddenLevel == SKHiddenLevel.General)
                        {
                            var departmentType = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0);
                            //param = Enum.GetName(typeof(FMDepartmentType), departmentType);
                            if (departmentType != null)
                            {
                                level = ((SKDepartmentTypeEnum)departmentType.DEPARTMENT_TYPE).GetDescription();
                                if (departmentType.DEPARTMENT_STATUS == 2)
                                {
                                    level = "公司级";
                                }
                            }
                        }
                        entity.STATUS = PFStandardStatus.Approving;
                        entity.Nav_RectifyRecord = null;
                        entity.Nav_ApplyUser = null;
                        entity.Nav_ApplyDepartment = 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[] { ',' });
                        MFlowPermitService.InsertApprove(serialCode[0], "SK024", level, entity.ID, "SK024_SHOWPRINT", entity.TaskID, true, () =>
                        {
                            if (entity != null)
                                UpdateEntityNoCommit(entity);
                        }, null, null, null, null, null, "SK024_SHOWPRINT", null, level + "延期整改申请审批");
                        return true;
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                });
                return true;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SKGet")]
        public JsonActionResult<T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY> SKGet([FromBody] KeywordFilter filter)
        {
            filter.IgnoreDataRule = true;
            filter.Include.Add("Nav_RectifyRecord.Nav_Question");
            filter.Include.Add("Nav_RectifyRecord.Nav_RiskArea");
            filter.Include.Add("Nav_RectifyRecord.Nav_RectifyPhotoas.Nav_ImgFile");
            filter.Include.Add("Nav_ApplyUser");
            filter.Include.Add("Nav_ApplyDepartment");
            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;
        }
        /// <summary>
        /// 验收人审阅
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                var apply = this.GetEntity<T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY>(entity.ID);
                if (apply != null)
                    apply.STATUS = PFStandardStatus.Archived;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "SK024_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (apply != null)
                        this.UpdateEntityNoCommit(apply);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult<bool> BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("SK/SKHiddenDangerRectifyDelayApply/BackUpdateNew", entity);
            });
        }
        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> 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<T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY>(model.DATA_ID, new string[] { "Nav_ApplyUser" });
                entity.STATUS = PFStandardStatus.Rejected;
                T_FM_NOTIFICATION_TASK notice = null;
                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.消息, "SK024");
                }
                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);
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SKOrderPaged")]
        public PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY> SKOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            pageFilter.IgnoreDataRule = true;
            pageFilter.SelectField = new string[] { "ID", "HIDDEN_DANGER_RECTIFY_RECORD_ID","DELAY_RECITIFY_TIME","RECITIFY_MEASURES_TEMP",
                        "APPLY_USER_ID","APPLY_DEPARTMENT_ID","Nav_RectifyRecord.CODE","MineType","Nav_RectifyRecord.HIDDEN_PLACE","Nav_RectifyRecord.HIDDEN_LEVEL","Nav_RectifyRecord.RECITIFY_TIME",
                        "DELAY_REASON","STATUS","Nav_ApplyUser","Nav_ApplyDepartment","Nav_RectifyRecord.Nav_RiskArea.NAME","Nav_RectifyRecord.Nav_Contents","Nav_RectifyRecord.Nav_Question.DESCREPTION",
                        "Nav_RectifyRecord.Nav_RectifyPhotoas.Nav_ImgFile",
                         "Nav_RectifyRecord.Nav_RectifyPhotoas.IMG_FILE_ID" };
            var result = this.GetOrderPageEntities<T_SK_HIDDEN_DANGER_RECTIFY_DELAY_APPLY>(null, pageFilter);
            return result;
        }
        /// <summary>
        /// 取整改记录，落实人为本人，且状态为草稿的
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("RecordOrderPaged")]
        public PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> RecordOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            pageFilter.IgnoreDataRule = true;
            pageFilter.SelectField = new string[] { "ID", "CODE", "Nav_ProductionUnit.NAME", "Nav_RiskArea.NAME","HIDDEN_PLACE","HIDDEN_LEVEL","Nav_Question.DESCREPTION","RECITIFY_TIME","Nav_RectifyPhotoas","Nav_RectifyPhotoas.Nav_ImgFile.FILE_PATH" };
            var result = this.GetOrderPageEntities<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(t=>t.IMPLEMENT_USER_ID == userId && t.STATUS == PFStandardStatus.Draft, pageFilter);
            return result;
        }
    }
}
