using System;
using APT.BaseData.Domain.Entities;
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;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SETrainingEffectEvaluationSurvey")]
    public class SETrainingEffectEvaluationSurveyController : AuthorizeApiController<T_SE_TRAINING_EFFECT_EVALUATION_SURVEY>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SETrainingEffectEvaluationSurveyController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TRAINING_EFFECT_EVALUATION_SURVEY entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (DateTime.Now > entity.END_TIME)
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE021_SHOWPRINT");
                    if (finishNotice != null)
                        UpdateEntity(finishNotice);
                    throw new Exception("调查时间已到，待办关闭！");
                }
                if (entity.STATUS != SETrainningEffectSurveyStatus.草稿)
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE021_SHOWPRINT");
                    if (finishNotice != null)
                        UpdateEntity(finishNotice);
                    throw new Exception("调查已完成，不可重复提交");
                }
                var Nav_ResultList = entity.Nav_ResultList;
                entity.Nav_ResultList = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                { 
                    entity.STATUS = SETrainningEffectSurveyStatus.归档;
                    if (Nav_ResultList == null)
                    {
                        throw new Exception("培训效果评估调查表结果不可为空");
                    }
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE021_SHOWPRINT");
                }
                UnifiedCommit(() =>
                  {
                      UpdateEntityNoCommit(entity);
                      if (Nav_ResultList != null)
                          BantchSaveEntityNoCommit(Nav_ResultList);
                      if (finishNotice != null)
                          UpdateEntityNoCommit(finishNotice);
                  });
                return true;
            });
        }
    }
}
