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

namespace APT.SC.WebApi.Controllers.Api.PEController
{
    /// <summary>
    ///  年度安全绩效监测计划
    /// </summary>
    [Route("api/PE/PESafetyMonitorPlan")]
    public partial class SafetyMonitorPlanController : AuthorizeApiController<T_PE_SAFETY_MONITOR_PLAN>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public SafetyMonitorPlanController(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_PE_SAFETY_MONITOR_PLAN entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Details;
                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 = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                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 =>
                    {
                        //if (t.ASSESSMENT_CYCLE == PTAssessmentCycleNewEnums.Day)
                        //    this.ThrowError("040051");
                        t.ORG_ID = entity.ORG_ID; t.SAFETY_MONITOR_PLAN_ID = entity.ID;
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = PFStandardStatus.Approving;
                    entity.Nav_Details = 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], "PE019", "", entity.ID, "PE019_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (details != null && details.Any())
                            this.BantchSaveEntityNoCommit(details);
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                        if (notices != null && notices.Any())
                            this.BantchSaveEntityNoCommit(notices);
                    }, null, null, null, null, null, "PE019_SHOWPRINT", null);
                    return true;
                    //if (entity.TaskID != Guid.Empty)
                    //{
                    //    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    //}
                }
                entity.Nav_Details = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_PE_SAFETY_MONITOR_PLAN> 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_PE_SAFETY_MONITOR_PLAN>(id, new string[] {"Nav_User", "Nav_Department","Nav_ProductionUnit",
            "Nav_Details","Nav_Details.Nav_Department","Nav_Details.Nav_Project","Nav_Details.Nav_User"});
                return result;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("PE/PESafetyMonitorPlan/BackUpdate", id);
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRecordEdit")]
        public JsonActionResult<T_PE_SAFETY_MONITOR_PLAN> GetRecordEdit([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 record = this.GetEntity<T_PE_SAFETY_MONITOR_RECORD>(id);
                var result = new T_PE_SAFETY_MONITOR_PLAN();
                if (record != null)
                {
                    result = this.GetEntity<T_PE_SAFETY_MONITOR_PLAN>(t=>t.ID == record.SAFETY_MONITOR_PLAN_ID, new string[] {"Nav_User", "Nav_Department","Nav_ProductionUnit",
            "Nav_Details","Nav_Details.Nav_Department","Nav_Details.Nav_Project","Nav_Details.Nav_User"});
                    if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                    {
                        var records = this.GetEntities<T_PE_SAFETY_MONITOR_RECORD>(t => t.SAFETY_MONITOR_PLAN_ID == result.ID && t.ASSESSMENT_CYCLE == record.ASSESSMENT_CYCLE, new BaseFilter(result.ORG_ID), "Nav_Details", "Nav_MonitorUser.Nav_User").ToList();
                        result.Nav_Details = result.Nav_Details.Where(t => t.ASSESSMENT_CYCLE == record.ASSESSMENT_CYCLE).ToList();
                        if (result.Nav_Details != null && result.Nav_Details.Any())
                        {
                            foreach (var item in result.Nav_Details)
                            {
                                var temp = records.FirstOrDefault(t => t.USER_ID == item.USER_ID);
                                if (temp != null && temp.Nav_Details != null && temp.Nav_Details.Any())
                                {
                                    var first = temp.Nav_Details.FirstOrDefault(t => t.PROJECT_ID == item.PROJECT_ID && t.CONTENTS == item.CONTENTS && t.STANDARD == item.STANDARD && t.METHOD == item.METHOD);
                                    item.MONITOR_LIVE = first?.MONITOR_LIVE;
                                    item.RESULT_DISCUSS = first?.RESULT_DISCUSS;
                                }
                                if (temp != null && temp.Nav_MonitorUser != null && temp.Nav_MonitorUser.Any())
                                {
                                    item.Nav_MonitorUser = temp.Nav_MonitorUser;
                                }
                            }
                        }
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 根据生产单元带出考评项目
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSafetyPlanDetail")]
        public JsonActionResult<T_PE_SAFETY_MONITOR_PLAN> GetSafetyPlanDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_PE_SAFETY_MONITOR_PLAN main = new T_PE_SAFETY_MONITOR_PLAN();
                List<T_PE_SAFETY_MONITOR_PLAN_DETAIL> detailList = new List<T_PE_SAFETY_MONITOR_PLAN_DETAIL>();
                filter.SelectField = new List<string> { "ORG_ID", "ID","NAME","CODE" };
                var monitorProjects = this.GetEntities<T_PE_MONITOR_PROJECT>(t => !t.IS_DELETED, filter).ToList();
                if (monitorProjects != null && monitorProjects.Any())
                {
                    var cycle = PTAssessmentCycleEnums.Year;
                    var set = this.GetEntity<T_PT_TIME_SET>(t => t.ENABLE_STATUS == 0 && t.SET_TYPE == PTSetTypeEnum.SafetyMonitorPlan);
                    if (set != null)
                    {
                        switch (set.PLANCHECKFREQUENCY)
                        {
                            case BSPLANCHECKFREQUENCYEnum.Date:
                                cycle= PTAssessmentCycleEnums.Day; break;
                            case BSPLANCHECKFREQUENCYEnum.Week:
                                cycle = PTAssessmentCycleEnums.Week; break;
                            case BSPLANCHECKFREQUENCYEnum.Month:
                                cycle = PTAssessmentCycleEnums.Month; break;
                            case BSPLANCHECKFREQUENCYEnum.Quarter:
                                cycle = PTAssessmentCycleEnums.Quarter; break;
                            case BSPLANCHECKFREQUENCYEnum.HalfYear:
                                cycle = PTAssessmentCycleEnums.HalfYear; break;
                            case BSPLANCHECKFREQUENCYEnum.Year:
                                cycle = PTAssessmentCycleEnums.Year; break;
                            default: cycle = PTAssessmentCycleEnums.Year; break;
                        }
                    }
                    var id = Guid.NewGuid();
                    foreach (var project in monitorProjects)
                    {
                        T_PE_SAFETY_MONITOR_PLAN_DETAIL detail = new T_PE_SAFETY_MONITOR_PLAN_DETAIL();
                        detail.ORG_ID = project.ORG_ID;
                        detail.SAFETY_MONITOR_PLAN_ID = id;
                        detail.PROJECT_ID = project.ID;
                        detail.Nav_Project = project;
                        detail.ASSESSMENT_CYCLE = cycle;
                        detailList.Add(detail);
                    }
                }
                main.Nav_Details = detailList.ToList();
                return main;
            });
        }
    }
}
