using AngleSharp.Html.Parser;
using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.Serializer;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Vpn.Model;
using Hncore.Pass.Vpn.Request.Product;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Hncore.Pass.Vpn.Service
{
    //先锋
    public class AgentClient5Service : AgentClient1Service
    {
        string LoginUrl { get; set; } = "main/agentLogin.html";
        string LoginCodeUrl { get; set; } = "main/imgcode.html";
        string RefrushTokenUrl { get; set; } = "agent.html";
        string SingleAddUrl { get; set; } = "agent/memberSingleAdd.html";
        string SingleReAddUrl { get; set; } = "agent/memberRenew.html";
        string MuiltAddUrl { get; set; } = "agent/memberMuiltAdd.html";
        string RefundUrl { get; set; } = "agent/memberRefund/id/{0}.html"; 
        string UpdateUrl = "agent/memberUpdate/id/{0}.html";//agent/memberUpdate/id/1155709.html 
        string OnlineUrl { get; set; } = "agent/radiusOnline.html?search=1&username=";
        string ClientOnlineUrl { get; set; } = "agent/clientOnline.html?search=1&username=";
        string KIllUrl { get; set; } = "";
        string KillUrlClient = "/agent/disConnect/sessionid/{0}.html";
        string KillUrl = "/agent/disConnect/radacctid/{0}.html";
        string searchAccountUrl = "agent/memberList/type/1.html?search=1&username=";
        string searchTestAccountUrl = "agent/memberList/type/0.html?search=1&username=";
        string DeleteUrl { get; set; } = "agent/multiDelMember.html ";
        IHttpClientFactory m_HttpClientFactory;       
        public AgentClient5Service(IHttpClientFactory httpClientFactory):base(httpClientFactory)
        {
            m_HttpClientFactory = httpClientFactory;
        } 

        /// <summary>
        /// 新开
        /// </summary>
        /// <param name="packageId"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override async Task<ApiResult> NewAccount(string packageKey, string account, string pwd, int connCount = 1, int accountType = 1, int payCount = 1)
        {

            if(packageKey == "free"){
                return await NewTestAccount(packageKey, account, pwd, 1, accountType, 1);
            }

            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi/?secretId="+secretId+"&secretKey="+secretKey+"&type=adduser&user="+account+"&pass="+pwd+"&serverid="+packageKey+"&logincount="+connCount.ToString()+"&phone=17719092232&cardname=万永康&cardno=410325199810129916";

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();

            

            
            if (status =="1")
            {
                return new ApiResult(ResultCode.C_SUCCESS);
            }
            return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");

        }

         /// <summary>
        /// 新开
        /// </summary>
        /// <param name="packageId"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task<ApiResult> NewTestAccount(string packageKey, string account, string pwd, int connCount = 1, int accountType = 1, int payCount = 1)
        {
            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi3/?secretId="+secretId+"&secretKey="+secretKey+"&type=addtestuser&user="+account+"&password="+pwd+"&username3=admin01&phone=17719092232&cardname=万永康&cardno=410325199810129916";

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();

            Console.WriteLine("==================================================");
            Console.WriteLine(jo);
            Console.WriteLine("==================================================");

            

            
            if (status =="1")
            {
                return new ApiResult(ResultCode.C_SUCCESS);
            }
            return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");
        }

        /// <summary>
        /// 续费
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override async Task<ApiResult> NewReAccount(string packageKey, string account, int connCount, int payCount = 1)
        {

            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi/?secretId="+secretId+"&secretKey="+secretKey+"&type=buy&user="+account+"&serverid="+packageKey+"&logincount="+connCount.ToString()+"&phone=17719092232&cardname=万永康&cardno=410325199810129916";

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();

            
            if (status =="1")
            {
                    return new ApiResult(1);
            }
            return new ApiResult(ResultCode.C_INVALID_ERROR, "续费失败");

        }
        /// <summary>
        /// 删除账号
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<bool> DeleteAccount(string account)
        {
            var client = CreateHttpClient();
            var infoRet = await this.GetAccountInfo(account, true);
            if (infoRet.Code != ResultCode.C_SUCCESS)
                return false;
            var map = new Dictionary<string, string>(){
                {infoRet.Data.Id,infoRet.Data.Id },              
            };
            var title = GetOpTitle("DeleteAccount", account);
            LogHelper.Info(title, account);
            try
            {              
                var resp = await client.PostAsForm(this.DeleteUrl, map);
                var content = await resp.Content.ReadAsStringAsync();             
                if (content.Has() && content.IndexOf("删除成功") != -1)
                {
                    return true;
                }
                else
                {
                    LogHelper.Error(title, content);
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message);
                return false;
            }
        }
/// <summary>
        /// 得到账号信息
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<ApiResult<OriginAccountModel>> GetAccountInfo(string account,bool isTest=false)
        {

            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi/?secretId="+secretId+"&secretKey="+secretKey+"&type=getuserinfo&user="+account;

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();

            Console.WriteLine("---------------------------------------------------------------");
            Console.WriteLine(jo);
            Console.WriteLine("---------------------------------------------------------------");

            
            if (status =="1")
            {
                var trData = new OriginAccountModel
                {
                    Account = account,
                    Pwd = "",
                    AccountType = "",
                    Package = "",
                    RegistTime = "",
                    EndTime = jo["expiretime"].ToString(),
                    RestTime = "",
                    ConnectCount = jo["logincount"].ToString(),
                    Amount = "",
                    IsActive = "",
                    Remark = "",
                };
                return new ApiResult<OriginAccountModel>(trData);
            }
            
            return new ApiResult<OriginAccountModel>(ResultCode.C_INVALID_ERROR, "没有查询到信息");
        }

        /// <summary>
        /// 修改账号密码
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override async Task<bool> UpdateAccountPwd(string account, string pwd)
        {

            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi/?secretId="+secretId+"&secretKey="+secretKey+"&type=setuser&user="+account+"&&new_pwd="+pwd;

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();

            if (status =="1")
            {
                return true;
            } else {
                return false;
            }
            
        }
        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="packageId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<ApiResult> Refund(string account, string packageKey, int days)
        {
            var client = CreateHttpClient();           
            var title = GetOpTitle("Refund", account);          
            try
            {
                var accountInfo = await this.GetAccountInfo(account);
                if (accountInfo.Code != ResultCode.C_SUCCESS)
                {
                    return new ApiResult(ResultCode.C_INVALID_ERROR, "退款失败");
                }
                var url = string.Format(this.RefundUrl, accountInfo.Data.Id);
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("退款成功!") != -1)
                {
                    return new ApiResult(1);
                }
                else
                {
                    LogHelper.Error(title, content);
                    return new ApiResult(ResultCode.C_INVALID_ERROR, "退款失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message);
                return new ApiResult(ResultCode.C_INVALID_ERROR, "退款失败");
            }
        }
        /// <summary>
        /// 是否在线
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<ApiResult<List<OriginAccountOnlineModel>>> OnLine(string account)
        {

            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi3/?secretId="+secretId+"&secretKey="+secretKey+"&type=get_user_onlinelog&user="+account;

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();
            var retData = new List<OriginAccountOnlineModel>();
            if (status =="1")
            {
                if(jo.ContainsKey("data")){
                    foreach (var tr in jo["data"])
                    {
                        JObject jsondata = (JObject)JsonConvert.DeserializeObject(tr.ToJson());

                        var trData = new OriginAccountOnlineModel
                        {
                            Account = account,
                            ServerIP = jsondata["server_ip"].ToString(),
                            LoginTime = "",
                            OnlineTime = jsondata["online_time"].ToString(),
                            LoginIP = jsondata["client_ip"].ToString(),
                            UpStream = "",
                            DownStream = "",
                            Id = "user="+account+"-address="+jsondata["address"].ToString()+"-server_ip="+jsondata["server_ip"].ToString(),
                        
                        };
                        
                        retData.Add(trData);
                    }
                }
                return new ApiResult<List<OriginAccountOnlineModel>>(retData);
            } else {
                return new ApiResult<List<OriginAccountOnlineModel>>(retData);
            }

        }
        /// <summary>
        /// 踢号
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<bool> KillOut(string id)
        {
            var ids = "";
            if(id.Contains("-")){
                string[] arrStr = id.Split('-');
                ids = arrStr[0]+"&"+arrStr[1]+"&"+arrStr[2];
            }
            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi3/?secretId="+secretId+"&secretKey="+secretKey+"&type=user_online_offline&"+ids;

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();
            if (status =="1")
            {
                return true;
            }
            return false;
        }

        public async Task<bool> KillOutClient(string id)
        {           
            var client = CreateHttpClient();
            var title = GetOpTitle("KillOutClient", id);
            var info = "";
            try
            {
                var url = string.Format(this.KillUrlClient, id);
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("已经向客户端发送断开消息") != -1)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message + "-->info:" + info);
            }
            return false;
        }

        public override async Task<bool> Exist(string account)
        {
            

            var secretId = "626B6170693231";
            var secretKey = "6b3fdfc206841f44c6609bf19c182a6a";

            var url = "http://bkapi.pptp.biz/userapi3/?secretId="+secretId+"&secretKey="+secretKey+"&type=getuserlenNum&user="+account;

            var client = CreateHttpClient();

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            JObject jo = (JObject)JsonConvert.DeserializeObject(content);
            var status = jo["code"].ToString();

            
            
            Console.WriteLine("================test==================================");
            Console.WriteLine(jo);
            Console.WriteLine("==================================================");

            
            if (status =="1")
            {
                return false;
            }
            return true;
        }
    }
}
