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
{
    //老鹰A组
    public class AgentClient2Service : AgentClientBaseService
    {
        string LoginUrl { get; set; } = "index.php/admin/index/login.html";
        string LoginCodeUrl { get; set; } = "main/imgcode.html";
        string RefrushTokenUrl { get; set; } = "index.php/admin/index/public_welcome.html";// "";
        string SingleAddUrl { get; set; } = "index.php/admin/users/useradd.html";
        string SingleReAddUrl { get; set; } = "index.php/admin/users/userrenew.html";
        string MuiltAddUrl { get; set; } = "index.php/admin/users/usersadd.html";
        string RefundUrl { get; set; } = "index.php/admin/users/userrefund.html";
        string OnlineUrl { get; set; } = "";
        string GetAccount { get; set; } = "index.php/admin/users/users/grid/datagrid.html";
        string KIllUrl { get; set; } = "index.php/admin/users/useroffline.html";
        string UpdateUrl { get; set; } = "index.php/admin/users/useredit.html";
        string DeleteAccountUrl { get; set; } = "index.php/admin/users/userdelete.html";
        string searchAccountUrl = "index.php/admin/users/users/grid/datagrid.html";
        string existCheckUrl = "index.php/admin/users/public_checkusername.html";
        string refrushCookie = "admin/Common/getCookie";
        string sessionlife = "index.php/admin/index/public_sessionlife.html";
        IHttpClientFactory m_HttpClientFactory;       
        public AgentClient2Service(IHttpClientFactory httpClientFactory):base(httpClientFactory)
        {
            m_HttpClientFactory = httpClientFactory;
        } 

        public  async Task<int> RefrushStatus1()
        {
            int status = 0;
            if (this.Token.Has())
            {
                var client = CreateHttpClient();
                if (this.RefrushTokenUrl.Has())
                {                   
                    var getResp = await client.GetAsync(this.RefrushTokenUrl);
                    var content = await getResp.Content.ReadAsStringAsync();
                    if (getResp.StatusCode == HttpStatusCode.OK && content.IndexOf("正常登录") == -1)
                    {
                        status = 1;
                    }
                    else
                    {                     
                        Debug.WriteLine("离线");
                        Debug.WriteLine(content);
                    }
                }
            }
            return status;
        }

        public override async Task<int> RefrushStatus()
        {
            var map = new Dictionary<string, string>(){
                {"key","1" }
            };
            int status = 0;
            var client = CreateHttpClient();
            client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
            var getResp = await client.PostAsForm(this.sessionlife, map);
            var content = await getResp.Content.ReadAsStringAsync();
            content= System.Text.RegularExpressions.Regex.Unescape(content);           
            if (getResp.StatusCode == HttpStatusCode.OK && content.IndexOf("登录后台") == -1)
            {
                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("离线");
            //    }
            //}
            client.DefaultRequestHeaders.Remove("X-Requested-With");
            return status;
        }


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

        public override async Task<ApiResult> Login(AgentLoginRequest request)
        {
            var client = CreateHttpClient(false);   
            var map = new Dictionary<string, string>(){
                {"managername",request.Account },
                {"password",request.Pwd },
           //     {"authnum",request.Code },
            };
            LogHelper.Info("Login", map.ToJson());
            request.Key = await GetHomeCookie();         
            AddCookie(client, request.Key);          
            var resp = await client.PostAsForm(this.LoginUrl, map);
            var content = await resp.Content.ReadAsStringAsync();
            if (content.IndexOf("index.html") == -1)
            {
                return new ApiResult(ResultCode.C_VISITOR_CHECKING, "登录失败");
            }
            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)
        {
            var client = CreateHttpClient();    
            var map = new Dictionary<string, string>(){
                 {"info[groupid]","2001" },
                 {"info[srvid]","6" },
                 {"info[username]",account },
                 {"info[password]",pwd },
                 {"info[cycle]",packageKey },
                 {"info[simuse]",connCount.ToString() },
                 {"info[usetime]","1" },
                 {"info[tryuse]",accountType==1?"0":"1"},
            };
            var title = GetOpTitle("NewAccount", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.SingleAddUrl, 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="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>(){
                 {"info[groupid]","2001" },
                 {"info[srvid]","6" },
                 {"info[username_header]",account },
                 {"info[username_start]",startNum.ToString() },
                 {"info[username_end]",endNum.ToString() },
                 {"info[pwdtype]","0" },
                 {"info[password]",pwd },
                 {"info[repassword]",pwd },
                 {"info[cycle]",packageKey },
                 {"info[simuse]",connCount.ToString() },
                 {"info[usetime]","1" },
                 {"info[tryuse]","0" },
            };
            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();     
            Dictionary<string, int> priceMap = new Dictionary<string, int>()
            {
                {"daycardprice",3},
                {"weekcardprice",15},
                {"monthcardprice",60},
            };
            var price = priceMap[packageKey];
            var totalAmount = price * connCount;
            var map = new Dictionary<string, string>(){
                 {"info[username]",account },
                 {"info[cycle]",packageKey },
                 {"info[simuse]",connCount.ToString()},
                 {"info[usetime]","1" },
                 {"info[usemoney]",totalAmount.ToString() },
            };
            var title = GetOpTitle("NewReAccount", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.SingleReAddUrl, 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>
        /// <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();
            var map = new Dictionary<string, string>(){
                 {"search[username]",account },
                 {"page","1" },
                 {"rows","25" },
            };
            var title = GetOpTitle("GetAccountInfo", account);
            try
            {
                var content = await client.PostAsFormGetString(this.searchAccountUrl, map);

                JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                var rows = jo["rows"].ToArray();
                var row = rows.FirstOrDefault();
                var trData = new OriginAccountModel
                {
                    User = row["groupname"].ToString(),
                    Account = row["username"].ToString(),
                    AccountType = row["username"].ToString(),
                    Package = row["cycle"].ToString(),
                    RegistTime = row["createdon"].ToString(),
                    EndTime = row["expiration"].ToString(),
                    ConnectCount = row["simuse"].ToString(),
                    Pwd=row["open_password"].ToString(),
                    //  Amount = row["cycle"].ToString(),
                    RestTime = row["havetime"].ToString(),
                    IsActive = row["status"].ToString(),
                    Remark = row["comment"].ToString(),
                    OnLine = row["status"].ToString().IndexOf("在线") == -1 ? 0 : 1,
                    LoginTime= row["acctstarttime"].ToString(),
                    LoginServer= row["nasipaddress"].ToString(),
                };
                trData.RealEndTime = DateTime.Parse(trData.EndTime);
                return new ApiResult<OriginAccountModel>(trData);
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message);
                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>(){
                 {"info[groupid]","2001" },
                 {"info[srvid]","6" },
                 {"info[username]",account },
                 {"info[password]",pwd },              
            };

            LogHelper.Info(GetOpTitle("UpdateAccountPwd", account), map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.UpdateUrl, map);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("修改成功") != -1)
                {
                    return true;
                }
                else
                {
                    LogHelper.Error(GetOpTitle("UpdateAccountPwd", account), content);
                }
            }
            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();
            var map = new Dictionary<string, string>(){
                {"info[username]",account },
                {"info[cycle]",packageKey },
                {"info[expiretime]",days.ToString() },
            };
            var title = GetOpTitle("Refund", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.RefundUrl, 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>
        /// <returns></returns>
        public override async Task<ApiResult<List<OriginAccountOnlineModel>>> OnLine(string account)
        {
            var accountInfo =await this.GetAccountInfo(account, false);
            if (accountInfo.Code != ResultCode.C_SUCCESS) return await base.OnLine(account);

            var list = new List<OriginAccountOnlineModel>();
            if (accountInfo.Data.OnLine == 1)
            {
                list.Add(new OriginAccountOnlineModel()
                {
                    Account = account,
                    OnLine = accountInfo.Data.OnLine,
                    Id = account,
                    LoginTime= accountInfo.Data.LoginTime,
                    LoginIP= accountInfo.Data.LoginServer
                });
            }
            return new ApiResult<List<OriginAccountOnlineModel>>(list);      
        }
        /// <summary>
        /// 踢号
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="account">账号</param>
        /// <returns></returns>
        public override async Task<bool> KillOut( string account)
        {
            var client = CreateHttpClient();
            client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
            var map = new Dictionary<string, string>(){
                {"usernames",account },               
            };
            var title = GetOpTitle("KillOut", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.KIllUrl, map);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("次踢人操作") != -1)
                {
                    return true;
                }
                else
                {
                    LogHelper.Error(title, content);                  
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message);           
            }
            return false;
        }

        /// <summary>
        /// 是否存在
        /// </summary>      
        /// <param name="account"></param>
        /// <returns></returns>
        public override async Task<bool> Exist(string account)
        {
            var client = CreateHttpClient();
            var map = new Dictionary<string, string>(){
                {"username",account }
            };
            var title = GetOpTitle("Exist", account);
            LogHelper.Info(title, map.ToJson());
            try
            {
                var resp = await client.PostAsForm(this.existCheckUrl, map);
                var content = await resp.Content.ReadAsStringAsync();
                if (content.Has() && content.IndexOf("false") != -1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(title, ex.Message);
                return false;
            }
        }
    }
}
