using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Bogus.DataSets;
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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Hncore.Pass.Vpn.Service
{
    public class AgentClient6Service : AgentClientBaseService
    {
        string secretId = "20200716182518182489";
        string secretKey = "OFcEJAfzYjWT3e2s";
        string UserApiUrl = "userapi/";
        string LoginIndexUrl { get; set; } = "login/";       
        string LoginUrl { get; set; } = "loginauth/";
        string LoginCodeUrl { get; set; } = "";
        string RefrushTokenUrl { get; set; } = "userInfo/";
        string SingleAddUrl { get; set; } = "userapi/";
        string SingleReAddUrl { get; set; } = "user_buy_server";
        string MuiltAddUrl { get; set; } = "agent/memberMuiltAdd.html";
        string RefundUrl { get; set; } = "agent/memberRefundAct.html ";      
        string UpdateUrl = "setuser";
        string OnlineUrl { get; set; } = "/userapi3/?secretId=20200716182518182489&secretKey=OFcEJAfzYjWT3e2s&type=get_user_onlinelog&user=";
        // string KIllUrl { get; set; } = "agent/disConnect2/radacctid/{0}.html";
        string KIllUrl { get; set; } = "/userapi3/?secretId=20200716182518182489&secretKey=OFcEJAfzYjWT3e2s&type=user_online_offline&user={0}&address={1}&server_ip={2}";
        ///userapi3/?secretId=xxx&secretKey=xxxv&type=user_online_offline&user=xxx&address=10.20.0.10&server_ip=58.21.1.x
        string searchAccountUrl = "userList/?sum=100&page=1&search_data=";
        string searchTestAccountUrl = "agent/memberList/type/0.html?search=1&username=";
        string DeleteUrl { get; set; } = "agent/memberDel/id/";//1160862.html";
        IHttpClientFactory m_HttpClientFactory;       
        public AgentClient6Service(IHttpClientFactory httpClientFactory):base(httpClientFactory)
        {
            m_HttpClientFactory = httpClientFactory;
        }

        protected override HttpClient CreateHttpClient(bool autoCooke = true)
        {
            var client = m_HttpClientFactory.CreateClient("agentClient1.0");
            client.BaseAddress = new System.Uri(this.BaseUrl);
            if (this.Token.Has() && autoCooke)
            {
                AddCookie(client, this.Token);
            }
            return client;
        }

        private string FormatRequest(Dictionary<string, string> map)
        {
            map["secretId"] = this.secretId;
            map["secretKey"] = this.secretKey;
            var data = string.Join("&", map.Select(m => $"{m.Key}={m.Value}"));           
            return data;
        }

        public override async Task<int> RefrushStatus()
        {
            int status = 0;
            if (this.Token.Has())
            {
                var client = CreateHttpClient();
                if (this.RefrushTokenUrl.Has())
                {
                   // client.DefaultRequestHeaders.Add("Cookie", this.Token);
                    var getResp = await client.GetAsync(this.RefrushTokenUrl);
                    if (getResp.StatusCode == HttpStatusCode.OK)
                    {
                        status = 1;
                    }
                    else
                    {
                        var request = new AgentLoginRequest()
                        {
                            Account = this.Product.Account,
                            Pwd = this.Product.Pwd
                        };
                    
                        var ret = await this.Login(request);
                        if (ret.Code == ResultCode.C_SUCCESS)
                        {
                            this.Product.Token = ret.Data.ToString();
                            status = 1;
                        }
                        else
                        {
                            Debug.WriteLine("离线");
                        }
                    }
                }
            }
            return status;
        }
        public override async Task<(byte[], string)> GetCode()
        {         
           
            return (null, "");
        }

        private async Task<(string, string)> GetHomeCookie()
        {
            var client = CreateHttpClient(false);
            var getResp = await client.GetAsync(this.LoginIndexUrl);
            var cookies = this.GetCookies(getResp);
            cookies = cookies.Replace("path=/;", "").Replace("httponly", "").Trim();

            var content = await getResp.Content.ReadAsStringAsync();

            var parser = new HtmlParser();
            var document = await parser.ParseDocumentAsync(content);
            var csrf_tokenNode = document.QuerySelector("input[name=csrfmiddlewaretoken]");//<input type='hidden' name='csrfmiddlewaretoken' value='b8XKenjQ9GJUJF0xSZySXLsG5FGNHepk' />

            var csrf_token = csrf_tokenNode.GetAttribute("value");
            return (cookies, csrf_token);
        }

        public override async Task<ApiResult> Login(AgentLoginRequest request)
        {
            var tokens = await this.GetHomeCookie();
            var client = CreateHttpClient(false);
            client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");

            var csrftoken = this.GetCookieValue(tokens.Item1, "csrftoken");
            var key = this.GetCookieValue(tokens.Item1, "key");
            var map = new Dictionary<string, string>(){
                {"csrfmiddlewaretoken",tokens.Item2},
                {"username",request.Account },
                {"password",request.Pwd },
                {"remember",key },
            };
            LogHelper.Info("Login", map.ToJson());

            var loginToken = $"csrftoken={csrftoken};key={key}";
            AddCookie(client, loginToken);
            var resp = await client.PostAsForm(this.LoginUrl, map);
            var content = await resp.Content.ReadAsStringAsync();
            if (resp.StatusCode != HttpStatusCode.Found || resp.Headers.Location.ToString().IndexOf("http://user.webok.me/userInfo/")==-1)
            {
                return new ApiResult(ResultCode.C_VISITOR_CHECKING, "登录失败");
            }
            var sessionid = this.GetCookie(resp, "sessionid");
            var username_user = this.GetCookie(resp, "username_user");
            request.Key = $"{loginToken};{sessionid};{username_user}";
            return new ApiResult(request.Key);
        }
        public override bool CheckAccount(int productId,List<string> accounts)
        {
            return false;
        }

        /// <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 == "test_pay")
                return await NewTestAccount(account, pwd);
            var client = CreateHttpClient();
            var map = new Dictionary<string, string>(){
                {"type","adduser" },
                {"user",account },
                {"pass",pwd },
                {"logincount",connCount.ToString()},
                {"serverid",packageKey },
            };
            var title = GetOpTitle("NewAccount", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                
                var resp = await client.GetAsync(this.UserApiUrl + "?" + this.FormatRequest(map));
                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);
                }
                else
                {
                    LogHelper.Error(title, content);
                    return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.GetInfo());
                return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");
            }
        }
        /// <summary>
        /// 新开测试账号
        /// </summary>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task<ApiResult> NewTestAccount(string account, string pwd)
        {
            var client = CreateHttpClient();
            var map = new Dictionary<string, string>(){
                {"type","addtestuser" },
                {"user",account },
                {"password",pwd },
                {"username3","" },
            };
            var title = GetOpTitle("NewAccount", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                
                var resp = await client.GetAsync("/userapi3/?" + this.FormatRequest(map));
                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);
                }
                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="packageId"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override async Task<ApiResult> NewMuiltAccount(string packageKey, string account, string pwd, int connCount = 1, int accountType = 1,int startNum=0, int endNum=1 )
        {
            var client = CreateHttpClient();
            var map = new Dictionary<string, string>(){
                {"taocanName",packageKey },
                {"usernameTpl",account },
                {"password",pwd },
                {"maxonline",connCount.ToString()},
                {"startNum",startNum.ToString()},
                {"endNum",endNum.ToString()},
                {"mode",accountType.ToString()},
            };
            var title = GetOpTitle("NewMuiltAccount", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.MuiltAddUrl, map);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("<td>成功</td>") != -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>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override async Task<ApiResult> NewReAccount(string packageKey, string account, int connCount, int payCount = 1)
        {
            var ret = await this.GetAccountInfo(account);
            if (ret.Code != ResultCode.C_SUCCESS|| ret.Data==null)
            {
                return new ApiResult(ResultCode.C_INVALID_ERROR, "账户不存在，续费失败");
            }            
            var client = CreateHttpClient();           
            var map = new Dictionary<string, string>(){
                {"user",account },   
                {"serverid",packageKey },
                {"type","buy" },               
            };
            var title = GetOpTitle("NewReAccount", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.GetAsync(this.UserApiUrl + "?" + this.FormatRequest(map));
                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);
                }
                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<bool> DeleteAccount(string account)
        {
            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 client = CreateHttpClient();           
            var title = GetOpTitle("GetAccountInfo", account);

            
            var info = "";
            try
            {
                //账号信息
                var resp_info = await client.GetAsync("/userapi/?secretId=20200716182518182489&secretKey=OFcEJAfzYjWT3e2s&type=getuserinfo&user="+account);
                var content_info = await resp_info.Content.ReadAsStringAsync();

                JObject jo = (JObject)JsonConvert.DeserializeObject(content_info);
                var status = jo["code"].ToString();



                var trData = new OriginAccountModel
                {
                    Id = account,
                    Account = account,
                    Pwd = account,
                    AccountType = "",
                    Package = "",
                    ConnectCount = jo["logincount "].ToString(),
                    RegistTime = "",
                    EndTime = jo["expiretime "].ToString(),
                    RestTime = "",
                    Amount = "",
                    Remark = "",
                };
                trData.RealEndTime = DateTime.Parse(trData.EndTime);
                return new ApiResult<OriginAccountModel>(trData);
            }      
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message+"-->info:"+ info);
                return new ApiResult<OriginAccountModel>(ResultCode.C_INVALID_ERROR, "查询失败");
            }

            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 client = CreateHttpClient();          
            var map = new Dictionary<string, string>(){
                   {"user",account },
                   {"new_pwd",pwd },
                   {"type","setuser" }, 
            };
            var title = GetOpTitle("UpdateAccountPwd", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.GetAsync(this.UserApiUrl + "?" + this.FormatRequest(map));
                var content = await resp.Content.ReadAsStringAsync();
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                var status = jo["code"].ToString();
                if (status == "1")
                {
                    return true;
                }
                else
                {
                    LogHelper.Error(title, content);
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(GetOpTitle("UpdateAccountPwd", account), ex);
            }
            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 url1 = "http://user.webok.me/userapi3/?secretId=20200716182518182489&secretKey=OFcEJAfzYjWT3e2s&type=buy_log&user="+account+"&page=1";

            System.Net.WebRequest wrq = System.Net.WebRequest.Create(url1);
            wrq.Method = "GET";
            System.Net.WebResponse wrp = wrq.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
            var strResult = sr.ReadToEnd();
        
            JObject jo1 = (JObject)JsonConvert.DeserializeObject(strResult);
            

            var id = jo1["data"][0]["id"].ToString();
            
            var url = "/userapi3/?secretId=20200716182518182489&secretKey=OFcEJAfzYjWT3e2s&type=refund&id="+id;

            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);
            }
            else
            {
                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 client = CreateHttpClient();
            var title = GetOpTitle("OnLine", account);

            var info = "";
            try
            {
                var url = this.OnlineUrl + account;
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                var retData = new List<OriginAccountOnlineModel>();
                if ((int)jo["code"] == 1)
                {
                    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 = jsondata["online_time"].ToString(),
                            OnlineTime = jsondata["online_time"].ToString(),
                            LoginIP = jsondata["client_ip"].ToString(),
                            UpStream = "",
                            DownStream = "",
                            Id= "{user:\""+account+"\",address:\""+jsondata["address"]+"\",server_ip:\""+jsondata["server_ip"]+"\"}",
                        };
                       
                        retData.Add(trData);
                    }
                }
                return new ApiResult<List<OriginAccountOnlineModel>>(retData);
                // return new ApiResult<List<OriginAccountOnlineModel>>(ResultCode.C_INVALID_ERROR, "查询失败");
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message + "-->info:" + info);
                return new ApiResult<List<OriginAccountOnlineModel>>(ResultCode.C_INVALID_ERROR, "查询失败");
            }
        }
        /// <summary>
        /// 踢号
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<bool> KillOut( string id)
        {
            var client = CreateHttpClient();
            var title = GetOpTitle("KillOut", id);
            JObject userinfo = (JObject)JsonConvert.DeserializeObject(id);



            var info = "";
            try
            {
                var url = string.Format(this.KIllUrl, userinfo["user"],userinfo["address"],userinfo["server_ip"]);
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                if((int)jo["code"] == 1)
                {
                    return true;
                }                                  
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message + "-->info:" + info);              
            }
            return false;
        }

        /// <summary>
        /// 是否存在
        /// </summary>      
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<bool> Exist(string account)
        {
            var client = CreateHttpClient();           
            var title = GetOpTitle("Exist", account);
            LogHelper.Info(title, account);


            string url = $"userapi3/?secretId={secretId}&secretKey={secretKey}&type=getuserlenNum&user={account}";
            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")
            {
                var count = jo["count"].ToInt();
                return count > 0;
            }
            else
            {
                return false;
            }           
        }
    }
}
