using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System;
using NPOI.SS.Formula.Functions;
using APT.BaseData.Domain.Enums;
using APT.MS.Domain.Entities.BS;
using System.Linq.Expressions;

namespace APT.HM.WebApi.Controllers.Api
{
    /// <summary>
    ///  作业任务库
    /// </summary>
    [Route("api/HM/HMOperationLink")]
    public partial class OperationLinkController : AuthorizeApiController<T_HM_OPERATION_LINK>
    {
        /// <summary>
        /// 更新或新增数据
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_OPERATION_LINK entity)
        {
            return SafeExecute(() =>
            {
                var history = this.GetEntity<T_HM_OPERATION_LINK>(t => t.OPERATION_STEP_ID == entity.OPERATION_STEP_ID && t.ID != entity.ID, "Nav_OperationStep");
                if (history != null)
                    throw new Exception("已存在名为"+ history.Nav_OperationStep.NAME+"的数据,请修改作业名称");
                var details = entity.Nav_LinkPost;
                entity.Nav_OperationLinkEvaluateRisk = null;
                entity.Nav_LinkPost = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.OPERATION_LINK_ID = entity.ID;
                        t.Nav_Post = null;
                    });
                    var postName = details.Where(x => x.Nav_Post != null).Select(m => m.Nav_Post.NAME).Distinct().ToList();
                    entity.POST = string.Join(",", postName);
                }
                var safeConfirms = entity.Nav_SafeConfirms;
                entity.Nav_SafeConfirms = null;
                if (safeConfirms != null && safeConfirms.Any())
                {
                    safeConfirms.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.OPERATION_LINK_ID = entity.ID;
                    });
                }
                var safeMesasures = entity.Nav_SafeMeasures;
                entity.Nav_SafeMeasures = null;
                if (safeMesasures != null && safeMesasures.Any())
                {
                    safeMesasures.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.OPERATION_LINK_ID = entity.ID;
                    });
                }
                var safeDeal = entity.Nav_DealMeasures;
                entity.Nav_DealMeasures = null;
                if (safeDeal != null && safeDeal.Any())
                {
                    safeDeal.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.OPERATION_LINK_ID = entity.ID;
                    });
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (safeConfirms != null && safeConfirms.Any())
                        this.BantchSaveEntityNoCommit(safeConfirms);
                    if (safeMesasures != null && safeMesasures.Any())
                        this.BantchSaveEntityNoCommit(safeMesasures);
                    if (safeDeal != null && safeDeal.Any())
                        this.BantchSaveEntityNoCommit(safeDeal);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_HM_OPERATION_LINK> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
            var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
            if (string.IsNullOrEmpty(id))
                this.ThrowError("030017");
            var result = this.GetEntity<T_HM_OPERATION_LINK>(id, new string[] { "Nav_OperationStep", "Nav_WorkPermitType","Nav_LinkPost","Nav_LinkPost.Nav_Post",
                "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures", "Nav_Files" });
                 if (result.Nav_LinkPost != null && result.Nav_LinkPost.Any())
                 {
                     var postName = result.Nav_LinkPost.Where(t=>t.Nav_Post!=null).Select(m => m.Nav_Post.NAME).Distinct().ToList();
                     result.POST =  string.Join(",", postName);
                 }
                return result;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_HM_OPERATION_LINK> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            KeywordPageFilter keywordPageFilter = new KeywordPageFilter();
            keywordPageFilter = pageFilter;
            var rule = keywordPageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "POST");
            if (rule != null)
                keywordPageFilter.FilterGroup.Rules.Remove(rule);
            keywordPageFilter.IgnoreDataRule = true;
            //pageFilter.Include.Add("Nav_LinkPost");
            //pageFilter.Include.Add("Nav_LinkPost.Nav_Post");
            Expression<Func<T_HM_OPERATION_LINK, bool>> expression = e => !e.IS_DELETED;
            var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
            if (!string.IsNullOrEmpty(mineType))
            {
                var tempList = mineType.Split(",").ToList();
                expression = expression.And(t => tempList.Contains(t.MineType.ToString()));
            }
            var result = this.GetOrderPageEntities<T_HM_OPERATION_LINK>(expression, keywordPageFilter, null);
            if (result.TotalCount > 0)
            {
                result.Data.ForEach(t =>
                {
                    if (t.Nav_LinkPost != null && t.Nav_LinkPost.Any())
                    {
                        var postName = t.Nav_LinkPost.Where(x => x.Nav_Post != null).Select(m => m.Nav_Post.NAME).Distinct().ToList();
                        t.POST = string.Join(",", postName);
                    }
                });
                if (rule != null)
                {
                    result.Data = result.Data.Where(t =>t.POST!=null && t.POST.Contains(rule.Value.ToString()));
                }
            }
            return result;
        }
    }
}
