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 APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Api;
using APT.Utility;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.Infrastructure.Api.Redis;

namespace APT.PF.WebApiControllers.Api.PF
{
    [Route("api/PF/PageTree")]
    [APT.Infrastructure.Api.RootOrg]
    public class PageTreeController : AuthorizeApiController<T_PF_PAGE_TREE>
    {
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_PF_PAGE_TREE>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_PF_PAGE_TREE>> OrderEntities([FromBody] KeywordFilter filter)
        {
            //return WitOrderEntities(null, filter);
            return SafeExecute<IEnumerable<T_PF_PAGE_TREE>>(() =>
            {
                var data = this.GetOrderEntities<T_PF_PAGE_TREE>(null, filter); ;
                data.ForEach(x =>
                {
                    if (x.Nav_Columns != null) x.Nav_Columns.Where(i => !string.IsNullOrEmpty(i.ENUM))
            .ForEach(i => i.ENUM = DataHelper.EnumToString(i.ENUM));
                });
                return data;
            });
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_PF_PAGE_TREE> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_PF_PAGE_TREE> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_PF_PAGE_TREE entity)
        {
            return SafeExecute<bool>(() =>
            {
                this.UpdateEntity(entity);
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.CreateFormConfigVersion(PFFormConfigVersionEnum.PageTree, 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.PageTree, 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_TREE_COLUMN>(t => ids.Contains(t.PAGE_TREE_ID));
            this.DeleteEntity<T_PF_PAGE_TREE>(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.PageTree, ids);
                var arrays = string.IsNullOrEmpty(ids) ? null : ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(t => new Guid(t)).ToList();
                if (arrays != null && arrays.Count > 0)
                    this.DoDelete(arrays);
                return true;
            });
        }
        /// <summary>
        /// 根据ID获得实体数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_PF_PAGE_TREE> Get([FromBody] KeywordFilter filter)
        {
            //return WitEntity(null, filter);
            return SafeExecute<T_PF_PAGE_TREE>(() =>
            {
                var data = this.GetEntity<T_PF_PAGE_TREE>(null, filter);
                if (data == null)
                    throw new Exception("不存在此表单");
                if (data.Nav_Columns != null && data.Nav_Columns.Any(i => !string.IsNullOrEmpty(i.ENUM)))
                {
                    data.Nav_Columns.Where(i => !string.IsNullOrEmpty(i.ENUM))
                    .ForEach(i => i.ENUM = DataHelper.EnumToString(i.ENUM));
                }
                return data;
            });
        }
        /// <summary>
        /// 获取树配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetTreePageConfigInfo")]
        public JsonActionResult<TreePageModel> GetTreePageConfigInfo([FromBody] KeywordFilter filter)
        {
            //return WitEntity(null, filter);
            return SafeExecute<TreePageModel>(() =>
            {
                string formCode = filter.Keyword;
                if (string.IsNullOrEmpty(formCode))
                    throw new Exception("表单CODE不允许为空");
                filter.OrgType = FilterOrgTypeEnum.仅本组织;
                var redisCode = string.Format(RedisCacheKey.PageTreeRedisKey, filter.Keyword, filter.OrgId);
                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<TreePageModel>(redisCode);
                }
                var form = this.GetEntityByRedis<T_PF_FORM>(formCode, filter.GetOrgId());
                if (form == null)
                    return null;
                var redisFilter = new BaseFilter(filter.GetOrgId());
                redisFilter.Sort = "NUM";
                //var pageTree= this.GetEntity<T_PF_PAGE_TREE>(t => t.PAGE_FORM_ID == form.ID);
                var pageTree = this.GetEntity<T_PF_PAGE_TREE>(t => t.PAGE_FORM_ID == form.ID);

                if (pageTree == null)
                    return null;


                TreePageModel result = new TreePageModel();
                result.Nav_Form = form;
                result.Nav_PageTree = pageTree;

                var columns = this.GetEntitiesByRedis<T_PF_TREE_COLUMN>(null, redisFilter, pageTree.ID.ToString());
                result.Nav_Columns = columns;//
                                             //result.Nav_Columns = this.GetOrderEntities<T_PF_TREE_COLUMN>(t => t.PAGE_TREE_ID == pageTree.ID, tmpFilter).ToList();
                                             //重置枚举
                if (result.Nav_Columns != null)
                {
                    result.Nav_Columns.Where(i => !string.IsNullOrEmpty(i.ENUM))
                            .ForEach(i => i.ENUM = DataHelper.EnumToString(i.ENUM));
                }
                result.Nav_Btns = this.GetEntitiesByRedis<T_PF_BTN>(null, redisFilter, pageTree.ID.ToString());

                BaseFilter tmpFilter = new BaseFilter();
                tmpFilter.Sort = "NUM";
                tmpFilter.Order = DbOrder.ASC;
                tmpFilter.OrgType = FilterOrgTypeEnum.仅本组织;
                tmpFilter.SelectField = new string[] { "Nav_Picture.CODE", "NUM", "Nav_PicFilterDetail.NAME", "Nav_PicFilterDetail.FIELD_TYPE", "Nav_PicFilterDetail.OPERATE", "Nav_PicFilterDetail.VALUE" };
                result.Nav_PicFilter = this.GetEntities<T_PF_PIC_FILTER>(i => i.PAGE_FORM_ID == form.ID, tmpFilter).ToList();
                CsRedisManager.StringSet(redisCode, result);
                return result;
            });
        }
    }
}
