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.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/CMEquipmentDemandSurveyMaster")]
    public class CMEquipmentDemandSurveyMasterController : AuthorizeApiController<T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMEquipmentDemandSurveyMasterController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService,  IFMNotificationTaskService notificationTaskService, IFMUserService userService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificationTaskService = notificationTaskService;
            UserService = userService;
        }

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


        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER entity)
        {
            return SafeExecute<bool>(() =>
            {
                var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.USER_ID.HasValue && entity.USER_ID.Value != LoginID)
                {
                    throw new Exception("您没有权限操作此表单！");
                }

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

                T_FM_NOTIFICATION_TASK taskEnd = null;

                List<T_FM_NOTIFICATION_TASK> listTaskRed = null;//待办 阅
                //List<T_FM_NOTIFICATION_TASK> listTaskDay = null;//今日提醒  跟踪设备采买过程，购买后更新“应急物资库"
                List<T_CM_EQUIPMENT_DEMAND_SURVEY> listSurvey = null;
                List<T_FM_NOTIFICATION_TASK> listTaskLib = null;//物资管理员 待办
                List<T_FM_NOTIFICATION_TASK> listTaskLibPer = null;//物资管理员 待办

                if (entity.STATUS == PFStandardStatus.Sign)
                {
                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "CM032_SHOWPRINT");
                    }
                    int RowIndex = 1;
                    foreach (var item in ListDetail)
                    {
                        if (item.NEED_COUNT == 0)
                        {
                            throw new Exception("需求数量不能为空【行：" + RowIndex + "】！");
                        }
                        RowIndex++;
                    }

                    //安环部负责人待办事项收到应急装备需求评估表，对需求数量进行编辑，编辑完成后点击通知，触发一个待办事项和一个今日提醒给需求部门安全员
                    //待办事项：需求部门安全员待办事项收到应急装备需求评估表打印界面，点击已阅
                    //今日提醒：需求部门安全员收到今日提醒，消息类型：其他，信息内容：跟踪设备采买过程，购买后更新“应急物资库"的信息
                    var listSurveyID = ListDetail.Select(e => e.DEMAND_SURVEY_ID).Distinct();

                    listSurvey = GetEntities<T_CM_EQUIPMENT_DEMAND_SURVEY>(e => listSurveyID.Contains(e.ID), null, "Nav_User").ToList();
                    List<string> Title = new List<string>();
                    //List<string> TitleRed = new List<string>();
                    List<string> userName = new List<string>();
                    List<Guid> UserId = new List<Guid>();
                    List<Guid> DataId = new List<Guid>();
                    foreach (var item in listSurvey)
                    {
                        Title.Add("应急装备需求确认");
                        //TitleRed.Add("跟踪应急装备采买过程，购买后更新“应急物资库”的信息");
                        userName.Add(item.Nav_User.NAME);
                        UserId.Add(item.USER_ID.Value);
                        DataId.Add(item.ID);
                        item.STATUS = PFStandardStatus.Archived;
                    }

                    listTaskRed = NotificationTaskService.InsertUserNoticeTaskModels(Title, DataId, entity.ORG_ID, UserId, userName, DateTime.Now, DateTime.Now.AddDays(1), 1, "CM030_SHOWPRINT");


                    #region    应急物资对应管理人 收到管理物品对应的确认

                    var listThingId = ListDetail.Select(e => e.LIBRARY_ID).Distinct();
                    var listThings = GetEntities<T_CM_MATERIAL_LIBRARY>(e => listThingId.Contains(e.ID), null, "Nav_User");
                    List<Guid> listUserID = new List<Guid>();
                    List<string> listUserName = new List<string>();

                    foreach (var item in listThings)
                    {
                        if (!listUserID.Contains(item.USER_ID))
                        {
                            listUserID.Add(item.USER_ID);
                            listUserName.Add(item.Nav_User.NAME);
                        }
                    }

                    listTaskLib = NotificationTaskService.InsertUserNoticeTaskModels("应急物资数量需求通知", entity.ID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, 0, "CM031_SHOWPRINT", FMTASKTYPE.CM_LIBRARY_MANAGE_CHECK);//默认确认先不做    FMNoticeTypeEnum.消息

                    if (LoginID.HasValue && listUserID.Contains(LoginID.Value))
                    {
                        listTaskLibPer = new List<T_FM_NOTIFICATION_TASK>();
                        List<Guid> listThingTaskId = new List<Guid>();
                        foreach (var item in listTaskLib)
                        {
                            if (item.USER_ID == LoginID)
                            {
                                item.NOTICE_STATUS = 1;
                                item.TASK_DT = DateTime.Now;
                                listThingTaskId = listThings.Where(e => e.USER_ID == LoginID).Select(e => e.ID).Distinct().ToList();

                                listTaskLibPer.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("物资库存更新", listThingTaskId, item.ORG_ID, item.USER_ID, item.USER_NAME, DateTime.Now, 0, "CM028", FMTASKTYPE.CM_LIBRARY_CHANGECOUNT));
                                break;
                            }
                        }
                    }

                    #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 (listTaskDay != null && listTaskDay.Any())
                    //    BantchSaveEntityNoCommit(listTaskDay);
                    if (listTaskRed != null && listTaskRed.Any())
                        BantchSaveEntityNoCommit(listTaskRed);
                    if (listSurvey != null && listSurvey.Any())//保存并发送变成已归档
                        BantchSaveEntityNoCommit(listSurvey);
                    if (listTaskLib != null && listTaskLib.Any())//物资管理员 收到待办
                        BantchSaveEntityNoCommit(listTaskLib);
                    if (listTaskLibPer != null && listTaskLibPer.Any())//物资管理员（为登陆者） 收到物资库存修改待办
                        BantchSaveEntityNoCommit(listTaskLibPer);
                });
                return true;
            });
        }


        /// <summary>
        /// 获取装备需求汇总中某个物资管理员的物资信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetManageOrder")]
        public JsonActionResult<T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER> GetManageOrder([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var SurveyMaster = GetEntity<T_CM_EQUIPMENT_DEMAND_SURVEY_MASTER>(null, filter, null);
                var detail = GetEntities<T_CM_EQUIPMENT_DEMAND_SURVEY_DETAIL>(e => e.SURVEY_MASTER_ID == SurveyMaster.ID && e.Nav_MaterialLibrary.USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID, null, "Nav_EQDSurvey.Nav_Department", "Nav_MaterialType").OrderBy(e => e.TYPE_ID).ToList();
                SurveyMaster.Nav_ListDetail = detail;
                return SurveyMaster;
            });
        }


        /// <summary>
        /// 物资库管理员确认 
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Check")]
        public JsonActionResult<bool> Check([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    task = NotificationTaskService.GetEntityTask(new Guid(filter.Parameter1));
                }
                var Keyword = filter.Parameter2;
                var LoginId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                List<Guid> listIDS = new List<Guid>();
                List<Guid> listThingTaskId = null;
                List<T_FM_NOTIFICATION_TASK> listTask = null;
                if (!string.IsNullOrEmpty(Keyword))
                {
                    List<string> listID = Keyword.Split('_', StringSplitOptions.RemoveEmptyEntries).ToList();
                    listID.ForEach(e => { listIDS.Add(new Guid(e)); });
                }

                #region    验证

                if (listIDS.Count > 0)
                {
                    var listLibs = GetEntities<T_CM_MATERIAL_LIBRARY>(e => e.USER_ID == LoginId && listIDS.Contains(e.ID), null, null);
                    listThingTaskId = listLibs.Select(e => e.ID).ToList();
                }

                #endregion

                if (listThingTaskId != null && listThingTaskId.Any())
                {
                    listTask = NotificationTaskService.InsertUserNoticeTaskModels("物资库存更新", listThingTaskId, filter.OrgId, LoginId.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserName, DateTime.Now, 0, "CM028", FMTASKTYPE.CM_LIBRARY_CHANGECOUNT);
                }

                this.UnifiedCommit(() =>
                {
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (listTask != null && listTask.Any())//新待办
                        BantchSaveEntityNoCommit(listTask);
                });
                return true;
            });
        }
    }
}