using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
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/BSDepartmentAreaobject")]
    public partial class BSDepartmentAreaobjectController : AuthorizeApiController<T_BS_DEPARTMENT_AREAOBJECT>
    {
        IFMDepartmentService DepartmentService { get; set; }

        public BSDepartmentAreaobjectController(IFMDepartmentService departmentService)
        {
            DepartmentService = departmentService;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_DEPARTMENT_AREAOBJECT entity)
        {
            return SafeExecute<bool>(() =>
            {
                var check = GetEntity<T_BS_DEPARTMENT_AREAOBJECT>(e => e.DEPARTMENTID == entity.DEPARTMENTID && e.ID != entity.ID && !e.IS_DELETED);
                if (check != null)
                {
                    throw new Exception("该部门已经设置过所属范围，操作失败！");
                }

                List<T_BS_DEPARTMENT_AREAOBJECT> listResult = new List<T_BS_DEPARTMENT_AREAOBJECT>();
                List<T_BS_DEPARTMENT_AREAOBJECT> listResultAdd = new List<T_BS_DEPARTMENT_AREAOBJECT>();
                if (entity.ISDOWNSAME)//下级同步
                {
                    List<Guid> departmentIds = new List<Guid>() { entity.DEPARTMENTID };
                    DepartmentService.GetDepartmentIds(entity.ORG_ID.Value, new List<Guid>() { entity.DEPARTMENTID }, ref departmentIds);
                    departmentIds.Remove(entity.DEPARTMENTID);
                    if (departmentIds.Count > 0)
                    {
                        var listDepartmentObj = GetEntities<T_BS_DEPARTMENT_AREAOBJECT>(e => departmentIds.Contains(e.DEPARTMENTID), null, null);

                        foreach (var item in listDepartmentObj)
                        {
                            departmentIds.Remove(item.DEPARTMENTID);
                            if (item.CHECKOBJECT != entity.CHECKOBJECT)
                            {
                                //不一样 修改
                                item.CHECKOBJECT = entity.CHECKOBJECT;
                                listResult.Add(item);
                            }
                        }

                        //未设置 添加
                        if (departmentIds.Count > 0)
                        {
                            foreach (var item in departmentIds)
                            {
                                T_BS_DEPARTMENT_AREAOBJECT temp = new T_BS_DEPARTMENT_AREAOBJECT();
                                temp.ID = Guid.NewGuid();
                                temp.CHECKOBJECT = entity.CHECKOBJECT;
                                temp.DEPARTMENTID = item;
                                temp.IS_DELETED = false;
                                temp.ORG_ID = entity.ORG_ID;
                                //temp.ENTITY_ORG_TPYE = ;
                                //temp.FORM_ID = ;
                                //temp.FLOW_STATUS = ;
                                //temp.FLOW_SEND_STATUS = ;
                                //temp.FLOW_ID = ;
                                temp.CREATE_TIME = DateTime.Now;
                                temp.MODIFY_TIME = temp.CREATE_TIME;
                                temp.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                                temp.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                                listResultAdd.Add(temp);
                            }
                        }

                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (listResult.Any())
                        BantchUpdateEntityNoCommit(listResult);
                    if (listResultAdd.Any())
                        BantchAddEntityNoCommit(listResultAdd);
                });
                return true;
            });
        }


        /// <summary>
        /// 分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedObject")]
        public PagedActionResult<T_HM_RISK_AREA> OrderPagedObject([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_HM_RISK_AREA> result)
            {
                BSMineTypeEnum? CHECKOBJECT = null;
                if (pageFilter.FilterGroup.Groups != null && pageFilter.FilterGroup.Groups.Count > 0)
                {
                    //BS032 属性
                    List<FilterGroup> listGroup = pageFilter.FilterGroup.Groups.ToList();
                    var listRules = listGroup[0].Rules.ToList();
                    for (int i = listRules.Count - 1; i > -1; i--)
                    {
                        if (listRules[i].Field == "CHECKOBJECT")
                        {
                            CHECKOBJECT = (BSMineTypeEnum)int.Parse(listRules[i].Value.ToString());
                            listRules.Remove(listRules[i]);
                            listGroup[0].Rules = listRules;
                        }
                    }
                    pageFilter.FilterGroup.Groups = listGroup;
                }
                //else   
                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Count > 0 && CHECKOBJECT == null)//&& CHECKOBJECT == null  如果没有 CHECKOBJECT 再次 查找 
                {
                    //BS032 列表
                    List<FilterRule> listRules = pageFilter.FilterGroup.Rules.ToList();
                    for (int i = listRules.Count - 1; i > -1; i--)
                    {
                        if (listRules[i].Field == "CHECKOBJECT")
                        {
                            CHECKOBJECT = (BSMineTypeEnum)int.Parse(listRules[i].Value.ToString());
                            listRules.Remove(listRules[i]);
                        }
                    }
                    pageFilter.FilterGroup.Rules = listRules;
                }
                Expression<Func<T_HM_RISK_AREA, bool>> expression = e => e.ORG_ID == pageFilter.OrgId && !e.IS_DELETED;

                if (CHECKOBJECT == null || CHECKOBJECT == BSMineTypeEnum.All)
                {
                    //所有区域
                    PagedActionResult<T_HM_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_HM_RISK_AREA>(expression, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
                else
                {
                    var listAreOBJ = GetEntities<T_BS_DEPARTMENT_AREAOBJECT>(e => e.CHECKOBJECT == CHECKOBJECT.Value, null, null);
                    if (listAreOBJ != null && listAreOBJ.Any())
                    {
                        List<Guid> listDepID = listAreOBJ.Select(e => e.DEPARTMENTID).Distinct().ToList();
                        //T_HM_RISK_AREA 中的  DEPARTMENT_ID  有些有值 有些没值 所以暂时放开  比如 有些只有 选矿 就全部出来了
                        //expression = expression.And(e => e.DEPARTMENT_ID.HasValue && listDepID.Contains(e.DEPARTMENT_ID.Value));
                        expression = expression.And(e => !e.DEPARTMENT_ID.HasValue || (e.DEPARTMENT_ID.HasValue && listDepID.Contains(e.DEPARTMENT_ID.Value)));
                        PagedActionResult<T_HM_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_HM_RISK_AREA>(expression, pageFilter, null);
                        result.Data = orderPageEntities.Data;
                        result.TotalCount = orderPageEntities.TotalCount;
                    }
                    else
                    {
                        result.Data = new List<T_HM_RISK_AREA>();
                        result.TotalCount = 0;
                    }
                }
            });
        }

        /// <summary>
        /// 分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedObjectSub")]
        public PagedActionResult<T_HM_RISK_AREA> OrderPagedObjectSub([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_HM_RISK_AREA> result)
            {
                List<Guid> listAreaID = new List<Guid>();

                BSMineTypeEnum? CHECKOBJECT = null;
                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Count > 0)
                {
                    //BS032 列表
                    List<FilterRule> listRules = pageFilter.FilterGroup.Rules.ToList();
                    for (int i = listRules.Count - 1; i > -1; i--)
                    {
                        if (listRules[i].Field == "CHECKOBJECT")
                        {
                            CHECKOBJECT = (BSMineTypeEnum)int.Parse(listRules[i].Value.ToString());
                            listRules.Remove(listRules[i]);
                        }
                        else if (listRules[i].Field == "Nav_ListCheckRiskArea")
                        {
                            List<AreaSearch> listAreaSearch = JsonHelper.FromJson<List<AreaSearch>>(listRules[i].Value.ToString());
                            try
                            {
                                listAreaID = listAreaSearch.FindAll(e => !e.IS_DELETED.HasValue || !e.IS_DELETED.Value).Select(e => e.RISK_AREA_ID).Distinct().ToList();
                                listRules.Remove(listRules[i]);
                            }
                            catch
                            {

                            }
                        }
                    }
                    pageFilter.FilterGroup.Rules = listRules;
                }
                Expression<Func<T_HM_RISK_AREA, bool>> expression = e => e.ORG_ID == pageFilter.OrgId && !e.IS_DELETED;

                if (listAreaID.Count > 0)
                {
                    expression = expression.And(e => listAreaID.Contains(e.ID));
                    //所有区域
                    PagedActionResult<T_HM_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_HM_RISK_AREA>(expression, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
                else if (CHECKOBJECT == null || CHECKOBJECT == BSMineTypeEnum.All)
                {
                    //所有区域
                    PagedActionResult<T_HM_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_HM_RISK_AREA>(expression, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
                else
                {
                    var listAreOBJ = GetEntities<T_BS_DEPARTMENT_AREAOBJECT>(e => e.CHECKOBJECT == CHECKOBJECT.Value, null, null);
                    if (listAreOBJ != null && listAreOBJ.Any())
                    {
                        List<Guid> listDepID = listAreOBJ.Select(e => e.DEPARTMENTID).Distinct().ToList();
                        expression = expression.And(e => e.DEPARTMENT_ID.HasValue && listDepID.Contains(e.DEPARTMENT_ID.Value));
                        PagedActionResult<T_HM_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_HM_RISK_AREA>(expression, pageFilter, null);
                        result.Data = orderPageEntities.Data;
                        result.TotalCount = orderPageEntities.TotalCount;
                    }
                    else
                    {
                        result.Data = new List<T_HM_RISK_AREA>();
                        result.TotalCount = 0;
                    }
                }
            });
        }

    }

    public class AreaSearch
    {
        public Guid RISK_AREA_ID { get; set; }
        public Guid ID { get; set; }
        public Guid SAFE_CHECK_ID { get; set; }
        public Guid ORG_ID { get; set; }
        public bool? IS_DELETED { get; set; }

        //"Nav_RiskArea": {
        //  "NAME": "破碎车间-粗碎单元"
        //},

    }


}
