using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;

namespace APT.SC.WebApi.Controllers.Api.OG
{
    [Route("api/OG/OGStanardSysReview")]
    public class OGStanardizationSystemReviewController : AuthorizeApiController<T_OG_STANDARDIZATION_SYSTEM_REVIEW>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public OGStanardizationSystemReviewController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
		/// 获得单条实体数据
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("Get")]
        public JsonActionResult<T_OG_STANDARDIZATION_SYSTEM_REVIEW> Get([FromBody] KeywordFilter filter)
        {
            if (filter.FilterGroup.Rules.Count > 0)
            {
                return WitEntity(null, filter);
            }
            return SafeExecute(() =>
            {
                var ret = new T_OG_STANDARDIZATION_SYSTEM_REVIEW
                {
                    ID = Guid.NewGuid(),
                    ORG_ID = filter.OrgId,
                    Nav_ReviewItemsList = new List<T_OG_STANDARDIZATION_REVIEW_ITEMS_REL>(),
                    Nav_ReviewUserList = new List<T_OG_STANDARDIZATION_PERSON_REL>(),
                    Nav_ReviewResultList = new List<T_OG_STANDARDIZATION_REVIEW_RESULT_REL>(),
                    Nav_ActionPlanList = new List<T_OG_STANDARDIZATION_ACTION_PLAN_REL>(),
                };
                GetEntities<T_OG_STANDARDIZATION_REVIEW_ITEM_ENUM>(null, new BaseFilter(filter.GetOrgId())).ForEach(t =>
                {
                    ret.Nav_ReviewItemsList.Add(new T_OG_STANDARDIZATION_REVIEW_ITEMS_REL
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.OrgId,
                        REVIEW_ID = ret.ID,
                        ITEM_ID = t.ID,
                        Nav_Item = t,
                    });
                });
                GetEntities<T_OG_STANDARDIZATION_REVIEW_RESULT_ENUM>(null, new BaseFilter(filter.GetOrgId())).ForEach(t =>
                {
                    ret.Nav_ReviewResultList.Add(new T_OG_STANDARDIZATION_REVIEW_RESULT_REL
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.OrgId,
                        REVIEW_ID = ret.ID,
                        RESULT_ID = t.ID,
                        Nav_Result = t,
                    });
                });
                GetEntities<T_OG_STANDARDIZATION_ACTION_PLAN_ENUM>(null, new BaseFilter(filter.GetOrgId())).ForEach(t =>
                {
                    ret.Nav_ActionPlanList.Add(new T_OG_STANDARDIZATION_ACTION_PLAN_REL
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.OrgId,
                        REVIEW_ID = ret.ID,
                        PLAN_ID = t.ID,
                        Nav_Plan = t,
                    });
                });
                return ret;
            });
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_OG_STANDARDIZATION_SYSTEM_REVIEW entity)
        {
            return SafeExecute(() =>
            {
                if (entity.USER_ID == null || entity.USER_ID == Guid.Empty)
                {
                    entity.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                }
                var Nav_ReviewItemsList = entity.Nav_ReviewItemsList;
                var Nav_ReviewUserList = entity.Nav_ReviewUserList;
                var Nav_ReviewResultList = entity.Nav_ReviewResultList;
                var Nav_ActionPlanList = entity.Nav_ActionPlanList;
                Nav_ReviewItemsList.ForEach((item) =>
                {
                    item.Nav_Item = null;
                });
                Nav_ReviewUserList.ForEach((item) =>
                {
                    item.REVIEW_ID = entity.ID;
                    item.ORG_ID = entity.ORG_ID;
                    item.Nav_User = null;
                });
                Nav_ReviewResultList.ForEach((item) =>
                {
                    item.Nav_Result = null;
                });
                Nav_ActionPlanList.ForEach((item) =>
                {
                    item.Nav_Plan = null;
                });
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.STATUS != (int)PFStandardStatus.Draft)
                    {
                        throw new Exception("您已提交过此数据，不可重复提交，请更新页面后重试");
                    }
                    entity.STATUS = PFStandardStatus.Sign;
                    var allSendUserTitles = new List<string>();
                    var allSendDataIds = new List<Guid>();
                    var allSendUserIds = new List<Guid>();
                    var allSendUserNames = new List<string>();
                    var userids = Nav_ActionPlanList.Select(t => t.USER_ID.Value).Distinct().ToList();
                    var userNames = GetEntities<T_FM_USER>(t => userids.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                    foreach (var userid in userids)
                    {
                        allSendUserTitles.Add("标准化系统评审意见");
                        allSendDataIds.Add(entity.ID);
                        allSendUserIds.Add(userid);
                        allSendUserNames.Add(userNames.FirstOrDefault(t => t.ID == userid).NAME);
                    }
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, entity.ORG_ID.Value, allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), 1, "OG034_REPORT");
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetEntityTask(entity.TaskID);
                        if (task.SOURCE_DATA_ID == null)
                            task.SOURCE_DATA_ID = entity.ID;
                    }
                }
                entity.Nav_ReviewItemsList = null;
                entity.Nav_ReviewUserList = null;
                entity.Nav_ReviewResultList = null;
                entity.Nav_ActionPlanList = null;
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_ReviewItemsList != null)
                        BantchSaveEntityNoCommit(Nav_ReviewItemsList);
                    if (Nav_ReviewUserList != null)
                        BantchSaveEntityNoCommit(Nav_ReviewUserList);
                    if (Nav_ReviewResultList != null)
                        BantchSaveEntityNoCommit(Nav_ReviewResultList);
                    if (Nav_ActionPlanList != null)
                        BantchSaveEntityNoCommit(Nav_ActionPlanList);
                    if (sendNotices != null)
                        BantchAddEntityNoCommit(sendNotices);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                });

                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SubmitUser")]
        public JsonActionResult<bool> SubmitUser([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var finishNotice = NotificationTaskService.GetTaskFinishModel(Guid.Parse(filter.Parameter3));
                var ids = ((string)filter.Parameter1).Split(',');
                var flags = ((string)filter.Parameter2).Split(',');
                if (ids == null || ids.Count() == 0)
                {
                    return true;
                }
                var models = GetEntities<T_OG_STANDARDIZATION_ACTION_PLAN_REL>(t => t.REVIEW_ID == Guid.Parse(filter.Parameter4) && t.IMPLEMENTATION == OGStandardizationImplementation.未填写, new BaseFilter(filter.GetOrgId()));
                if (models == null)
                {
                    throw new Exception("已提交无法修该数据!");
                }
                for (var x = 0; x < ids.Count(); x++)
                {
                    int status = flags[x] == "1" ? (int)OGStandardizationImplementation.已执行 : (int)OGStandardizationImplementation.未执行;
                    Guid id = new Guid(ids[x]);
                    var actionplan = models.FirstOrDefault(t => t.ID == id);
                    if (actionplan == null)
                    {
                        throw new Exception("你已提交或无权限修改!");
                    }
                    actionplan.IMPLEMENTATION = (OGStandardizationImplementation)status;
                }
                var count = models.Where(t => t.IMPLEMENTATION == OGStandardizationImplementation.未填写).Count();
                T_OG_STANDARDIZATION_SYSTEM_REVIEW entity = null;
                if (count == 0)
                {
                    entity = GetEntity<T_OG_STANDARDIZATION_SYSTEM_REVIEW>(t => t.ID == Guid.Parse(filter.Parameter4) && t.STATUS == PFStandardStatus.Sign);
                    entity.STATUS = PFStandardStatus.Archived;
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (models != null && models.Any())
                        BantchSaveEntityNoCommit(models);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
    }
}
