using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using APT.Utility;
using System.Linq.Expressions;
using System;

namespace APT.FM.WebApi.Controllers.Api.FM
{
    [Route("api/FM/Organization")]
    public class OrganizationController : AuthorizeTreeApiController<T_FM_ORGANIZATION>
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_FM_ORGANIZATION>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_FM_ORGANIZATION>> OrderEntities([FromBody] KeywordFilter filter)
        {
            return WitOrderEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("NWOrderEntities")]
        public JsonActionResult<IEnumerable<T_FM_ORGANIZATION>> NWOrderEntities([FromBody] KeywordFilter filter)
        {
            //filter.FilterGroup.Rules.Add(new FilterRule() { Field = "ID", Operate = FilterOperate.Equal, Value = filter.OrgId });
            var orgId = filter.OrgId;
            filter.OrgId = null;
            filter.IgnoreOrgRule = true;
            Expression<Func<T_FM_ORGANIZATION, bool>> expression = t => true;
            var parentRule = filter.FilterGroup.Rules.FirstOrDefault(i => i.Field == "PARENT_ID");
            if (parentRule != null && string.IsNullOrEmpty(parentRule.Value.ToString()))
            {
                expression = expression.And(i => i.ID == orgId);
            }
            return WitOrderEntities(expression, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_FM_ORGANIZATION> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FM_ORGANIZATION> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return WitRealDelete(id);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("NWDelete")]
        public JsonActionResult<bool> NWDelete(string ids)
        {

            var isRootOrg = this.GetEntities<T_FM_ORGANIZATION>(x => x.ID == new Guid(ids), new BaseFilter()).FirstOrDefault();
            if (isRootOrg == null)
            {
                return SafeExecute<bool>(() =>
                {
                    return true;
                });
            }
            else
            {
                if (isRootOrg.PARENT_ID == null)               
                    return new JsonActionResult<bool>() { IsSuccessful = false, ErrorMessage = "根企业不允许删除！" };               
                else
                    return new JsonActionResult<bool>() { IsSuccessful = false, ErrorMessage = "已创建企业建议启用状态改为禁用！" };
            }
            //if (isRootOrg.PARENT_ID == null)
            //{
            //    return new JsonActionResult<bool>() { IsSuccessful = false, ErrorMessage = "根企业不允许删除！" };
            //}
            //else
            //{
            //    return WitRealDelete(ids);
            //}
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_FM_ORGANIZATION entity)
        {
            return SafeExecute<bool>(() =>
            {
                this.TreeUpdateEntity(entity);
                var extConnConfigService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IFMOrganizationService>();
                extConnConfigService.SetOrgCache();
                return true;
            });
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("NWUpdate")]
        public JsonActionResult<bool> NWUpdate([FromBody] T_FM_ORGANIZATION entity)
        {
            if (entity.PARENT_ID == null)
            {
                var org = this.GetEntities<T_FM_ORGANIZATION>(x => x.ID == entity.ID, new BaseFilter());
                if (org.Any())
                {
                    return new JsonActionResult<bool>() { IsSuccessful = false, ErrorMessage = "该企业信息无法修改！" };
                }
                else
                    return new JsonActionResult<bool>() { IsSuccessful = false, ErrorMessage = "无法新增与根企业同级子企业！" };
            }
            else
            {
                return SafeExecute<bool>(() =>
                {
                    this.TreeUpdateEntity(entity);
                    var extConnConfigService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IFMOrganizationService>();
                    extConnConfigService.SetOrgCache();
                    return true;
                });
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult<bool> BatchDelete(string ids)
        {
            return WitRealBatchDelete(ids);
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_FM_ORGANIZATION> Get([FromBody] KeywordFilter filter)
        {
            filter.OrgId = null;
            filter.IgnoreOrgRule = true;
            return WitEntity(null, filter);
        }
    }
}
