using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Entities.WB;
using APT.MS.Domain.Enums;
using APT.Utility;
using Castle.Core.Internal;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Differencing;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.WB
{
    [Route("api/WB/WBSafeCheckTask")]
    public class WBSafeCheckTaskController : AuthorizeApiController<T_WB_SAFE_CHECK_TASK>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public WBSafeCheckTaskController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_WB_SAFE_CHECK_TASK entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                var Nav_Details = entity.Nav_Details;
                entity.Nav_Details = null;
                var ListArea = entity.Nav_ListArea;
                entity.Nav_ListArea = null;
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    Random r = new Random();
                    entity.CODE = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10, 99);
                }
                List<T_WB_SAFE_CHECK_TASK_DETAIL_USER> users = new List<T_WB_SAFE_CHECK_TASK_DETAIL_USER>();
                var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                foreach (var detail in Nav_Details)
                {
                    if (detail.USER_ID == Guid.Empty)
                    {
                        throw new Exception("请选择记录人员!");
                    }
                    if (detail.Nav_Users != null)
                    {
                        detail.Nav_Users.ForEach(user =>
                        {
                            if (user.USER_ID == detail.USER_ID)
                            {
                                user.ROW_NUM = 0;
                            }
                            else
                            {
                                user.ROW_NUM = 999;
                            }
                        });
                        users.AddRange(detail.Nav_Users);
                        detail.Nav_Users = null;
                    }
                };
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (!entity.CHECK_TIME.HasValue)
                    {
                        throw new Exception("请选择检查时间!");
                    }
                    else if (entity.CHECK_TIME.Value <= DateTime.Now)
                    {
                        throw new Exception("检查时间必须大于当前时间!");
                    }

                    entity.STATUS = PFStandardStatus.Approving;
                    sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                    var lisUserID = users.Select(e => e.USER_ID).Distinct();
                    var listUser = GetEntities<T_FM_USER>(e => lisUserID.Contains(e.ID), null, null);
                    foreach (var user in listUser)
                    {
                        sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程安全检查任务表-确认", entity.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB029_SHOWPRINT"));
                    }

                    //操作人待办默认处理
                    if (lisUserID.Contains(LoginID.Value))
                    {
                        foreach (var item in sendNotices)
                        {
                            if (item.USER_ID == LoginID)
                            {
                                item.NOTICE_STATUS = 1;
                                item.TASK_DT = DateTime.Now;
                                break;
                            }
                        }
                        foreach (var item in users)
                        {
                            if (item.USER_ID == LoginID.Value)
                            {
                                item.MODIFY_TIME = DateTime.Now;
                                item.DEAL_STATUS = UserDealStatusEnum.已处理;
                            }
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                    }
                    entity.CREATER_ID = LoginID;//检查记录审批人
                }
                foreach (var item in ListArea)
                {
                    item.Nav_CheckArea = null;
                }
                foreach (var item in users)
                {
                    item.TASK_ID = entity.ID;
                }
                UnifiedCommit(() =>
                {
                    UpdateEntity(entity);
                    if (Nav_Details != null && Nav_Details.Any())
                        BantchSaveEntityNoCommit(Nav_Details);
                    if (ListArea != null && ListArea.Any())
                        BantchSaveEntityNoCommit(ListArea);
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);
                    if (sendNotices != null)
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("recordSign")]
        public JsonActionResult<bool> recordSign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var userID = Guid.Parse(filter.Parameter3);
                var orgId = filter.GetOrgId();
                var sendUserID = Guid.Empty;
                var sendUserNAME = "";
                var users = GetEntities<T_WB_SAFE_CHECK_TASK_DETAIL_USER>(t => t.Nav_Record.Nav_Parent.ID == id, new BaseFilter(orgId));
                //var currUser = users.FirstOrDefault(t => t.USER_ID == userID);
                var currUser = users.Where(t => t.USER_ID == userID);


                T_FM_NOTIFICATION_TASK finishTask = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                //currUser.DEAL_STATUS = UserDealStatusEnum.已处理;
                //currUser.MODIFY_TIME = DateTime.Now;
                foreach (var item in currUser)
                {
                    item.DEAL_STATUS = UserDealStatusEnum.已处理;
                    item.MODIFY_TIME = DateTime.Now;
                }

                T_WB_SAFE_CHECK_TASK model = null;
                var todoCount = users.Count(t => t.DEAL_STATUS == 0 && t.USER_ID != userID);
                if (todoCount == 0)
                {
                    model = GetEntity<T_WB_SAFE_CHECK_TASK>(id);
                    model.STATUS = PFStandardStatus.Reading;
                }
                if (taskID != Guid.Empty)
                {
                    finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);
                }
                UnifiedCommit(() =>
                {
                    if (model != null)
                        UpdateEntityNoCommit(model);
                    if (currUser != null && currUser.Any())
                        BantchSaveEntityNoCommit(currUser);
                    //UpdateEntityNoCommit(currUser);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);

                });
                return true;
            });
        }


        /// <summary>
        /// 搜索检查详情
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEntities")]
        public JsonActionResult<IEnumerable<T_WB_SAFE_CHECK_TASK_DETAIL>> GetEntities([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_WB_SAFE_CHECK_TASK_DETAIL>>(() =>
            {
                Guid ID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    try
                    {
                        ID = new Guid(filter.Keyword);
                    }
                    catch { }
                }
                Guid CHECK_TYPE_ID = Guid.Empty;
                List<Guid> listAreaID = new List<Guid>();
                //Guid CHECK_AREA_ID = Guid.Empty;
                string MineType = string.Empty;
                if (filter.FilterGroup.Rules.Any())
                {
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        if (item.Field == "Parameter1")
                        {
                            try
                            {
                                CHECK_TYPE_ID = new Guid(item.Value.ToString());
                            }
                            catch { CHECK_TYPE_ID = Guid.Empty; }
                        }
                        else if (item.Field == "Parameter2")
                        {
                            try
                            {
                                var listA = item.Value.ToString().Split(",", StringSplitOptions.RemoveEmptyEntries);
                                foreach (var itemA in listA)
                                {
                                    listAreaID.Add(new Guid(itemA));
                                }
                            }
                            catch { listAreaID = new List<Guid>(); }
                        }
                        else if (item.Field == "Parameter3")
                        {
                            MineType = item.Value.ToString();
                        }
                    }
                    filter.FilterGroup.Rules.Clear();
                }
                List<T_WB_SAFE_CHECK_TASK_DETAIL> listResult = new List<T_WB_SAFE_CHECK_TASK_DETAIL>();
                if (CHECK_TYPE_ID == Guid.Empty || listAreaID.Count < 1 || string.IsNullOrEmpty(MineType))
                {
                    return listResult;
                }
                Expression<Func<T_WB_CHECK_MAIN, bool>> expression = e => e.ENABLE_STATUS == BaseData.Domain.Enums.FMEnableStatusEnum.启用;
                var minetypeArry = MineType.Split('_', StringSplitOptions.RemoveEmptyEntries);
                List<FMProductionUnit> listMineType = new List<FMProductionUnit>();
                foreach (var item in minetypeArry)
                {
                    try
                    {
                        listMineType.Add((FMProductionUnit)int.Parse(item));
                    }
                    catch { }
                }
                expression = expression.And(e => CHECK_TYPE_ID == e.CHECK_TYPE_ID && e.CHECK_AREA_ID.HasValue && listAreaID.Contains(e.CHECK_AREA_ID.Value) && listMineType.Contains(e.MineType));
                var listMain = GetEntities(expression, filter, null).OrderBy(e => e.MineType).ThenBy(e => e.CHECK_AREA_ID).ToList();
                if (listMain == null || !listMain.Any() || listMain.Count() < 1)
                {
                    return listResult;
                }
                var listArea = GetEntities<T_WB_CHECK_AREA_ENUM>(e => !e.IS_DELETED, null, null);
                T_WB_CHECK_AREA_ENUM area = null;
                int ROW_NUM = 0;
                var CREATE_TIME = DateTime.Now;
                foreach (var item in listMain)
                {
                    area = listArea.FirstOrDefault(e => e.ID == item.CHECK_AREA_ID.Value);
                    if (area == null)
                    {
                        continue;
                    }
                    ROW_NUM++;
                    listResult.Add(new T_WB_SAFE_CHECK_TASK_DETAIL()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.OrgId,
                        MAIN_ID = item.ID,
                        Nav_Main = item,
                        PARENT_ID = ID,
                        ROW_NUM = ROW_NUM,
                        MineType = item.MineType,
                        AREA_ID = item.CHECK_AREA_ID.Value,
                        Nav_Area = area,
                        CHECK_CONTENT = item.CHECKCONTENT,
                        CHECK_BASIS = item.CHECKPROOF,
                        CREATE_TIME = CREATE_TIME
                    });
                }
                return listResult;
            });
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetInfo")]
        public JsonActionResult<T_WB_SAFE_CHECK_TASK> GetInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = GetEntity<T_WB_SAFE_CHECK_TASK>(null, filter, null);
                if (result != null && result.CHECK_TYPE_ID != Guid.Empty && !string.IsNullOrEmpty(result.MineType) && (!result.Nav_Details.Any() || result.Nav_Details.Count() < 1))
                {
                    //根据检查库 去填充信息
                    //T_WB_CHECK_MAIN
                    List<FMProductionUnit> listMineType = new List<FMProductionUnit>();
                    if (!string.IsNullOrEmpty(result.MineType))
                    {
                        var listMinetype = result.MineType.Split("_", StringSplitOptions.RemoveEmptyEntries);
                        foreach (var item in listMinetype)
                        {
                            listMineType.Add((FMProductionUnit)int.Parse(item));
                        }
                    }
                    //MineType
                    var listMain = GetEntities<T_WB_CHECK_MAIN>(e => !e.IS_DELETED && e.CHECK_TYPE_ID == result.CHECK_TYPE_ID && e.CHECK_AREA_ID.HasValue && listMineType.Contains(e.MineType), null, null).OrderBy(e => e.MineType).ThenBy(e => e.CHECK_AREA_ID);
                    var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    if (listMain != null && listMain.Any())
                    {
                        var listAreaID = listMain.Select(e => e.CHECK_AREA_ID.Value).Distinct();
                        var listArea = GetEntities<T_WB_CHECK_AREA_ENUM>(e => listAreaID.Contains(e.ID), null, null);
                        List<T_WB_SAFE_CHECK_TASK_AREA> ListArea = new List<T_WB_SAFE_CHECK_TASK_AREA>();
                        foreach (var item in listArea)
                        {
                            ListArea.Add(new T_WB_SAFE_CHECK_TASK_AREA()
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = result.ORG_ID,
                                CHECK_AREA_ID = item.ID,
                                CHECK_TASK_ID = result.ID,
                                Nav_CheckArea = item
                            });
                        }
                        result.Nav_ListArea = new List<T_WB_SAFE_CHECK_TASK_AREA>();
                        result.Nav_ListArea = ListArea;

                        List<T_WB_SAFE_CHECK_TASK_DETAIL> listDetails = new List<T_WB_SAFE_CHECK_TASK_DETAIL>();
                        int ROW_NUM = 0;
                        foreach (var item in listMain)
                        {
                            ROW_NUM++;
                            listDetails.Add(new T_WB_SAFE_CHECK_TASK_DETAIL()
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = result.ORG_ID,
                                PARENT_ID = result.ID,
                                ROW_NUM = ROW_NUM,
                                MAIN_ID = item.ID,
                                //USER_ID=
                                MineType = item.MineType,
                                AREA_ID = item.CHECK_AREA_ID.Value,
                                Nav_Area = listArea.First(e => e.ID == item.CHECK_AREA_ID.Value),
                                CHECK_CONTENT = item.CHECKCONTENT,
                                CHECK_BASIS = item.CHECKPROOF,
                                CREATER_ID = LoginID,
                                CREATE_TIME = DateTime.Now
                            });
                            result.Nav_Details = new List<T_WB_SAFE_CHECK_TASK_DETAIL>();
                            result.Nav_Details = listDetails;
                        }
                    }
                }
                return result;
            });
        }
    }
}
