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.AE;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.CM;
using APT.MS.Domain.Entities.TI;
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/CMEquipmentDemandSurvey")]
    public class CMEquipmentDemandSurveyController : AuthorizeApiController<T_CM_EQUIPMENT_DEMAND_SURVEY>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IAEAccidentEventReportService AccidentEventReportService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMEquipmentDemandSurveyController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IAEAccidentEventReportService accidentEventReportService, IFMNotificationTaskService notificationTaskService, IFMUserService userService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            AccidentEventReportService = accidentEventReportService;
            NotificationTaskService = notificationTaskService;
            UserService = userService;
        }

        /// <summary>
        /// 应急装备需求调查表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_CM_EQUIPMENT_DEMAND_SURVEY entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.USER_ID.HasValue && entity.USER_ID.Value != APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                {
                    throw new Exception("您没有权限操作此表单！");
                }
                if (entity.END_TIME == DateTime.MinValue)
                {
                    throw new Exception("请选择截止时间！");
                }
                if (entity.START_TIME > entity.END_TIME)
                {
                    throw new Exception("截止时间不能小于发起时间！请联系管理员查看配置的准确性：统管理 > 应急管理配置 > 自动触发日期配置  【应急装备需求调查结束日期】要大于【应急装备需求调查触发日期】");
                }
                if (entity.Nav_ListDetail == null || !entity.Nav_ListDetail.Any())
                {
                    throw new Exception("应急装备需求明细不能为空！");
                }
                T_FM_NOTIFICATION_TASK taskEnd = null;
                if (entity.STATUS == PFStandardStatus.Sign)
                {
                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "CM030_SHOWPRINT");
                    }
                    int RowIndex = 1;
                    foreach (var item in entity.Nav_ListDetail)
                    {
                        if (item.TYPE_ID == Guid.Empty)
                        {
                            throw new Exception("类型不能为空【行：" + RowIndex + "】！");
                        }
                        if (string.IsNullOrEmpty(item.MATERIAL_NAME))
                        {
                            throw new Exception("装备名称不能为空【行：" + RowIndex + "】！");
                        }
                        if (!item.AVAILABLE_COUNT.HasValue)
                        {
                            throw new Exception("请填写库内现有数量【行：" + RowIndex + "】！");
                        }
                        if (item.NEED_COUNT == 0)
                        {
                            throw new Exception("需求数量不能为空【行：" + RowIndex + "】！");
                        }
                        RowIndex++;
                    }


                    RowIndex = 1;
                    T_CM_EQUIPMENT_DEMAND_SURVEY_DETAIL check = null;
                    foreach (var item in entity.Nav_ListDetail)
                    {
                        check = entity.Nav_ListDetail.FirstOrDefault(e => e.TYPE_ID == item.TYPE_ID && e.LIBRARY_ID == item.LIBRARY_ID && e.ID != item.ID && !e.IS_DELETED);
                        if (check != null)
                        {
                            throw new Exception("【装备明细】装备名称不能重复【行：" + RowIndex + "】！");
                        }
                        RowIndex++;
                    }
                }

                var Files = entity.Nav_Files;
                entity.Nav_Files = null;
                var ListDetail = entity.Nav_ListDetail;
                entity.Nav_ListDetail = null;

                #region    如果是最后一个提交的 给安环部 
                T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER modelSurveyMaster = null;
                List<T_CM_EQUIPMENT_DEMAND_SURVEY_DETAIL> listSurveyDetail = null;
                T_FM_NOTIFICATION_TASK taskSurveyMaster = null;
                DateTime dtNow = DateTime.Now;
                if (entity.STATUS == PFStandardStatus.Sign && dtNow <= entity.END_TIME)
                {
                    var listSurveyCheck = GetEntities<T_CM_EQUIPMENT_DEMAND_SURVEY>(e => e.YEAR == dtNow.Year && !e.IS_DELETED && e.ID != entity.ID, null, null);
                    if (listSurveyCheck != null && listSurveyCheck.Any())
                    {
                        var check = listSurveyCheck.FirstOrDefault(e => e.STATUS == PFStandardStatus.Draft);
                        if (check == null)
                        {
                            var SurveyMaster = GetEntity<T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER>(e => e.YEAR == dtNow.Year && !e.IS_DELETED);
                            if (SurveyMaster != null)
                            {
                                DateTime dtYearStart = Convert.ToDateTime(DateTime.Now.Year + "-01-01 00:00:00");
                                var listDetailCheck = GetEntities<T_CM_EQUIPMENT_DEMAND_SURVEY_DETAIL>(e => !e.IS_DELETED && e.CREATE_TIME >= dtYearStart && !e.SURVEY_MASTER_ID.HasValue, null, null);
                                if (listDetailCheck != null && listDetailCheck.Any() && listDetailCheck.Count() > 0)
                                {
                                    //增强健壮性
                                    SurveyMaster = null;
                                }
                            }
                            if (SurveyMaster == null)
                            {
                                string Msg = string.Empty;
                                T_FM_USER userSafeMaster = null;
                                var configDate = GetEntity<T_CM_CONFIG>(e => e.ORG_ID == entity.ORG_ID);
                                if (configDate != null && configDate.DEPARTMENT_ID.HasValue && configDate.DEPARTMENT_ID.Value != Guid.Empty && configDate.POST_ID.HasValue && configDate.POST_ID.Value != Guid.Empty)
                                {
                                    var listUser = UserService.GetDepPostUser(ref Msg, configDate.DEPARTMENT_ID.Value, configDate.POST_ID.Value, true);
                                    if (listUser != null && listUser.Any())
                                        userSafeMaster = listUser[0];
                                }
                                if (userSafeMaster == null)
                                    userSafeMaster = UserService.GetRoleUser(ref Msg, "安环部负责人", null, null);
                                if (userSafeMaster != null)
                                {
                                    modelSurveyMaster = new T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER();
                                    modelSurveyMaster.ID = Guid.NewGuid();
                                    modelSurveyMaster.START_TIME = dtNow;
                                    modelSurveyMaster.END_TIME = dtNow.AddDays(1);
                                    modelSurveyMaster.USER_ID = userSafeMaster.ID;
                                    modelSurveyMaster.YEAR = dtNow.Year;
                                    modelSurveyMaster.STATUS = PFStandardStatus.Draft;
                                    modelSurveyMaster.IS_DELETED = false;
                                    modelSurveyMaster.ORG_ID = entity.ORG_ID;
                                    //modelSurveyMaster.ENTITY_ORG_TPYE = ;
                                    //modelSurveyMaster.FORM_ID = ;
                                    //modelSurveyMaster.FLOW_STATUS = ;
                                    //modelSurveyMaster.FLOW_SEND_STATUS = ;
                                    //modelSurveyMaster.FLOW_ID = ;
                                    modelSurveyMaster.CREATE_TIME = dtNow;
                                    modelSurveyMaster.MODIFY_TIME = dtNow;
                                    //modelSurveyMaster.CREATER_ID = ;
                                    //modelSurveyMaster.MODIFIER_ID = ;

                                    var listSurvey = GetEntities<T_CM_EQUIPMENT_DEMAND_SURVEY>(e => e.YEAR == dtNow.Year && e.STATUS == PFStandardStatus.Sign && !e.IS_DELETED, null, "Nav_ListDetail");
                                    if (listSurvey != null && listSurvey.Any())
                                    {
                                        listSurveyDetail = new List<T_CM_EQUIPMENT_DEMAND_SURVEY_DETAIL>();
                                        foreach (var item in listSurvey)
                                        {
                                            listSurveyDetail.AddRange(item.Nav_ListDetail);
                                        }
                                        foreach (var item in listSurveyDetail)
                                        {
                                            item.SURVEY_MASTER_ID = modelSurveyMaster.ID;
                                        }

                                        //本次操作的数据 修改
                                        foreach (var item in ListDetail)
                                        {
                                            item.SURVEY_MASTER_ID = modelSurveyMaster.ID;
                                        }
                                    }

                                    taskSurveyMaster = NotificationTaskService.InsertUserNoticeTaskModel("应急装备需求评估", modelSurveyMaster.ID, modelSurveyMaster.ORG_ID, modelSurveyMaster.USER_ID.Value, userSafeMaster.NAME, dtNow, dtNow.AddDays(1), 0, "CM032");
                                }
                            }
                        }
                    }
                }
                #endregion

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (Files != null && Files.Any())
                        BantchSaveEntityNoCommit(Files);
                    if (ListDetail != null && ListDetail.Any())
                        BantchSaveEntityNoCommit(ListDetail);
                    if (taskEnd != null)
                        UpdateEntityNoCommit(taskEnd);
                    if (modelSurveyMaster != null)//安环负责人评估
                        UpdateEntityNoCommit(modelSurveyMaster);
                    if (taskSurveyMaster != null)
                        UpdateEntityNoCommit(taskSurveyMaster);
                    if (listSurveyDetail != null && listSurveyDetail.Any())
                        BantchSaveEntityNoCommit(listSurveyDetail);
                });
                return true;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetOrder")]
        public JsonActionResult<T_CM_EQUIPMENT_DEMAND_SURVEY> GetOrder([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var SurveyMaster = GetEntity<T_CM_EQUIPMENT_DEMAND_SURVEY>(null, filter, null);
                if (SurveyMaster.Nav_ListDetail != null && SurveyMaster.Nav_ListDetail.Any())
                {
                    SurveyMaster.Nav_ListDetail = SurveyMaster.Nav_ListDetail.OrderBy(e => e.TYPE_ID).ThenBy(e => e.MATERIAL_NAME).ToList();
                }
                return SurveyMaster;
            });
        }

        /// <summary>
        /// 评估人员签到
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Sign")]
        public JsonActionResult<bool> Sign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                ////评估人员签到，所有评估人员签到后触发审批
                Guid ID = new Guid(filter.Keyword);
                var survey = GetEntity<T_CM_EQUIPMENT_DEMAND_SURVEY>(e => e.ID == ID);
                survey.STATUS = PFStandardStatus.Approving;

                Guid taskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                    taskID = new Guid(filter.Parameter1);

                //给自己发送今日提醒

                T_FM_NOTIFICATION_TASK taskRead = NotificationTaskService.InsertUserNoticeTaskModel("请跟踪应急装备采买过程，购买后通知库管员处理“物资库存更新”待办", ID, survey.ORG_ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserName, DateTime.Now, DateTime.Now.AddDays(1), 2, "");

                //结束 待办
                T_FM_NOTIFICATION_TASK task = NotificationTaskService.GetEntityTask(taskID);
                this.UnifiedCommit(() =>
                {
                    if (survey != null)
                        UpdateEntityNoCommit(survey);
                    if (task != null)//代办消息 清除
                        UpdateEntityNoCommit(task);
                    if (taskRead != null)//今日提醒
                        UpdateEntityNoCommit(taskRead);
                });
                return true;
            });
        }

    }
}