using APT.BaseData.Domain.ApiModel.Platform;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Data.Common;

namespace APT.PF.WebApiControllers.Api.PF
{

    /// <summary>
    /// 系统日志
    /// </summary>
    [Route("api/PF/Connect")]
    public partial class ConnectController : AuthorizeApiController<T_PF_DATA_CHANNEL>
    {
        public int UnConnectTime = 30;//30分钟断线通知
        public int NoticTime = 30;//通知间隔时间
        public int NoticCount = 3;//通知次数
        /// <param name="data">
        /// 判断是否链接
        /// </param>
        /// <returns></returns>
        [HttpPost, Route("Judge")]
        public JsonActionResult<bool> Judge([FromBody] KeywordFilter filter)
        {
            return base.SafeExecute(() =>
            {
                var lastTimeStr = CsRedisManager.StringGet<string>(RedisCacheKey.LastConnetTime);
                if (string.IsNullOrEmpty(lastTimeStr))
                    return false;
                var lastTime = DateTime.Parse(lastTimeStr);
                if (lastTime != null)
                {
                    if (lastTime.AddMinutes(UnConnectTime) < DateTime.Now)
                    {
                        var noticeTimeStr = CsRedisManager.StringGet<string>(RedisCacheKey.LastNoticeTime);
                        if (string.IsNullOrEmpty(noticeTimeStr))
                            return false;
                        var noticeTime = DateTime.Parse(noticeTimeStr);
                        if (noticeTime == null || noticeTime.AddMinutes(NoticTime) < DateTime.Now)
                        {

                            var noticeCount = CsRedisManager.StringGet<int>(RedisCacheKey.LastNoticeCount);
                            if (noticeCount == null || noticeCount < NoticCount)
                            {
                                //短信通知
                                CsRedisManager.StringSet(RedisCacheKey.LastNoticeTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                if (noticeCount == null)
                                    noticeCount = 1;
                                else
                                    noticeCount++;
                                CsRedisManager.StringSet(RedisCacheKey.LastNoticeCount, noticeCount);
                                var config = this.GetEntity<T_FM_BASE_CONFIG>(i => i.ORG_ID == filter.OrgId);
                                //插入到表
                                if (!string.IsNullOrEmpty(config.TEL))
                                {
                                    T_FM_NOTICE notice = new T_FM_NOTICE()
                                    {
                                        ID = Guid.NewGuid(),
                                        MESSAGE = "[" + config.SYS_NAME + "]系统数据采集已中断，中断时间:" + lastTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        NOTICE_TYPE = (int)FMNoticeType.短信,
                                        ORG_ID = config.ORG_ID,
                                        TRYCOUNT = 3,
                                        TEL = config.TEL,
                                        NOTICE_STATUS = (int)FMNoticeStatus.等待发送,
                                        Message_TYPE = (int)FMMessageType.数据中断
                                    };
                                    this.AddEntity(notice);
                                }
                            }
                        }
                    }
                }
                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;
        }

    }
}
