using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Enums;
using APT.Utility;
using log4net.Filter;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    ///  技术交底表
    /// </summary>
    [Route("api/FO/FOTechDisclosureFromTech")]
    public partial class TechDisclosureFromTechController : AuthorizeApiController<T_FO_TECH_DISCLOSURE_FROM_TECH>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public TechDisclosureFromTechController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_TECH_DISCLOSURE_FROM_TECH> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var entity = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM_TECH>(id, "Nav_OperationStep", "Nav_User.Nav_UserSignFiles.Nav_ImgFile", "Nav_Department", "Nav_Files.Nav_ImgFile");
                if (entity != null)
                {
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "TECH_DISCLOSURE_FROM_ID", "USER_ID", "Nav_User.NAME", "Nav_User.CODE", "Nav_User.FILE_PATH", "Nav_User.Nav_UserSignFiles.Nav_ImgFile" };
                    var persons = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM_TECH_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, newFilter).ToList();
                    entity.Nav_Person = persons.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
                }
                return entity;
            });
        }
        /// <summary>
        /// 新增修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_TECH_DISCLOSURE_FROM_TECH entity)
        {
            return SafeExecute<bool>(() =>
            {
                entity.FORM_STATUS = (int)FOTeamActivityState.草稿;
                var persons = entity.Nav_Person;
                var deleteIds = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM_TECH_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m=>m.ID).ToList();
                if (persons != null && persons.Any())
                {
                    persons = persons.Where(t => !t.IS_DELETED && t.USER_ID != null).ToList();
                }
                entity.Nav_Person = null;
                var files = entity.Nav_Files;
                var deleteFileIds = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM_TECH_FILE>(t => t.TECH_DISCLOSURE_FROM_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                if (files != null && files.Any())
                {
                    files = files.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Files = null;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var departmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                entity.DEPARTMENT_ID = departmentId;
                if (string.IsNullOrEmpty(entity.DisclosureContent))
                {
                    throw new Exception("交底内容必需填写");
                }
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    entity.CODE = "JSJD" + DateTime.Now.ToShortDateString().Replace("/", "") + new Random().Next(1, 999);
                }
                entity.DisclosureContent = entity.DisclosureContent.Trim().Replace(" ", "");
                if (persons != null && persons.Any())
                {
                    persons.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.TECH_DISCLOSURE_FROM_ID = entity.ID;
                        t.Nav_User = null;
                    });
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.DISCLOSURE_DATE == null || entity.DISCLOSURE_DATE == DateTime.Parse("0001-01-01 00:00:00"))
                        throw new Exception("交底时间必需填写");
                  
                        entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                        persons.ForEach(t =>
                        {
                            if (t.USER_ID == loginUserId)
                                t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                        });
                        //新增的消息通知
                        var userIds = persons.Where(m => m.USER_ID != null && m.USER_ID != loginUserId).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                        if (userIds != null && userIds.Any())
                        {
                            var UserNames = new List<string>();
                            var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                            foreach (var u in userIds)
                            {
                                var current = user.FirstOrDefault(t => t.ID == u);
                                UserNames.Add(current?.NAME);
                            }
                            //发消息
                            DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("技术交底表确认"+DateTime.Now.Month.ToString().PadLeft(2,'0') + DateTime.Now.Day.ToString().PadLeft(2, '0'), entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                            dtEnd, (int)FMNoticeTypeEnum.消息, "FO035_SHOWPRINT");
                        }
                        else
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                        }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "FO035_SHOWPRINT";
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (deleteIds != null && deleteIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_TECH_DISCLOSURE_FROM_TECH_PERSON>(deleteIds);
                    if (deleteFileIds != null && deleteFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_TECH_DISCLOSURE_FROM_TECH_FILE>(deleteFileIds);
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (persons != null && persons.Any())
                        this.BantchSaveEntityNoCommit(persons);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 签到同意
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_TECH_DISCLOSURE_FROM_TECH entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userID = currTask.USER_ID;
                    }
                }
                var tech = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM_TECH>(entity.ID);
                var user = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM_TECH_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == tech.ID && t.USER_ID == userID, new BaseFilter(orgId));
                user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                var todoCount = this.GetCount<T_FO_TECH_DISCLOSURE_FROM_TECH_PERSON>(t => t.TECH_DISCLOSURE_FROM_ID == tech.ID && t.DEAL_STATUS == 0 && t.USER_ID != null && t.USER_ID != userID, new BaseFilter(orgId));
                if (todoCount == 0 || todoCount == 1)
                {
                    tech.FORM_STATUS = (int)FOTeamActivityState.已归档;
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO035_SHOWPRINT";
                }
                this.UnifiedCommit(() =>
                {
                    if (tech != null)
                        UpdateEntityNoCommit(tech);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
    }
}
