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

using APT.Utility;
using System.Diagnostics;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.Infrastructure.Api.Redis;

namespace APT.PF.WebApiControllers.Api.PF
{
    [APT.Infrastructure.Api.RootOrg]
    [Route("api/PF/FormQuery")]
    public class FormQueryController : AuthorizeApiController<T_PF_FORM_QUERY>
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_PF_FORM_QUERY>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_PF_FORM_QUERY>> OrderEntities([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_PF_FORM_QUERY>>(() =>
            {
                var data = this.GetOrderEntities<T_PF_FORM_QUERY>(null, filter);
                return data;
            });

        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_PF_FORM_QUERY> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_PF_FORM_QUERY> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_PF_FORM_QUERY entity)
        {
            return SafeExecute<bool>(() =>
            {
                this.UpdateEntity(entity);
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.CreateFormConfigVersion(PFFormConfigVersionEnum.FormQuery, entity.ID.ToString());
                return true;
            });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.CreateFormConfigVersion(PFFormConfigVersionEnum.FormQuery, id);
                List<Guid> ids = new List<Guid>();
                ids.Add(new Guid(id));
                this.DoDelete(ids);
                return true;
            });
        }

        private void DoDelete(List<Guid> ids)
        {
            this.DeleteEntity<T_PF_QUERY>(t => ids.Contains(t.PAGE_FORM_QUERY_ID ?? Guid.Empty));
            this.DeleteEntity<T_PF_FORM_QUERY>(t => ids.Contains(t.ID));
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult<bool> BatchDelete(string ids)
        {
            return SafeExecute<bool>(() =>
            {
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.CreateFormConfigVersion(PFFormConfigVersionEnum.FormQuery, ids);
                var arrays = string.IsNullOrEmpty(ids) ? null : ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(t => new Guid(t)).ToList();
                if (arrays != null && arrays.Any())
                    this.DoDelete(arrays);
                return true;
            });
        }
        /// <summary>
        /// 根据ID获得实体数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_PF_FORM_QUERY> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }


        /// <summary>
        /// 获取编辑页配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSearchConfigInfo")]
        public JsonActionResult<SearchModel> GetSearchConfigInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<SearchModel>(() =>
            {
                var session = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<ISessionProvider>();
                string formId = filter.Parameter1;
                string code = filter.Parameter2;
                var formCode = filter.Keyword;
                var redisCode = string.Format(RedisCacheKey.SearchConfigRedisKey, formCode, formId, code, filter.GetOrgId());
                bool isRedisConfig = true;
                var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
                if (!string.IsNullOrEmpty(redisConfig))
                    isRedisConfig = bool.Parse(redisConfig);
                if (isRedisConfig)
                {
                    if (CsRedisManager.KeyExists(redisCode))
                        return CsRedisManager.StringGet<SearchModel>(redisCode);
                }
                T_PF_FORM form = null;
                filter.OrgType = FilterOrgTypeEnum.仅本组织;
                if (!string.IsNullOrEmpty(formCode))
                    form = this.GetEntity<T_PF_FORM>(i => i.CODE == formCode, new BaseFilter(filter.GetOrgId()));
                if (form == null)
                {
                    form = this.GetEntity<T_PF_FORM>(formId);
                    if (form == null)
                        return null;
                }
                SearchModel result = new SearchModel();
                result.Nav_Form = form;

                Expression<Func<T_PF_FORM_QUERY, bool>> expression = t => t.PAGE_FORM_ID == form.ID;

                //var formQuery = this.GetEntityByRedis<T_PF_FORM_QUERY>(form.ID.ToString(), filter.OrgId ?? Guid.NewGuid());
                var formQuerys = this.GetEntities<T_PF_FORM_QUERY>(expression,
                    new BaseFilter(filter.GetOrgId()), "Nav_Querys").OrderBy(t => t.NUM).ToList();

                if (formQuerys != null && formQuerys.Any())
                {
                    if (!string.IsNullOrEmpty(code))
                        formQuerys.ForEach(i => i.Nav_Querys = i.Nav_Querys.Where(x => x.CODE == code).ToList());
                }
                result.Nav_FormQuery = formQuerys;
                CsRedisManager.StringSet(redisCode, result);
                return result;
            });
        }

    }
}
