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/BSCheckQuestion")]
    public partial class BSCheckQuestionController : AuthorizeApiController<T_BS_CHECK_QUESTION>
    {

        /// <summary>
        /// 安全检查 安检员  问题描述 选择 数据源  
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckDetailDESCREPTION")]
        public PagedActionResult<T_BS_CHECK_QUESTION> GetCheckDetailDESCREPTION([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_QUESTION>((result) =>
            {

                //如果没有 检查库 看看 检查内容 做匹配

                List<Guid> listID = new List<Guid>();
                listID.Add(new Guid("55555555-5555-5555-5555-555555555555"));
                //listID.Add(new Guid("77777777-7777-7777-7777-777777777777"));//去除其他
                var listQues2 = GetEntities<T_BS_CHECK_QUESTION>(e => listID.Contains(e.ID), null, null);

                if (pageFilter.FilterGroup.Groups.Count > 0)
                {
                    List<FilterGroup> listGroups = pageFilter.FilterGroup.Groups.ToList();
                    var rules = listGroups[0].Rules;
                    var rulesSearch = listGroups.Count > 1 ? listGroups[1].Rules : null;

                    Guid RISK_AREA_ID = Guid.Empty;
                    Guid CHECK_PROJECT_ID = Guid.Empty;
                    Guid CHECK_PROJECT_CATEGORY_ID = Guid.Empty;
                    Guid CHECK_TYPE_LEVEL_ID = Guid.Empty;
                    Guid SAFE_CHECK_ID = Guid.Empty;
                    Guid DEPARTMENT_ID = Guid.Empty;
                    string CHECKCONTENT = string.Empty;
                    string CHECKCONTENTSearch = string.Empty;
                    BSMineTypeEnum? CHECKOBJECT = null;
                    try
                    {
                        foreach (var rule in rules)
                        {
                            switch (rule.Field)
                            {
                                case "RISK_AREA_ID":
                                    RISK_AREA_ID = new Guid(rule.Value.ToString());
                                    break;
                                case "CHECK_PROJECT_ID":
                                    CHECK_PROJECT_ID = new Guid(rule.Value.ToString());
                                    break;
                                case "CHECK_PROJECT_CATEGORY_ID":
                                    CHECK_PROJECT_CATEGORY_ID = new Guid(rule.Value.ToString());
                                    break;
                                case "CHECKCONTENT":
                                    CHECKCONTENT = rule.Value.ToString();
                                    break;
                                case "CHECK_TYPE_LEVEL_ID":
                                    CHECK_TYPE_LEVEL_ID = new Guid(rule.Value.ToString());
                                    break;
                                case "SAFE_CHECK_ID":
                                    SAFE_CHECK_ID = new Guid(rule.Value.ToString());
                                    break;
                                case "DEPARTMENT_ID":
                                    DEPARTMENT_ID = new Guid(rule.Value.ToString());
                                    break;
                                case "CHECKOBJECT":
                                    CHECKOBJECT = (BSMineTypeEnum)int.Parse(rule.Value.ToString());
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    catch { }

                    if (CHECK_TYPE_LEVEL_ID == Guid.Empty && SAFE_CHECK_ID != Guid.Empty)
                    {
                        CHECK_TYPE_LEVEL_ID = GetEntity<T_BS_SAFE_CHECK>(SAFE_CHECK_ID).CHECK_TYPE_LEVEL_ID.Value;
                    }

                    if (rulesSearch != null && rulesSearch.Any())
                    {
                        CHECKCONTENTSearch = rulesSearch.ToList()[0].Value.ToString();
                    }

                    //wyw1114 expression && e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == DEPARTMENT_ID
                    Expression<Func<T_BS_CHECK_MAIN, bool>> expression = e => e.RISK_AREA_ID == RISK_AREA_ID && e.CHECK_TYPE_LEVEL_ID == CHECK_TYPE_LEVEL_ID && e.CHECK_PROJECT_ID == CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == CHECKCONTENT && !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.CHECK_QUESTION_ID.HasValue;

                    if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                    {
                        expression = expression.And(e => e.Nav_CheckQuestion != null && e.Nav_CheckQuestion.DESCREPTION.Contains(CHECKCONTENTSearch));
                    }

                    //var listQuesSearch = GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckQuestion" }).Select(e => e.Nav_CheckQuestion).Distinct();
                    var listQuesSearch = GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckQuestion" }).Select(e => e.Nav_CheckQuestion).Distinct();

                    if (listQuesSearch != null && listQuesSearch.Any())
                    {
                        //if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                        //{
                        //    listQuesSearch = listQuesSearch.Where(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));
                        //}

                        //检查问题
                        var listMainSearch = GetEntities<T_BS_CHECK_MAIN>(expression, null, null).Distinct();

                        List<T_BS_CHECK_QUESTION> listQuesResult = new List<T_BS_CHECK_QUESTION>();
                        if (listQues2 != null && listQues2.Any())
                        {
                            listQuesResult = listQues2.ToList();
                            if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                            {
                                listQuesResult = listQuesResult.FindAll(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));
                            }

                            foreach (var item in listQuesSearch)
                            {
                                item.Nav_Main = listMainSearch.FirstOrDefault(e => e.CHECK_QUESTION_ID == item.ID);
                            }

                            listQuesResult.AddRange(listQuesSearch.ToList());
                        }
                        else
                        {
                            listQuesResult = listQuesSearch.ToList();
                        }
                        result.Data = listQuesResult;
                        result.TotalCount = listQuesSearch.Count();
                    }
                    else
                    {
                        //if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                        //{
                        //    listQues2 = listQues2.ToList().FindAll(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));
                        //}
                        //result.TotalCount = listQues2.Count();
                        //result.Data = listQues2;

                        bool isHave = true;
                        if (CHECKOBJECT == null && SAFE_CHECK_ID != Guid.Empty)
                        {
                            var check = GetEntity<T_BS_SAFE_CHECK>(SAFE_CHECK_ID);
                            if (check != null && check.CHECKOBJECT.HasValue)
                            {
                                CHECKOBJECT = (BSMineTypeEnum)check.CHECKOBJECT.Value;
                            }
                        }

                        if (CHECKOBJECT != null)
                        {

                            #region      如果数据库中未查找到 到  T_BS_CHECK_CONTENTS 去查找

                            var contents = GetEntities<T_BS_CHECK_CONTENTS>(e => e.CHECKCONTENT == CHECKCONTENT && e.CHECKOBJECT == CHECKOBJECT, null, null);
                            if (contents != null && contents.Any())
                            {
                                Expression<Func<T_BS_CHECK_QUESTION, bool>> expressionQ = e => !e.IS_DELETED;
                                var listContentIDs = contents.Select(e => e.ID).ToList();

                                if (contents.Count() == 1)
                                {
                                    expressionQ = expressionQ.And(e => listContentIDs[0] == e.CHECK_CONTENTS_ID);
                                }
                                else
                                {
                                    expressionQ = expressionQ.And(e => e.CHECK_CONTENTS_ID.HasValue && listContentIDs.Contains(e.CHECK_CONTENTS_ID.Value));
                                }

                                if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                                {
                                    expressionQ = expressionQ.And(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));
                                }

                                var questions = GetEntities(expressionQ, null, null).ToList();
                                if (questions != null && questions.Any())
                                {
                                    questions.AddRange(listQues2);//加载无

                                    result.TotalCount = questions.Count();

                                    //foreach (var item in questions)
                                    //{
                                    //    if (!listID.Contains(item.ID))
                                    //    {
                                    //        item.Nav_Main = new T_BS_CHECK_MAIN();
                                    //        item.Nav_Main.QUESTION_LEVEL = (int)item.QUESTION_LEVEL;
                                    //    }
                                    //}
                                    result.Data = questions;
                                }
                                else
                                {
                                    isHave = false;
                                }
                            }
                            else
                            {
                                isHave = false;
                            }

                            #endregion
                        }
                        else
                        {
                            //保持原来的
                            isHave = false;
                        }

                        if (!isHave)
                        {
                            if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                            {
                                listQues2 = listQues2.ToList().FindAll(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));
                            }

                            result.TotalCount = listQues2.Count();
                            result.Data = listQues2;
                        }
                    }
                }
                else
                {
                    result.TotalCount = listQues2.Count();
                    result.Data = listQues2;
                }

                if (result.Data != null && result.Data.Any())
                {
                    int RequestType = DataHelper.GetRequestType(Request.Headers);
                    if (RequestType == 2)
                    {
                        result.Data = GetEnumsShow(result.Data);
                    }
                }

                //if (pageFilter.FilterGroup.Rules.Count > 0)
                //{


                //Guid DetailID = Guid.Empty;
                //foreach (var item in filter.FilterGroup.Rules)
                //{
                //    if (item.Field == "Keyword")
                //    {
                //        DetailID = new Guid(filter.FilterGroup.Rules.ToList()[0].Value.ToString());
                //        filter.FilterGroup.Rules.Remove(item);
                //        break;
                //    }
                //}
                //if (DetailID != Guid.Empty)
                //{
                //    var checkDetail = GetEntity<T_BS_SAFE_CHECK_DETAIL>(DetailID);
                //    var listQues = GetEntities<T_BS_CHECK_MAIN>(e => e.RISK_AREA_ID == checkDetail.RISK_AREA_ID && e.CHECK_PROJECT_ID == checkDetail.CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == checkDetail.CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == checkDetail.CHECKCONTENT, filter, new string[] { "Nav_CheckQuestion" }).Select(e => e.Nav_CheckQuestion).Distinct();
                //    result.TotalCount = listQues.Count();
                //    result.Data = listQues;
                //}
                //else
                //{
                //    result.TotalCount = 0;
                //    result.Data = new List<T_BS_CHECK_QUESTION>();
                //}
                //}
                //else
                //{
                //    result.TotalCount = 2;
                //    result.Data = listQues2;
                //}
            });

        }

        /// <summary>
        /// 问题等级（app接口需求）
        /// </summary>
        /// <param name="IListQuestion"></param>
        /// <returns></returns>
        private IEnumerable<T_BS_CHECK_QUESTION> GetEnumsShow(IEnumerable<T_BS_CHECK_QUESTION> IListQuestion)
        {
            if (IListQuestion != null && IListQuestion.Any())
            {
                foreach (var item in IListQuestion)
                {
                    if (item.Nav_Main != null && item.Nav_Main.QUESTION_LEVEL > 0)
                    {
                        item.Nav_Main.QUESTION_LEVE_DESCRIPTION = ((BSQuestionLevelEnum)item.Nav_Main.QUESTION_LEVEL).GetDescription();
                    }
                }
            }
            return IListQuestion;
        }

        /// <summary>
        /// 排序分页查询数据  DEMAND 各不相同  隐患上报  选择整改建议与措施
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedDisDemand")]
        public PagedActionResult<T_BS_CHECK_QUESTION> OrderPagedDisDemand([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_QUESTION>((result) =>
            {
                //Expression<Func<T_BS_CHECK_QUESTION, bool>> expression = null;// GetExpression(pageFilter, "OrderPagedArea", out SAFE_CHECK_ID);
                var info = this.GetEntities<T_BS_CHECK_QUESTION>(null, pageFilter, null).Select(e => new T_BS_CHECK_QUESTION { ID = e.ID, DEMAND = e.DEMAND, DESCREPTION = "" }).Distinct(e => e.DEMAND).ToList();
                result.TotalCount = info.Count;
                result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList<T_BS_CHECK_QUESTION>();
            });
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedRisk")]
        public PagedActionResult<T_BS_CHECK_QUESTION> OrderPagedRisk([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_CHECK_QUESTION> result)
            {
                PagedActionResult<T_BS_CHECK_QUESTION> orderPageEntities = GetOrderPageEntities<T_BS_CHECK_QUESTION>(null, pageFilter, null);
                result.Data = orderPageEntities.Data;

                if (result.Data != null && result.Data.Any())
                {
                    foreach (var item in result.Data)
                    {
                        if (item.QUESTION_LEVEL == BSQuestionLevelEnum.重大)
                        {
                            item.SERIOUS_RISK = 1;
                        }
                        else
                        {
                            item.SERIOUS_RISK = 0;
                        }
                    }
                }
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }


        /// <summary>
        /// 安全检查明细退回
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetRejectCheckDetailDESCREPTION")]
        public PagedActionResult<T_BS_CHECK_QUESTION> GetRejectCheckDetailDESCREPTION([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_QUESTION>((result) =>
            {
                Guid DetailID = Guid.Empty;
                foreach (var item in pageFilter.FilterGroup.Groups)
                {
                    foreach (var itemG in item.Rules)
                    {
                        if (itemG.Field == "ID")
                        {
                            DetailID = new Guid(itemG.Value.ToString());
                        }
                    }
                }

                var Detail = GetEntity<T_BS_SAFE_CHECK_DETAIL>(DetailID);//, "Nav_ListCheckDetailQuestion.Nav_Question"

                Guid CHECK_TYPE_LEVEL_ID = Guid.Empty;
                string CHECKCONTENTSearch = string.Empty;

                Guid RISK_AREA_ID = Detail.RISK_AREA_ID.Value;
                Guid CHECK_PROJECT_ID = Detail.CHECK_PROJECT_ID.Value;
                Guid CHECK_PROJECT_CATEGORY_ID = Detail.CHECK_PROJECT_CATEGORY_ID.Value;
                Guid SAFE_CHECK_ID = Detail.SAFE_CHECK_ID;
                Guid DEPARTMENT_ID = Detail.DEPARTMENT_ID.Value;
                string CHECKCONTENT = Detail.CHECKCONTENT;

                if (CHECK_TYPE_LEVEL_ID == Guid.Empty && SAFE_CHECK_ID != Guid.Empty)
                {
                    CHECK_TYPE_LEVEL_ID = GetEntity<T_BS_SAFE_CHECK>(SAFE_CHECK_ID).CHECK_TYPE_LEVEL_ID.Value;
                }

                Guid Q5 = new Guid("55555555-5555-5555-5555-555555555555");
                T_BS_CHECK_QUESTION modelQ5 = GetEntity<T_BS_CHECK_QUESTION>(Q5);

                List<FilterGroup> listGroups = pageFilter.FilterGroup.Groups.ToList();
                var rulesSearch = listGroups.Count > 1 ? listGroups[1].Rules : null;
                if (rulesSearch != null && rulesSearch.Any())
                {
                    CHECKCONTENTSearch = rulesSearch.ToList()[0].Value.ToString();
                }

                //wyw1114 expression && e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == DEPARTMENT_ID
                Expression<Func<T_BS_CHECK_MAIN, bool>> expression = e => e.RISK_AREA_ID == RISK_AREA_ID && e.CHECK_TYPE_LEVEL_ID == CHECK_TYPE_LEVEL_ID && e.CHECK_PROJECT_ID == CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == CHECKCONTENT && !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.CHECK_QUESTION_ID.HasValue;

                if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                {
                    expression = expression.And(e => e.Nav_CheckQuestion != null && e.Nav_CheckQuestion.DESCREPTION.Contains(CHECKCONTENTSearch));
                }

                //var listQuesSearch = GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckQuestion" }).Select(e => e.Nav_CheckQuestion).Distinct();
                var listQuesSearch = GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckQuestion" }).Select(e => e.Nav_CheckQuestion).Distinct();

                if (listQuesSearch != null && listQuesSearch.Any())
                {
                    //if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                    //{
                    //    listQuesSearch = listQuesSearch.Where(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));
                    //}

                    //检查问题
                    var listMainSearch = GetEntities<T_BS_CHECK_MAIN>(expression, null, null).Distinct();

                    List<T_BS_CHECK_QUESTION> listQuesResult = new List<T_BS_CHECK_QUESTION>() { modelQ5 };

                    //if (listQues2 != null && listQues2.Any())
                    //{
                    //    listQuesResult = listQues2.ToList();
                    if (!string.IsNullOrEmpty(CHECKCONTENTSearch))
                        listQuesResult = listQuesResult.FindAll(e => e.DESCREPTION.Contains(CHECKCONTENTSearch));

                    foreach (var item in listQuesSearch)
                        item.Nav_Main = listMainSearch.FirstOrDefault(e => e.CHECK_QUESTION_ID == item.ID);

                    listQuesResult.AddRange(listQuesSearch.ToList());
                    //}
                    //else
                    //{
                    //    listQuesResult = listQuesSearch.ToList();
                    //}
                    result.Data = listQuesResult;
                    result.TotalCount = listQuesSearch.Count();
                    if (result.TotalCount > 0 && DataHelper.GetRequestType(Request.Headers) == 2)
                    {
                        foreach (var item in result.Data)
                        {
                            if (item.QUESTION_LEVEL > 0)
                            {
                                item.QUESTION_LEVEL_SHOW = item.QUESTION_LEVEL.GetDescription();
                            }
                            else
                            {
                                item.QUESTION_LEVEL_SHOW = "";
                            }
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(CHECKCONTENTSearch) && modelQ5.DESCREPTION.Contains(CHECKCONTENTSearch))
                    {
                        result.TotalCount = 1;
                        result.Data = new List<T_BS_CHECK_QUESTION>() { modelQ5 };
                    }
                    else
                    {
                        result.TotalCount = 0;
                        result.Data = new List<T_BS_CHECK_QUESTION>() { };
                    }
                }
            });
        }
    }
}
