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 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
{
    //老鹰B组
    public class AgentClient3Service : AgentClientBaseService
    {
        string LoginUrl { get; set; } = "api/login";
        string LoginCodeUrl { get; set; } = "";
        string RefrushTokenUrl { get; set; } = "api/info?_=";
        string SingleAddUrl { get; set; } = "api/ppp/one";
        string ReAddUrl { get; set; } = "api/ppp/renewal";
        string MuiltAddUrl { get; set; } = "api/ppp/batch";
        string RefundUrl { get; set; } = "api/ppp/delete";
        string OnlineUrl { get; set; } = "api/ppp/oln?user={0}&_={1}";
        string GetAccount { get; set; } = "index.php/admin/users/users/grid/datagrid.html";
        string KIllUrl { get; set; } = "api/ppp/oln/stop";
        string UpdateUrl { get; set; } = "api/ppp/update";
        string DeleteAccountUrl { get; set; } = "api/ppp/delete?user=hl&_=1583126809671";
        string InfoUrl = "api/ppp?page=1&user=";
        string TestAddUrl { get; set; } = "api/addtestuser.html";
        IHttpClientFactory m_HttpClientFactory;       
        public AgentClient3Service(IHttpClientFactory httpClientFactory):base(httpClientFactory)
        {
            m_HttpClientFactory = httpClientFactory;
        } 

        public override async Task<int> RefrushStatus()
        {
            
            return 1;
        }
    

        public override async Task<ApiResult> Login(AgentLoginRequest request)
        {
            var client = CreateHttpClient(false);

            var map = new Dictionary<string, string>(){
                {"username",request.Account },
                {"password",request.Pwd },
                {"autologon","false"},
            };
            LogHelper.Info("Login", map.ToJson());              
            var resp = await client.PostAsForm(this.LoginUrl, map);
            var content = await resp.Content.ReadAsStringAsync();
            if (content.IndexOf("登陆成功")!= -1)
            {
                request.Key = this.GetCookie(resp, "_dailissid");
                return new ApiResult(request.Key);               
            }
            return new ApiResult(ResultCode.C_VISITOR_CHECKING, "登录失败");
        }
        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 == "free")
                return await NewTestAccount(account, pwd);
            var client = CreateHttpClient();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/memberAdd.html?username="+account+"&password="+pwd+"&tel=13073735878&realName=万勇强&idCard=410325199407079912&taocanName="+packageKey+"&maxonline="+connCount+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                Console.WriteLine("=====================================新开================================================");
                Console.WriteLine(jo);
                Console.WriteLine("=====================================================================================");
                var status = jo["code"].ToString();
                if (status == "1")
                {
                    return new ApiResult(ResultCode.C_SUCCESS);
                }
                else
                {
                    return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");
                }
            }
            catch (Exception ex)
            {
                return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");
            }
        }


        public async Task<ApiResult> NewTestAccount(string account, string pwd)
        {
            var client = CreateHttpClient();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/addtestuser.html?username="+account+"&password="+pwd+"&tel=13073735878&realName=万勇强&idCard=410325199407079912&maxonline=1&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                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);
                }
                else
                {
                    return new ApiResult(ResultCode.C_INVALID_ERROR, "开户失败");
                }
            }
            catch (Exception ex)
            {
                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>(){                
                 {"user",account },
                 {"passwd",pwd },
                 {"form",startNum.ToString() },
                 {"to",endNum.ToString() },             
                 {"type",packageKey },
                 {"conn_max",connCount.ToString() },
                 {"paynum","1" },
                 {"details","hl" },
            };
            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("开户成功") != -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 client = CreateHttpClient();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/taocanBuy.html?username="+account+"&taocanName="+packageKey+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                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(content);
                Console.WriteLine("=====================================================================================");
                if (status == "1")
                {
                    return new ApiResult(ResultCode.C_SUCCESS);
                }
                else
                {
                    return new ApiResult(ResultCode.C_INVALID_ERROR, "续费失败");
                }
            }
            catch (Exception ex)
            {
                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 map = new Dictionary<string, string>(){
                 {"usernames",account }
            };
            LogHelper.Info(GetOpTitle("DeleteAccount", account), map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.SingleAddUrl, map);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("删除成功") != -1)
                {
                    return true;
                }
                else
                {
                    LogHelper.Error(GetOpTitle("DeleteAccount", account), content);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(GetOpTitle("DeleteAccount", account), ex);
            }
            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)
        {

            var client = CreateHttpClient();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/getUserinfo.html?username="+account+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                Console.WriteLine("=======================================信息==============================================");
                Console.WriteLine(content);
                Console.WriteLine("=====================================================================================");
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                
                var trData = new OriginAccountModel
                {
                    Account = account,
                    AccountType = jo["active"].ToString(),
                    Package ="",
                    EndTime =jo["expiredate"].ToString(),
                    ConnectCount = jo["maxonline"].ToString(),                 
                };
                trData.RealEndTime = DateTime.Parse(trData.EndTime);

                var restDay = (trData.RealEndTime - DateTime.Now).Days;
                restDay = restDay < 0 ? 0 : restDay;
                if (restDay <= 1) trData.Package = "天";
                else if(restDay <= 7) trData.Package = "周";
                else trData.Package = "月";
                return new ApiResult<OriginAccountModel>(trData);
            }
            catch (Exception ex)
            {
                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();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/updatePW.html?username="+account+"&newpwd="+pwd+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                Console.WriteLine("=====================================修改密码================================================");
                Console.WriteLine(content);
                Console.WriteLine("=====================================================================================");
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                var status = jo["code"].ToString();
                if (status == "1")
                {
                    return true;
                }
                else
                {
                    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 client = CreateHttpClient();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/refundAct.html?username="+account+"&refundReason=api&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                Console.WriteLine("=======================================退款==============================================");
                Console.WriteLine(content);
                Console.WriteLine("=====================================================================================");
                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, "退款失败");
                }
            }
            catch (Exception ex)
            {
                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();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/radiusOnline.html?username="+account+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                Console.WriteLine("====================================在线=================================================");
                Console.WriteLine(content);
                Console.WriteLine("=====================================================================================");
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                var retData = new List<OriginAccountOnlineModel>();
                var status = jo["code"].ToString();
                if (status == "1")
                {

                    var trData = new OriginAccountOnlineModel
                        {
                            Account = account,
                            OnLine = 1,
                            LoginIP = jo["callingstationid"].ToString(),
                            ServerIP=jo["nasipaddress"].ToString(),
                            LoginTime=jo["acctstarttime"].ToString(),
                            OnlineTime=jo["acctsessiontime"].ToString(),
                            Id = jo["radacctid"].ToString()
                        };
                        
                        retData.Add(trData);
                    return new ApiResult<List<OriginAccountOnlineModel>>(retData);

                    // foreach (var tr in jo["data"])
                    // {
                    //     JObject jsondata = (JObject)JsonConvert.DeserializeObject(tr.ToJson());
                    //     Console.WriteLine("==========================================================");
                    //     Console.WriteLine(jsondata["callingstationid"].ToString());
                    //     Console.WriteLine("==========================================================");

                    //     var trData = new OriginAccountOnlineModel
                    //     {
                    //         Account = account,
                    //         OnLine = 1,
                    //         LoginIP = jsondata["callingstationid"].ToString(),
                    //         ServerIP=jsondata["nasipaddress"].ToString(),
                    //         LoginTime=jsondata["acctstarttime"].ToString(),
                    //         OnlineTime=jsondata["acctsessiontime"].ToString(),
                    //         Id = jsondata["radacctid"].ToString()
                    //     };
                        
                    //     retData.Add(trData);
                    // }

                      
                    // return new ApiResult<List<OriginAccountOnlineModel>>(retData);
                }
                else
                {
                    return new ApiResult<List<OriginAccountOnlineModel>>(retData);
                }
            }
            catch (Exception ex)
            {
                return await base.OnLine(account);
            }

        }
        /// <summary>
        /// 踢号
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<bool> KillOut( string id)
        {
            var client = CreateHttpClient();

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/disConnect.html?radacctid="+id+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            try
            {
                var resp = await client.GetAsync(url);
                var content = await resp.Content.ReadAsStringAsync();
                Console.WriteLine("=================================踢号====================================================");
                Console.WriteLine(content);
                Console.WriteLine("=====================================================================================");
                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                var status = jo["code"].ToString();
                if (status == "1")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(GetOpTitle("KillOut", id), ex);
            }
            return false;

        }

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

            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next();
            var time_s = DateTime.Now.GetUnixTimeStamp();
            var nonce =  MD5(time_s.ToString()) + i.ToString();
            var sign = MD5(nonce+"pptpm8dr8kj3");
            var url = "/gapi/userExist.html?username="+account+"&agentOrigin=admin1&nonce="+nonce+"&sign="+sign;

            var resp = await client.GetAsync(url);
            var content = await resp.Content.ReadAsStringAsync();
            if (content == "1")
            {
                return true;
            }
            else
            {
                return false;
            }           
        }
    }
}
