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.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.Record;
using NPOI.HSSF.Record.Chart;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SEThreeLevelSafeTrainRecord")]
    public class SEThreeLevelTrainRecordController : AuthorizeApiController<T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SEThreeLevelTrainRecordController(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_TRAIN_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_FM_USER current_user = GetEntity<T_FM_USER>((Guid)currUser);
                if (entity.USER_ID == null || entity.USER_ID == Guid.Empty)
                {
                    entity.USER_ID = currUser;
                }
                if (entity.DEPARTMENT_ID == null || entity.DEPARTMENT_ID == Guid.Empty)
                {
                    entity.DEPARTMENT_ID = current_user.DEPARTMENT_ID;
                }
                T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD next_train_record = null;
                T_FM_NOTIFICATION_TASK sendNotice1 = null;
                T_FM_NOTIFICATION_TASK sendNotice2 = null;

                T_FM_NOTIFICATION_TASK finishNotice = null;
                var Nav_TrainRecordFile = entity.Nav_TrainRecordFile;
                var Nav_TrainSignatureFile = entity.Nav_TrainSignatureFile;
                T_SE_THREE_LEVEL_SAFE_EDU_CARD eduCard = GetEntity<T_SE_THREE_LEVEL_SAFE_EDU_CARD>(entity.EDU_CARD_ID, new string[] { "Nav_User" });
                List<T_FM_DEPARTMENT> allDepartment = GetEntities<T_FM_DEPARTMENT>(null, new BaseFilter(entity.ORG_ID)).ToList();
                T_FM_DEPARTMENT nextTrainDep = null;
                T_FM_USER nextTrainUser = null;
                var trainUser = GetEntity<T_FM_USER>(t=>t.ID == eduCard.USER_ID && t.ENABLE_STATUS==0,new string[] { "Nav_Person" });
                if (trainUser != null)
                {
                    eduCard.ID_CARD_NUMBER = trainUser.ID_CARD;
                    eduCard.IN_TIME = trainUser.ENTRYTIME;
                    eduCard.DEPARTMENT_ID = trainUser.DEPARTMENT_ID;
                    eduCard.POST_ID = trainUser.Nav_Person.POST_ID;
                }
                T_FM_DEPARTMENT trainee_department = GetEntity<T_FM_DEPARTMENT>(t => t.ID == eduCard.DEPARTMENT_ID);

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.TRAINNING_TIME == "0" || string.IsNullOrEmpty(entity.TRAINNING_TIME))
                    {
                        throw new Exception("学时不能为0!");
                    }
                    if (entity.START_TIME < eduCard.IN_TIME || entity.END_TIME < eduCard.IN_TIME)
                    {
                        throw new Exception("培训时间不能早于入职时间!");
                    }
                    if (eduCard.STATUS == SEThreeLevelSafeTrainStatus.公司培训)//通知部门级安全员
                    {
                        if (trainee_department.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
                        {
                            nextTrainDep = allDepartment.Where(t => t.ID == trainee_department.PARENT_ID.Value).FirstOrDefault(); //车间级
                            if (nextTrainDep.DEPARTMENT_TYPE == (int)FMDepartmentType.车间)
                            {
                                nextTrainDep = allDepartment.Where(t => t.ID == nextTrainDep.PARENT_ID.Value).FirstOrDefault(); //
                                nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "部门安全员" && t.DEPARTMENT_ID == nextTrainDep.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                                if (nextTrainUser == null)
                                {
                                    nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "车间安全员" && t.DEPARTMENT_ID == trainee_department.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                                    if (nextTrainUser == null)
                                    {
                                        nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "车间安全员" && t.DEPARTMENT_ID == trainee_department.PARENT_ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                                    }
                                }
                            }
                        }
                        else if (trainee_department.DEPARTMENT_TYPE == (int)FMDepartmentType.车间)
                        {
                            nextTrainDep = allDepartment.Where(t => t.ID == trainee_department.PARENT_ID.Value).FirstOrDefault();
                            nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "部门安全员" && t.DEPARTMENT_ID == nextTrainDep.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                            if (nextTrainUser == null)
                            {
                                nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "车间安全员" && t.DEPARTMENT_ID == trainee_department.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                            }
                        }
                        else if (trainee_department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
                        {
                            nextTrainDep = allDepartment.Where(t => t.ID == trainee_department.ID).FirstOrDefault();
                            nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "部门安全员" && t.DEPARTMENT_ID == nextTrainDep.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                            if (nextTrainUser == null)
                            {
                                nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "车间安全员" && t.DEPARTMENT_ID == trainee_department.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                            }
                        }
                    }
                    var final_step = false;
                    if (eduCard.STATUS == SEThreeLevelSafeTrainStatus.部门培训)
                    {
                        nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "班组负责人" && t.DEPARTMENT_ID == trainee_department.ID && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
                        if (nextTrainUser == null)
                        {
                            final_step = true;
                        }
                    }
                    if (eduCard.STATUS == SEThreeLevelSafeTrainStatus.班组培训)
                    {
                        final_step = true;
                    }
                    var tempStatus = eduCard.STATUS;
                    eduCard.STATUS += 1;
                    if (final_step || nextTrainUser == null)
                    {
                        eduCard.STATUS = SEThreeLevelSafeTrainStatus.员工签到;
                        sendNotice2 = NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + eduCard.Nav_User.NAME + "-" + (eduCard.STATUS - 1).GetDescription() + "签到", entity.ID, entity.ORG_ID, (Guid)eduCard.USER_ID, eduCard.Nav_User.NAME, DateTime.Now, eduCard.IN_TIME.Value.AddMonths(1), 1, "SE015_SHOWPRINT");
                    }
                    else
                    {
                        var train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == (SEThreeLevelSafeTrainType)eduCard.STATUS);
                        if (train_contents == null)
                        {
                            throw new Exception("请配置三级安全教育培训内容!");
                        }
                        next_train_record = new T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD
                        {
                            ID = Guid.NewGuid(),
                            EDU_CARD_ID = eduCard.ID,
                            ORG_ID = eduCard.ORG_ID,
                            CONTENT_ID = train_contents.ID,
                            THREE_LEVEL_SAFE_TRAIN_TYPE = (SEThreeLevelSafeTrainType)eduCard.STATUS,
                        };
                        sendNotice1 = NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + eduCard.Nav_User.NAME + "-" + eduCard.STATUS.GetDescription(), next_train_record.ID, entity.ORG_ID, nextTrainUser.ID, nextTrainUser.NAME, DateTime.Now, eduCard.IN_TIME.Value.AddMonths(1), 1, "SE042");
                        sendNotice2 = NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + eduCard.Nav_User.NAME + "-" + tempStatus.GetDescription() + "签到", entity.ID, entity.ORG_ID, (Guid)eduCard.USER_ID, eduCard.Nav_User.NAME, DateTime.Now, eduCard.IN_TIME.Value.AddMonths(1), 1, "SE015_SHOWPRINT");
                    }
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE015_SHOWPRINT");
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_TrainRecordFile != null && Nav_TrainRecordFile.Any())
                        BantchSaveEntityNoCommit(Nav_TrainRecordFile);
                    if (Nav_TrainSignatureFile != null && Nav_TrainSignatureFile.Any())
                        BantchSaveEntityNoCommit(Nav_TrainSignatureFile);
                    if (next_train_record != null)
                        AddEntityNoCommit(next_train_record);
                    if (eduCard != null)
                        UpdateEntityNoCommit(eduCard);
                    if (sendNotice1 != null)
                        AddEntityNoCommit(sendNotice1);
                    if (sendNotice2 != null)
                        AddEntityNoCommit(sendNotice2);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });




                return true;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                T_SE_THREE_LEVEL_SAFE_EDU_CARD eduCard = null;
                T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD eduRecord = null;

                finishNotice = NotificationTaskService.GetTaskFinishModel(Guid.Parse(filter.Parameter2));
                eduRecord = GetEntity<T_SE_THREE_LEVEL_SAFE_TRAIN_RECORD>(filter.Parameter1, new string[] { "Nav_User" });
                eduRecord.STATUS = SEThreeLevelSafeTrainRecordStatus.归档;
                eduCard = GetEntity<T_SE_THREE_LEVEL_SAFE_EDU_CARD>(eduRecord.EDU_CARD_ID, new string[] { "Nav_User", "Nav_TrainRecordList" });
                var count = eduCard.Nav_TrainRecordList.Count(t => t.STATUS == SEThreeLevelSafeTrainRecordStatus.草稿);
                if (count == 0)
                {
                    T_FM_USER nextTrainUser = null;
                    nextTrainUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人", new string[] { "Nav_Department" });
                    eduCard.STATUS = SEThreeLevelSafeTrainStatus.审阅中;
                    sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + eduCard.Nav_User.NAME + "-审核", eduCard.ID, eduCard.ORG_ID, nextTrainUser.ID, nextTrainUser.NAME, DateTime.Now, DateTime.Now.AddHours(12), 1, "SE015_SHOWPRINT");
                }


                UnifiedCommit(() =>
                {

                    if (eduCard != null)
                        UpdateEntityNoCommit(eduCard);
                    if (eduRecord != null)
                        UpdateEntityNoCommit(eduRecord);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (sendNotice != null)
                        UpdateEntityNoCommit(sendNotice);
                });
                return true;
            });
        }
    }
}
