using APT.BaseData.Domain.Entities.FM;
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 APT.BaseData.Domain.Entities;
using APT.MS.Domain.Entities.HM;

namespace APT.SC.WebApi.Controllers.Api.OG
{
    [Route("api/OG/OGEmployeeOpinionCollection")]
    public class OGEmployeeOpinionCollectionController : AuthorizeApiController<T_OG_EMPLOYEE_OPINION_COLLECTION>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public OGEmployeeOpinionCollectionController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_OG_EMPLOYEE_OPINION_COLLECTION entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.STATUS != (int)OGEmployeeOpinionStatus.草稿 && entity.STATUS != OGEmployeeOpinionStatus.汇总中)
                {
                    throw new Exception("当前数据不可提交!");
                }
                if (entity.START_TIME == null)
                {
                    entity.START_TIME = DateTime.Now;
                }
                if (entity.END_TIME == null)
                {
                    throw new Exception("请选择结束时间");
                }
                if (entity.STATUS == OGEmployeeOpinionStatus.草稿)
                {
                    if (entity.END_TIME < entity.START_TIME)
                    {
                        throw new Exception("征集结束时间不可早于征集开始时间");
                    }
                }

                if (entity.USER_ID == null)
                {
                    if (entity.STATUS == OGEmployeeOpinionStatus.草稿)
                    {
                        entity.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    }
                }
                if (entity.DEPARTMENT_ID == null)
                {
                    if (entity.STATUS == OGEmployeeOpinionStatus.草稿)
                    {
                        entity.DEPARTMENT_ID = GetEntity<T_FM_USER>(t => t.ID == entity.USER_ID).DEPARTMENT_ID;
                    }
                }
                if (entity.AH_CHARGE_USER_ID == null)
                {
                    if (entity.STATUS == OGEmployeeOpinionStatus.草稿)
                    {
                        entity.AH_CHARGE_USER_ID = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人").ID;
                    }
                }
                var Nav_Users = entity.Nav_Users.Where(t => t.USER_ID != Guid.Empty);
                List<T_OG_EMPLOYEE_OPINION> opinions = new List<T_OG_EMPLOYEE_OPINION>();
                List<T_OG_EMPLOYEE_OPINION_COLLECTION_USER_FILE> files = new List<T_OG_EMPLOYEE_OPINION_COLLECTION_USER_FILE>();
                foreach (var detail in Nav_Users)
                {

                    if (detail.Nav_Opinions != null)
                    {
                        foreach (var opinion in detail.Nav_Opinions)
                        {
                            if (opinion.RESULT == OGOpinionResultEnum.不认可)
                            {
                                if (string.IsNullOrEmpty(opinion.REFUSE_DESCRIPTION))
                                {
                                    throw new Exception("不认可的请填写不认可解释!");
                                }
                            }
                        }

                        opinions.AddRange(detail.Nav_Opinions);
                        detail.Nav_Opinions = null;
                    }
                    if (detail.Nav_Files != null)
                    {
                        files.AddRange(detail.Nav_Files);
                        detail.Nav_Files = null;
                    }
                };
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var allUsers = GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID));
                    if (entity.STATUS == (int)OGEmployeeOpinionStatus.草稿)
                    {
                        entity.STATUS = OGEmployeeOpinionStatus.意见征集中;
                        var allSendUserTitles = new List<string>();
                        var allSendDataIds = new List<Guid>();
                        var allSendUserIds = new List<Guid>();
                        var allSendUserNames = new List<string>();
                        Nav_Users.ForEach(u =>
                        {
                            allSendUserTitles.Add("员工意见征集-意见反馈");
                            allSendDataIds.Add(u.ID);
                            allSendUserIds.Add(u.USER_ID);
                            allSendUserNames.Add(allUsers.FirstOrDefault(t => t.ID == u.USER_ID).NAME);
                        });
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, entity.ORG_ID, allSendUserIds, allSendUserNames, DateTime.Now, entity.END_TIME.Value, 1, "OG059_EDIT");
                    }
                    else if (entity.STATUS == OGEmployeeOpinionStatus.汇总中)
                    {
                        entity.STATUS = OGEmployeeOpinionStatus.负责人审阅中;
                        sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("员工意见征集-负责人审阅", entity.ID, entity.ORG_ID, entity.CHARGE_USER_ID.Value, allUsers.FirstOrDefault(t => t.ID == entity.CHARGE_USER_ID).NAME, DateTime.Now, DateTime.Now.AddDays(3), 1, "OG059_CHECK");
                    };
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.GetEntityTask(entity.TaskID, "OG059_SHOWPRINT");//wyw
                        if (!finishNotice.SOURCE_DATA_ID.HasValue)
                        {
                            finishNotice.SOURCE_DATA_ID = entity.ID;
                        }
                        //{
                        //    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID,entity.ID, "OG059_SHOWPRINT");
                        //}
                    }
                }
                entity.Nav_Users = null;
                UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(entity);
                if (Nav_Users != null && Nav_Users.Any())
                    BantchSaveEntityNoCommit(Nav_Users);
                if (sendNotices != null && sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
                if (sendNotice != null)
                    UpdateEntityNoCommit(sendNotice);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice);
                if (opinions != null && opinions.Any())
                    BantchSaveEntityNoCommit(opinions);
                if (files != null && files.Any())
                    BantchSaveEntityNoCommit(files);

            });
                return true;
            });
        }
        /// <summary>
        /// 同意
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Agree")]
        public JsonActionResult<bool> Agree([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = new Guid(filter.Keyword);
                var taskId = Guid.Parse(filter.Parameter1);
                var data = GetEntity<T_OG_EMPLOYEE_OPINION_COLLECTION>(id);
                if (data == null)
                {
                    throw new Exception("未查到相应数据");
                }
                T_FM_NOTIFICATION_TASK sendNotice = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;

                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (taskId != null && taskId != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == taskId);
                    if (currTask != null)
                    {
                        userID = currTask.USER_ID;
                    }
                }
                if (data.STATUS == OGEmployeeOpinionStatus.负责人审阅中)
                {
                    if (userID != data.CHARGE_USER_ID)
                    {
                        throw new Exception("你无权限做此操作");
                    }
                    data.STATUS = OGEmployeeOpinionStatus.安环部审阅中;
                    sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("员工意见征集-安环部审阅", data.ID, data.ORG_ID.Value, data.AH_CHARGE_USER_ID.Value, "", DateTime.Now, DateTime.Now.AddDays(3), 1, "OG059_CHECK");

                }
                else if (data.STATUS == OGEmployeeOpinionStatus.安环部审阅中)
                {
                    if (userID != data.AH_CHARGE_USER_ID)
                    {
                        throw new Exception("你无权限做此操作");
                    }
                    data.STATUS = OGEmployeeOpinionStatus.归档;
                }
                else
                {
                    throw new Exception("状态有误");
                }
                if (filter.Parameter1 != null)
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(taskId);
                }
                UnifiedCommit(() =>
                {
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    UpdateEntityNoCommit(data);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }

        /// <summary>
        /// 用户提交
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateUser")]
        public JsonActionResult<bool> FullUpdateUser([FromBody] T_OG_EMPLOYEE_OPINION_COLLECTION_USER entity)
        {
            return SafeExecute<bool>(() =>
            {
                var exist = GetEntity<T_OG_EMPLOYEE_OPINION_COLLECTION_USER>(t => t.ID == entity.ID, new BaseFilter(entity.ORG_ID),
                    new string[] { "Nav_Collection" });
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (exist == null)
                {
                    throw new Exception("未查到有效数据");
                }
                if (exist.STATUS != (int)OGEmployeeOpinionFeedbackStatus.未反馈 || exist.Nav_Collection.STATUS != OGEmployeeOpinionStatus.意见征集中)
                {
                    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "OG059_USERVIEW");
                    UpdateEntity(finishNotice);
                    throw new Exception("您已提交或当前征集已结束");
                }
                if (exist.Nav_Collection.END_TIME != null && exist.Nav_Collection.END_TIME < DateTime.Now)
                {
                    throw new Exception("征集截止时间已过，不可提交");
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = OGEmployeeOpinionFeedbackStatus.已反馈;
                    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "OG059_USERVIEW");
                }
                var Nav_Files = entity.Nav_Files;
                var Nav_Opinions = entity.Nav_Opinions;
                entity.Nav_Files = null;
                entity.Nav_Opinions = null;
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);
                    if (Nav_Opinions != null && Nav_Opinions.Any())
                        BantchSaveEntityNoCommit(Nav_Opinions);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });

                return true;
            });
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUser")]
        public JsonActionResult<T_OG_EMPLOYEE_OPINION_COLLECTION_USER> GetUser([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                return GetEntity<T_OG_EMPLOYEE_OPINION_COLLECTION_USER>(null, filter);
            });
        }
    }
}
