using APT.BaseData.Domain.Entities;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal;
using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Enums;
using Microsoft.EntityFrameworkCore.Internal;
using System.Linq;
using IdentityModel;
using System.Data.Common;

using APT.Utility;
namespace APT.PF.WebApiControllers.Api.PF
{

    /// <summary>
    /// 系统日志
    /// </summary>
    [Route("api/PF/DataChannel")]
    public partial class DataChannelController : AuthorizeApiController<T_PF_DATA_CHANNEL>
    {


        /// <summary>
        /// 联合添加
        /// </summary>
        /// <param name="data">
        /// 实体
        /// </param>
        /// <returns></returns>
        [HttpPost, Route("JoinAdd")]
        public JsonActionResult<bool> JoinAdd([FromBody] T_PF_DATA_CHANNEL data)
        {
            return base.SafeExecute(() =>
            {
                var extConnConfigService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IExtConnConfigService>();
                var connParam = extConnConfigService.GetConfigParam(data.ORG_ID ?? Guid.Empty, "D001");
                if (connParam == null)
                    this.ThrowError("20002");
                var conn = connParam["Conn"];
                if (string.IsNullOrEmpty(conn))
                    this.ThrowError("20002");
                var dbConn = this.InitDbConnection(DataBaseType.Postgresql, conn);

                var clientEnable = data.ENABLE_STATUS == (int)(FMEnableStatusEnum.启用) ? true : false;
                var sql = $"SELECT \"Id\", \"Enabled\", \"ClientId\", \"ClientName\"  FROM public.\"Clients\" where  \"ClientId\"='{data.APP_ID}'";
                bool isUpdate;
                int clientId;
                QueryClient(dbConn, sql, out isUpdate, out clientId);
                var commitSql = "";
                var addScop = "";
                var deleteScop = "";
                var commitSecret = "";
                var newClient = !isUpdate;
                //insert client数据
                if (!isUpdate)
                {
                    var insertSql = $"INSERT INTO \"Clients\"(\"Enabled\",\"ClientId\",\"ClientName\",\"ProtocolType\"," + //ok
                    $"\"RequireClientSecret\",\"AllowRememberConsent\",\"AlwaysIncludeUserClaimsInIdToken\"," +//ok
                    $"\"RequirePkce\",\"AllowPlainTextPkce\",\"AllowAccessTokensViaBrowser\"," +//ok
                    $"\"BackChannelLogoutSessionRequired\",\"AllowOfflineAccess\",\"IdentityTokenLifetime\"," +//ok
                    $"\"AccessTokenLifetime\",\"AuthorizationCodeLifetime\",\"ConsentLifetime\"," +//ok
                    $"\"AbsoluteRefreshTokenLifetime\",\"SlidingRefreshTokenLifetime\",\"RefreshTokenUsage\"," +//ok
                    $"\"UpdateAccessTokenClaimsOnRefresh\",\"RefreshTokenExpiration\",\"AccessTokenType\"," +//ok
                    $"\"EnableLocalLogin\",\"IncludeJwtId\",\"AlwaysSendClientClaims\"," +//ok
                    $"\"ClientClaimsPrefix\",\"PairWiseSubjectSalt\",\"DeviceCodeLifetime\"," +//ok
                    $"\"NonEditable\",\"RequireConsent\",\"FrontChannelLogoutSessionRequired\",\"Created\")" +//ok
                    $" VALUES ({clientEnable},'{data.APP_ID}','{data.NAME}','oidc'," +
                    $"true,true,false," +
                    $"false,false,false," +
                    $"true,true,300," +
                    $"{data.LIFE_TIME},300,null," +
                    $"2592000,1296000,1," +
                    $"false,1,0," +
                    $"true,false,false," +
                    $"'client_',null,300," +
                    $"false,true,true,'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, insertSql, null, false);
                    QueryClient(dbConn, sql, out isUpdate, out clientId);
                }
                commitSql = $"update \"Clients\" set \"Enabled\"={clientEnable},\"ClientId\"='{data.APP_ID}'," +
                $"\"AccessTokenLifetime\"={data.LIFE_TIME}, \"ClientName\"='{data.NAME}' where \"Id\"='{clientId}'";
                var clientScops = data.Nav_ClientScopes;
                data.Nav_ClientScopes = null;
                var filter = new BaseFilter();
                filter.IgnoreOrgRule = true;
                //查询scops
                deleteScop = $"DELETE  FROM  \"ClientScopes\" WHERE \"ClientId\"='{clientId}'";
                if (clientScops != null && clientScops.Any(i => !i.IS_DELETED))
                {
                    var sopesIds = clientScops.Select(i => i.SCOPE_ID).ToArray();
                    var scopes = this.GetEntities<T_PF_SCOPES>(x => sopesIds.Contains(x.ID), filter);
                    addScop = "INSERT INTO  \"ClientScopes\"(\"ClientId\",\"Scope\")  VALUES ";
                    foreach (var s in clientScops.Where(i => !i.IS_DELETED))
                    {
                        s.DATA_CHANNEL_ID = data.ID;
                        var scop = scopes.FirstOrDefault(i => i.ID == s.SCOPE_ID);
                        addScop += $"( '{clientId}','{scop.NAME}'),";
                    }
                    addScop = addScop.Trim(',');
                }
                //
                var clientGrantSql = "";
                if (!newClient)
                {
                    commitSecret = $"update \"ClientSecrets\" set \"Value\"='{data.SECURITY_KEY.ToSha256()}' where \"ClientId\"='{clientId}'";
                }
                else
                {
                    commitSecret = $"INSERT INTO \"ClientSecrets\"(\"Value\",\"Type\",\"Created\",\"ClientId\") " +
                    $"VALUES('{data.SECURITY_KEY.ToSha256()}','SharedSecret','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{clientId}')";

                    clientGrantSql = $"INSERT INTO \"ClientGrantTypes\"(\"GrantType\",\"ClientId\") " +
                    $"VALUES('client_credentials','{clientId}')";
                }

                //数据库操作

                //1.client表
                this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, commitSql, null, false);
                //2.scop表
                this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, deleteScop, null, false);
                if (!string.IsNullOrEmpty(addScop))
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, addScop, null, false);
                //3.Secret表
                this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, commitSecret, null, false);
                //4.grantType表
                if (newClient)
                {
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, clientGrantSql, null, true);
                }
                //5.内部数据
                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(data);
                    this.BantchSaveEntityNoCommit(clientScops);
                });



                return true;
            });
        }


        /// <summary>
        /// 联合添加
        /// </summary>
        /// <param name="data">
        /// 实体
        /// </param>
        /// <returns></returns>
        [HttpGet, Route("JobDelete")]
        public JsonActionResult<bool> JobDelete(string id)
        {
            return base.SafeExecute(() =>
            {
                var data = this.GetEntity<T_PF_DATA_CHANNEL>(id);
                if (data == null)
                    this.ThrowError("20002");
                var extConnConfigService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IExtConnConfigService>();
                var connParam = extConnConfigService.GetConfigParam(data.ORG_ID ?? Guid.Empty, "D001");
                if (connParam == null)
                    this.ThrowError("20002");
                var conn = connParam["Conn"];
                if (string.IsNullOrEmpty(conn))
                    this.ThrowError("20002");
                var dbConn = this.InitDbConnection(DataBaseType.Postgresql, conn);

                var clientEnable = data.ENABLE_STATUS == (int)(FMEnableStatusEnum.启用) ? true : false;
                var sql = $"SELECT \"Id\", \"Enabled\", \"ClientId\", \"ClientName\"  FROM public.\"Clients\" where  \"ClientId\"='{data.APP_ID}'";
                bool isUpdate;
                int clientId;
                QueryClient(dbConn, sql, out isUpdate, out clientId);
                if (isUpdate)
                {
                    var commitSql = $"delete from \"Clients\" where \"Id\"='{clientId}'";
                    //查询scops
                    var deleteScops = $"DELETE  FROM  \"ClientScopes\" WHERE \"ClientId\"='{clientId}'";
                    var commitSecret = $"delete from \"ClientSecrets\"  where \"ClientId\"='{clientId}'";
                    var clientGrantSql = $"delete from \"ClientGrantTypes\" where \"ClientId\"='{clientId}'";

                    //2.scop表
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, deleteScops, null, false);
                    //3.Secret表
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, commitSecret, null, false);
                    //4.grantType表
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, clientGrantSql, null, false);
                    //1.client表
                    this.ExecuteNonQueryByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, commitSql, null, true);



                }

                //4.内部数据
                this.UnifiedCommit(() =>
                {
                    this.DeleteEntityNoCommit<T_PF_CLIENT_SCOPES>(i => i.DATA_CHANNEL_ID == data.ID);
                    this.DeleteEntityNoCommit<T_PF_DATA_CHANNEL>(id);
                });
                return true;
            });
        }

        private void QueryClient(DbConnection dbConn, string sql, out bool isUpdate, out int clientId)
        {

            var update = false;
            var id = 0;
            this.ExecuteReaderPageByConn(DataBaseType.Postgresql, dbConn, System.Data.CommandType.Text, sql,
                        null, 0, 1, (reader) =>
                        {
                            while (reader.Read())
                            {
                                update = true;
                                id = Convert.ToInt32(reader.GetValue(0));
                            }
                        }, false);
            isUpdate = update;
            clientId = id;
        }

    }
}
