using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
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.CM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.CM
{
    [Route("api/CM/CMDrillPlan")]
    public class CMDrillPlanController : AuthorizeApiController<T_CM_DRILL_PLAN>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMDrillPlanController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMNotificationTaskService notificationTaskService, IFMUserService userService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificationTaskService = notificationTaskService;
            UserService = userService;
        }

        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_CM_DRILL_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                #region     值判断

                var listPlanDetail = entity.Nav_listPlanDetail;
                entity.Nav_listPlanDetail = null;

                List<T_CM_DRILL_PLAN_STANDARD_CREATE> listFiles = null;
                foreach (var item in listPlanDetail)
                {
                    if (item.Nav_ListStandard != null && item.Nav_ListStandard.Any())
                    {
                        if (listFiles == null)
                        {
                            listFiles = new List<T_CM_DRILL_PLAN_STANDARD_CREATE>();
                        }
                        listFiles.AddRange(item.Nav_ListStandard);
                    }
                }

                if (!entity.DEPARTMENT_ID.HasValue)
                {
                    throw new Exception("请选择制定部门！");
                }
                if (entity.YEAR == 0)
                {
                    throw new Exception("请选择年份！");
                }

                #endregion

                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);
                        if (listPlanDetail != null && listPlanDetail.Any())//明细
                            BantchSaveEntityNoCommit(listPlanDetail);
                        if (listFiles != null && listFiles.Any())//关联应急预案
                            BantchSaveEntityNoCommit(listFiles);
                    });
                }
                else
                {
                    int RowIndex = 1;
                    T_CM_DRILL_PLAN_DETAIL check = null;
                    foreach (var item in listPlanDetail)
                    {
                        if (!item.DRLL_DATE.HasValue)
                        {
                            throw new Exception("请选择应急演练时间【行：" + RowIndex + "】！");
                        }
                        else
                        {
                            item.DRLL_DATE = Convert.ToDateTime(item.DRLL_DATE.Value.ToString("yyyy-MM-01 00:00:00")).AddMonths(1).AddSeconds(-1);
                            if (item.DRLL_DATE.Value.Year != entity.YEAR)
                            {
                                throw new Exception("应急演练时间年份应与演练计划一致【" + entity.YEAR.ToString() + "】！");
                            }
                        }

                        if (!item.DEPARTMENT_ID.HasValue)
                        {
                            throw new Exception("组织演练部门不能为空【行：" + RowIndex + "】！");
                        }
                        if (!item.USER_ID.HasValue)
                        {
                            throw new Exception("责任人不能为空【行：" + RowIndex + "】！");
                        }
                        if (!item.TRIGGER_TIME.HasValue)
                        {
                            throw new Exception("请选择演练方案触发时间【行：" + RowIndex + "】！");
                        }
                        if (item.TRIGGER_TIME.Value > item.DRLL_DATE.Value)
                        {
                            throw new Exception("演练方案触发时间不能迟于应急演练时间【行：" + RowIndex + "】！");
                        }
                        check = listPlanDetail.FirstOrDefault(e => e.ID != item.ID && e.NAME.Trim() == item.NAME.Trim());
                        if (check != null)
                            throw new Exception("应急演练名称不能重复【行：" + RowIndex + "】！");

                        RowIndex++;
                    }

                    entity.APPROVE_ID = Guid.NewGuid();
                    var serialCode = DateTime.Now.ToString("yyyyMMddHHmmss");

                    T_FM_NOTIFICATION_TASK taskEnd = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "CM002_SHOWPRINT");
                        if (!taskEnd.SOURCE_DATA_ID.HasValue)
                            taskEnd.SOURCE_DATA_ID = entity.ID;
                    }
                    MFlowPermitService.InsertApprove("CM" + serialCode, "CM002", null, entity.ID, "CM002_SHOWPRINT", null, true, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);
                        if (taskEnd != null)//明细
                            UpdateEntityNoCommit(taskEnd);
                        if (listPlanDetail != null && listPlanDetail.Any())//明细
                            BantchSaveEntityNoCommit(listPlanDetail);
                        if (listFiles != null && listFiles.Any())//关联应急预案
                            BantchSaveEntityNoCommit(listFiles);
                    }, entity.APPROVE_ID, null, null, null, null, "CM002_SHOWPRINT", null, "年度应急演练计划审批");
                }

                return true;
            });
        }


        /// <summary>
        /// 年度应急演练计划表  审批结束
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("DrillPlanEnd")]
        public JsonActionResult<bool> CheckAuditEnd(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("CM/CMDrillPlan/DrillPlanEnd", id);
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("DetailOrderPaged")]
        public PagedActionResult<T_CM_DRILL_PLAN_DETAIL> DetailOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_CM_DRILL_PLAN_DETAIL> result)
            {
                DateTime Time = DateTime.Now;
                if (pageFilter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "TIME" && item.Value.ToString() != "")
                        {
                            Time = Convert.ToDateTime(item.Value.ToString());

                        }
                    }
                    pageFilter.FilterGroup.Rules.Clear();
                }

                Guid depID = Guid.Empty;
                Expression<Func<T_CM_DRILL_PLAN_DETAIL, bool>> expression = e => e.TRIGGER_TIME != null && e.TRIGGER_TIME.Value.Year == Time.Year && !e.IS_DELETED && e.Nav_PLAN.YEAR == Time.Year && e.Nav_PLAN.STATUS == PFStandardStatus.Archived;
                var userLogin = GetEntity<T_FM_USER>(e => e.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID, "Nav_Department");
                if (userLogin.Nav_Department.DEPARTMENT_TYPE == 0)
                {
                    if (userLogin.Nav_Department.DEPARTMENT_STATUS != 2)
                        depID = userLogin.DEPARTMENT_ID.Value;
                }

                if (depID != Guid.Empty)
                {
                    expression = expression.And(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID == depID);
                }
                PagedActionResult<T_CM_DRILL_PLAN_DETAIL> orderPageEntities = GetOrderPageEntities<T_CM_DRILL_PLAN_DETAIL>(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }
    }
}