using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSCheckProjectCategory")]
    public partial class BSCheckProjectCategoryController : AuthorizeApiController<T_BS_CHECK_PROJECT_CATEGORY>
    {
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_CHECK_PROJECT_CATEGORY entity)
        {
            return SafeExecute<bool>(() =>
            {
                var listObj = entity.Nav_ListOBJECT;
                entity.Nav_ListOBJECT = null;

                if (listObj == null)
                {
                    var checkCategory = GetEntity<T_BS_CHECK_PROJECT_CATEGORY_OBJECT>(e => e.CHECKOBJECT == BSMineTypeEnum.Mine && e.PROJECT_CATEGORY_ID == entity.ID);
                    if (checkCategory == null)
                    {
                        listObj = new List<T_BS_CHECK_PROJECT_CATEGORY_OBJECT>();
                        listObj.Add(new T_BS_CHECK_PROJECT_CATEGORY_OBJECT()
                        {
                            ORG_ID = entity.ORG_ID,
                            CHECKOBJECT = BSMineTypeEnum.Mine,
                            PROJECT_CATEGORY_ID = entity.ID,
                        });
                    }
                }
                var listCategoryType = entity.Nav_ListCategoryType;
                entity.Nav_ListCategoryType = null;
                if (listCategoryType == null)
                {
                    throw new Exception("请完善检查类型！");
                }

                var check = GetEntity<T_BS_CHECK_PROJECT_CATEGORY>(e => e.ID != entity.ID && e.NAME == entity.NAME && !e.IS_DELETED);
                if (check != null && check.ID != Guid.Empty)
                {
                    throw new Exception("该名称已被使用！");
                }

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (listObj != null && listObj.Any())
                        BantchSaveEntityNoCommit(listObj);
                    if (listCategoryType.Any())
                        BantchSaveEntityNoCommit(listCategoryType);
                });
                return true;
            });
        }


        /// <summary>
        /// 排序分页查询数据检查任务制定
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedObjType")]
        public PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY> OrderPagedObjType([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY> result)
            {
                PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY> orderPageEntities = null;
                Guid CHECK_TYPE_ID = Guid.Empty;
                List<FilterRule> listRules = pageFilter.FilterGroup.Rules.ToList();

                if (pageFilter.FilterGroup.Rules.Count < 3 && pageFilter.FilterGroup.Rules.Count != 2) //&& pageFilter.FilterGroup.Rules.Count != 1 手动隐患上报 加的
                {
                    orderPageEntities = new PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY>();
                    foreach (var item in listRules)
                    {
                        if (item.Field == "Nav_ListCategoryType.CHECK_TYPE_ID")
                        {
                            try
                            {
                                CHECK_TYPE_ID = new Guid(item.Value.ToString());
                            }
                            catch { }
                        }
                        else if (item.Field == "RISK_SUBMIT_ID")
                        {
                            var sub = GetEntity<T_BS_RISK_SUBMIT>(new Guid(item.Value.ToString()));
                            if (sub != null && sub.CHECK_TYPE_ID.HasValue)
                                CHECK_TYPE_ID = sub.CHECK_TYPE_ID.Value;
                        }
                    }

                    if (CHECK_TYPE_ID != Guid.Empty)
                    {
                        var listCATEGORY = GetEntities<T_BS_CHECK_PROJECT_CATEGORY_CHECKTYPE>(e => e.CHECK_TYPE_ID == CHECK_TYPE_ID, null, "Nav_ProjectCategory").Select(e => e.Nav_ProjectCategory).Distinct();

                        if (listCATEGORY != null && listCATEGORY.Any())
                        {
                            orderPageEntities.Data = listCATEGORY.ToList();
                            orderPageEntities.TotalCount = orderPageEntities.Data.Count();
                        }
                    }
                }
                else
                {
                    BSMineTypeEnum? CHECKOBJECT = null;
                    List<Guid> listCategoryID = new List<Guid>();
                    foreach (var item in listRules)
                    {
                        if (item.Field == "Nav_ListCategoryType.CHECK_TYPE_ID")
                        {
                            CHECK_TYPE_ID = new Guid(item.Value.ToString());
                        }
                        else if (item.Field == "Nav_ListOBJECT.CHECKOBJECT")
                        {
                            CHECKOBJECT = (BSMineTypeEnum)(int.Parse(item.Value.ToString()));
                        }
                        else if (item.Field == "Nav_ListCheckProjectCategory")
                        {
                            List<BS032SubSelectProjectCategory> listAreaSearch = JsonHelper.FromJson<List<BS032SubSelectProjectCategory>>(item.Value.ToString());
                            try
                            {
                                listCategoryID = listAreaSearch.FindAll(e => !e.IS_DELETED.HasValue || !e.IS_DELETED.Value).Select(e => e.CHECK_PROJECT_CATEGORY_ID).Distinct().ToList();
                            }
                            catch
                            {
                            }
                        }
                        pageFilter.FilterGroup.Rules.Remove(item);
                    }

                    Expression<Func<T_BS_CHECK_PROJECT_CATEGORY, bool>> expression = e => !e.IS_DELETED;
                    if (listCategoryID.Count > 0)
                    {
                        expression = expression.And(e => listCategoryID.Contains(e.ID));
                    }
                    else
                    {
                        if (CHECK_TYPE_ID != Guid.Empty)
                        {
                            expression = expression.And(e => e.Nav_ListCategoryType != null && e.Nav_ListCategoryType.FirstOrDefault(c => c.CHECK_TYPE_ID == CHECK_TYPE_ID) != null);
                        }

                        if (CHECKOBJECT != null)
                        {
                            expression = expression.And(e => e.Nav_ListOBJECT != null && e.Nav_ListOBJECT.FirstOrDefault(t => t.CHECKOBJECT == CHECKOBJECT) != null);
                        }
                    }

                    orderPageEntities = GetOrderPageEntities<T_BS_CHECK_PROJECT_CATEGORY>(expression, pageFilter, null);
                }
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }
    }
    public class BS032SubSelectProjectCategory
    {

        public Guid CHECK_PROJECT_CATEGORY_ID { get; set; }
        public Guid ID { get; set; }
        public Guid SAFE_CHECK_ID { get; set; }
        public Guid ORG_ID { get; set; }
        public string NAME { get; set; }
        public bool? IS_DELETED { get; set; }
    }
}
