using APT.BaseData.Domain.Entities;
using APT.Infrastructure.Api;
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;
using APT.Infrastructure.Core;

namespace APT.PF.WebApiControllers.Api.PF
{

    /// <summary>
    /// WebSocket信息
    /// </summary>
    [Route("api/PF/WebSocketInfo")]
    public partial class WebSocketInfoController : AuthorizeApiController<T_PF_DATA_CHANNEL>
    {


        /// <summary>
        /// 联合添加
        /// </summary>
        /// <param name="data">
        /// 实体
        /// </param>
        /// <returns></returns>
        [HttpPost, Route("ConcurrencyNum")]
        public JsonActionResult<int> ConcurrencyNum([FromBody]KeywordFilter filter)
        {
            return base.SafeExecute(() =>
            {
                return WebSocketServiceHelper.ClintInfos.Count;
            });
        }


        /// <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;
        }

    }
}
