using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.OG;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;


namespace APT.SC.WebApi.Controllers.Api.OG
{
    [Route("api/OG/OGRelatedEstimate")]
    public class OGRelatedEstimateController : AuthorizeApiController<T_OG_RELATED_ESTIMATE>
    {
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody]T_OG_RELATED_ESTIMATE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var Nav_Details = entity.Nav_Details;
                entity.Nav_Details = null;
                foreach(var item in Nav_Details)
                {
                    item.Nav_Item = null;
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_Details != null&&Nav_Details.Any())
                        BantchSaveEntityNoCommit(Nav_Details);

                });


                    return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_OG_RELATED_ESTIMATE> Get([FromBody] KeywordFilter filter)
        {
            if (filter.FilterGroup.Rules.Count > 0)
            {
                return WitEntity(null, filter);
            }
            return SafeExecute(() =>
            {
                var ret = new T_OG_RELATED_ESTIMATE {
                    ID = Guid.NewGuid(),
                    ORG_ID = filter.GetOrgId(),
                    Nav_Details = new List<T_OG_RELATED_ESTIMATE_DETAIL>(),
                };
                BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                baseFilter.Sort = "NAME";
                baseFilter.Order = DbOrder.ASC;
                var details = GetEntities<T_OG_RELATED_ESTIMATE_ITEM>(t=>t.IS_DELETED==false, baseFilter);
                var count = 1;
                details.ForEach(it =>
                {
                    ret.Nav_Details.Add(new T_OG_RELATED_ESTIMATE_DETAIL
                    {
                        ID = Guid.NewGuid(),
                        ESTIMATE_ID = ret.ID,
                        ITEM_ID = it.ID,
                        ORG_ID = filter.GetOrgId(),
                        Nav_Item = it,
                        NUM= count,
                    });
                    count++;
                });
                return ret;
            });
        }
    }
}
