using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Metadata;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.Record;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SEThreeLevelSafeEduCard")]
    public class SEThreeLevelEduCardController : AuthorizeApiController<T_SE_THREE_LEVEL_SAFE_EDU_CARD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SEThreeLevelEduCardController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_THREE_LEVEL_SAFE_EDU_CARD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (string.IsNullOrEmpty(entity.ID_CARD_NUMBER))
                {
                    throw new Exception("身份证号码不可为空");
                }
                if (entity.ID_CARD_NUMBER.Length < 18)
                {
                    throw new Exception("身份证号码不足18位");
                }
                if (entity.LAUNCH_DEPARTMENT_ID == null || entity.LAUNCH_DEPARTMENT_ID == Guid.Empty)
                {
                    T_FM_USER current_user = GetEntity<T_FM_USER>(t => t.ID == currUser);
                    entity.LAUNCH_DEPARTMENT_ID = current_user.DEPARTMENT_ID;
                }
                if (entity.LAUNCH_USER_ID == null || entity.LAUNCH_USER_ID == Guid.Empty)
                {
                    entity.LAUNCH_USER_ID = currUser;
                }
                if (entity.LAUNCH_TIME == null)
                {
                    entity.LAUNCH_TIME = DateTime.Now;
                }
                var threeLevelUser = GetEntity<T_FM_USER>(entity.USER_ID.Value, new string[] { "Nav_Person" });
                entity.DEPARTMENT_ID = threeLevelUser.DEPARTMENT_ID;
                entity.POST_ID = threeLevelUser.Nav_Person.POST_ID;
                T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD next_train_record = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {

                    if (entity.STATUS != SEThreeLevelSafeTrainStatus.草稿)
                    {
                        throw new Exception("已发送过通知!");
                    }
                    var safeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS==0, new string[] { "Nav_Department", "Nav_ApproveRole" });
                    next_train_record = new T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD
                    {
                        ID = Guid.NewGuid(),
                        EDU_CARD_ID = entity.ID,
                        ORG_ID = entity.ORG_ID,
                        THREE_LEVEL_SAFE_TRAIN_TYPE = SEThreeLevelSafeTrainType.公司级
                    };
                    entity.STATUS += 1;
                    next_train_record.THREE_LEVEL_SAFE_TRAIN_TYPE = (SEThreeLevelSafeTrainType)entity.STATUS.GetInt();
                    var train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == (SEThreeLevelSafeTrainType)entity.STATUS.GetInt());
                    next_train_record.CONTENT_ID = train_contents.ID;
                    if (safeUser == null)
                    {
                        throw new Exception("未找到公司安环部安全员");
                    }
                    sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + threeLevelUser.NAME + "-" + entity.STATUS.GetDescription(), next_train_record.ID, entity.ORG_ID, safeUser.ID, safeUser.NAME, DateTime.Now, entity.IN_TIME.Value.AddMonths(1), 1, "SE042");
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (next_train_record != null)
                        AddEntityNoCommit(next_train_record);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                });
                return true;
            });

        }

        /// <summary>
        /// 审阅
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Approve")]
        public JsonActionResult<bool> Approve([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var finishId = new Guid(filter.Parameter2);
                T_SE_THREE_LEVEL_SAFE_EDU_CARD record = GetEntity<T_SE_THREE_LEVEL_SAFE_EDU_CARD>(filter.Parameter1);
                if (record.STATUS != SEThreeLevelSafeTrainStatus.审阅中)
                {
                    throw new Exception("当前状态无法审阅!");
                }
                record.STATUS = SEThreeLevelSafeTrainStatus.归档;
                var finishNotice = NotificationTaskService.GetTaskFinishModel(finishId);
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(record);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_SE_THREE_LEVEL_SAFE_EDU_CARD> Get([FromBody] KeywordFilter filter)
        {
            var result = WitEntity(null, filter);
            if(result.Data==null)
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                var educardId = GetEntity<T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD>(id).EDU_CARD_ID;
                filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value= educardId;
                result = WitEntity(null, filter);
            }
            return result;
        }
    }
}
