using APT.BaseData.Domain.ApiModel.Platform;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Api;
using System;
using APT.BaseData.Domain.Enums.OP;

namespace APT.BD.WebApi.Controllers.Api
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/OP/TenantInfo")]
    public partial class TenantInfoController : CommonApiController
    {

        /// <summary>
        /// 根据域名获取组织数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetOrgList")]
        public JsonActionResult<dynamic> GetOrgList([FromBody] KeywordFilter filter)
        {
            return SafeExecute<dynamic>(() =>
            {

                dynamic ret = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrEmpty(filter.Parameter10))
                {
                    var baseFilter = new BaseFilter();
                    baseFilter.IgnoreOrgRule = true;
                   // baseFilter.SelectField = new string[] { "TENANT_ID", "Nav_Tenant.Nav_TenantDB.CODE", 
                        //"Nav_Tenant.Nav_TenantDB.DB_CONN", "Nav_Tenant.Nav_TenantDB.DB_CONN_WAN" };
                    var tenantDomain = this.GetEntity<T_OP_TENANT_DOMAIN>(i => i.DOMAIN_NAME == filter.Parameter10, "Nav_Tenant.Nav_TenantDB");
                    if (tenantDomain == null)
                        ThrowError("020027", filter.Parameter10);
                    if (tenantDomain.Nav_Tenant == null)
                        ThrowError("020026");
                    string conn = string.Empty;
                    T_OP_TENANT_DB_CONN srcDB = tenantDomain.Nav_Tenant.Nav_TenantDB;
                    if (srcDB != null)
                    {
                        conn = srcDB.DB_CONN;
                        if (ConfigurationManager.AppSettings["Env"] == ((int)EnvType.外网).ToString())
                        {
                            conn = srcDB.DB_CONN_WAN;
                        }
                    }
                    if (int.Parse(filter.Parameter11) == (int)PFPlatformTypeEnum.应用平台)
                    {
                        IEnumerable<TreeNode<T_FM_ORGANIZATION>> orgTree = null;
                        List<T_FM_ORGANIZATION> reslist;
                        baseFilter.SelectField = new string[] { "CODE", "TENANT_CODE", "NAME", "PARENT_ID", "ORG_ID", "ID" };
                        using (var context = new MigrationContext(conn))
                        {
                            orgTree = context.GetTreeOrderEntities<T_FM_ORGANIZATION>(x => x.ORG_ID == tenantDomain.TENANT_ID, baseFilter, null, out reslist);
                        }
                        ret.Data = orgTree.Where(x => x.Node.ID == tenantDomain.TENANT_ID);
                        //    ret.Data = this.GetTreeOrderEntities<T_FM_ORGANIZATION>(i => i.ENABLE_STATUS == (int)FMEnableStatusEnum.启用
                        //&& i.ID == tenant.ID, filter);
                    }
                    else
                    {
                        //企业平台  ----
                        var orgTree = this.GetTreeOrderEntities<T_FM_ORGANIZATION>(null, baseFilter);
                        ret.Data = orgTree.Where(x => x.Node.ID == tenantDomain.TENANT_ID);
                        //     ret.Data = this.GetOrderEntities<T_FM_ORGANIZATION>(i => i.ENABLE_STATUS == (int)FMEnableStatusEnum.启用
                        //&& i.ID == tenant.ID, filter);
                        //递归获取子集
                        //ret.Data = this.GetTreeOrderEntities<T_FM_ORGANIZATION>(i => i.ENABLE_STATUS == (int)FMEnableStatusEnum.启用
                        //, filter).Where(i=>i.Node.ID==tenant.ID);
                    }
                    ret.Tenant = tenantDomain.Nav_Tenant.CODE;


                }
                return ret;
            });
        }

        /// <summary>
        /// 根据域名获取组织数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_OP_TENANT>> Entities([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_OP_TENANT>>(() =>
            {
                return this.GetEntitiesByRedis<T_OP_TENANT>(i => i.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, filter);
            });
        }

        /// <summary>
        /// 根据租户名称获取数据库地址
        /// </summary>
        /// <param name="code">租户编码</param>
        /// <param name="deskey">Des Key</param>
        /// <param name="tenantKey">Redis key</param>
        /// <returns></returns>
        [HttpGet, Route("GetDbConn")]
        public JsonActionResult<string> GetDbConn(string code, string deskey, string tenantKey)
        {
            return SafeExecute<string>(() =>
            {
                var baseFilter = new BaseFilter();
                //baseFilter.SelectField = new string[] { "Nav_TenantDB.DB_CONN", "ID" };
                baseFilter.IgnoreOrgRule = true;
                var ret = string.Empty;
               // var tenant = this.GetEntityByRedis<T_OP_TENANT>(code, Guid.Empty);
                var tenant = this.GetEntity<T_OP_TENANT>(t=>t.CODE==code);

                if (tenant != null && !string.IsNullOrEmpty(deskey))
                {
                    var tenantDb = this.GetEntity<T_OP_TENANT_DB_CONN>(tenant.DB_CONN_ID.ToString());
                    ret = EncryptHelper.AesEncrypt(tenantDb?.DB_CONN, deskey);
                    if (ConfigurationManager.AppSettings["Env"] == ((int)EnvType.外网).ToString())
                    {
                        ret = EncryptHelper.AesEncrypt(tenantDb?.DB_CONN_WAN, deskey);
                    }
                    var tenantConnKey = tenantKey + code + "_" + ConfigurationManager.AppSettings["Env"];
                    CsRedisManager.StringSetAsync(tenantConnKey, ret).Wait();
                }
                return ret;
            });
        }

        /// <summary>
        /// 获取所有的数据库连接
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetAllDbConn")]
        public JsonActionResult<List<string>> GetAllDbConn(string deskey)
        {
            return SafeExecute<List<string>>(() =>
            {
                var baseFilter = new BaseFilter();
                baseFilter.SelectField = new string[] { "DB_CONN", "DB_CONN_WAN" };
                baseFilter.IgnoreOrgRule = true;
                var ret = new List<string>();
                var dbs = this.GetEntities<T_OP_TENANT_DB_CONN>(null, baseFilter);
                if (dbs != null && dbs.Any())
                {
                    ret = dbs.Select(i => EncryptHelper.AesEncrypt(i.DB_CONN, deskey)).ToList();
                    if (ConfigurationManager.AppSettings["Env"] == ((int)EnvType.外网).ToString())
                    {
                        ret = dbs.Select(i => EncryptHelper.AesEncrypt(i.DB_CONN_WAN, deskey)).ToList();
                    }
                    var tenantConnKey = ConfigurationManager.AppSettings["TenantConnKey"] + "_All_" + ConfigurationManager.AppSettings["Env"];
                    CsRedisManager.StringSetAsync(tenantConnKey, ret).Wait();
                }
                return ret;
            });
        }

    }
}
