using dodohold.core;
using System.Net;

namespace molilian.core
{
    public partial class AlimamaPlus
    {
        /// <summary>
        /// 获取可提现余额
        /// </summary>
        public void GetDrawBalance()
        {
            DateTime date = DateTime.Now.AddDays(-1);
            TkPoolDTO result = new TkPoolDTO();
            try
            {
                string t = $"{date.Convert2UnixTimestamp(true)}";
                string dt = date.ToString("yyyy-MM-dd");

                string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/settle.account.balance.get.json?" +
                    $"t={t}&_tb_token_={_tb_token}";

                var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                            .AddHeaders("X-Requested-With", "XMLHttpRequest")
                            .AddHeaders("Cookie", _cookies);
                client.Proxy = _proxy;
                if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                var response = client.Request(url);

                var body = response.Body();
                var root = body.Convert2JsonElement();

                int resultCode = root.Read<int>("resultCode", 0);
                bool success = root.Read("success", false);
                if (!success)
                {
                    _ = new LoggerLibrary("account", "error")
                        .Info(url, body)
                        .SaveAsync();
                    throw new Exception(body);
                }

                var drawBalance = root.PathRead<decimal>("data.totalBalance", 0);
                TkPoolCore.UpdateDrawBalance(_accountName, drawBalance);
            }
            catch (Exception ex) { }
        }


        public (bool, string) RenewCookie()
        {
            string cache_key = $"cache:tk_pool:{_accountName}:RenewCookie";
            long count = RedisHelper.IncrBy(cache_key);
            RedisHelper.Expire(cache_key, 30);
            if (count > 1) return (true, "前一个cookie续签正在执行中");

            try
            {
                {
                    string url = "https://pub.alimama.com/common/getUnionPubContextInfo.json";
                    var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                                .AddHeaders("X-Requested-With", "XMLHttpRequest")
                                .AddHeaders("Cookie", _cookies);
#if DEBUG
#else
                    client.Proxy = _proxy;
#endif
                    if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                    var response = client.Request(url);
                    var body = response.Body();
                }
                /*
{"invalidKey":null,"info":{"ok":true,"message":null},"data":{"noLogin":true,"ip":"121.206.54.236","loginUrlPrefix":"http://www.alimama.com/member/login.htm?forward=","env":"product"},"ok":true}                 */
                {

                    string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.userLoginInfo.get";
                    var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                                .AddHeaders("X-Requested-With", "XMLHttpRequest")
                                .AddHeaders("Cookie", _cookies);
#if DEBUG
#else
                    client.Proxy = _proxy;
#endif
                    if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                    var response = client.Request(url);
                    var body = response.Body();
                    var body2 = body;
                }

                {
                    string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.login";
                    var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                                .AddHeaders("X-Requested-With", "XMLHttpRequest")
                                .AddHeaders("Cookie", _cookies);
#if DEBUG
#else
                    client.Proxy = _proxy;
#endif
                    if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                    var response = client.Request(url);
                    var body = response.Body();
                    var root = body.Convert2JsonElement();
                    /*
                     {"success":true,"model":{}}
                     */

                    bool success = root.PathRead<bool>("success", true);
                    string msgCode = root.PathRead("msgCode", string.Empty);
                    string msgInfo = root.PathRead("msgInfo", string.Empty);

                    if (!success)
                    {
                        _ = new LoggerLibrary("account", "error")
                            .Info(url, body)
                            .SaveAsync();
                        return (false, body);
                    }
                    //{"success":false,"msgInfo":"用户淘宝未登录","msgCode":"USER_TB_NOT_LOGIN"}
                }

                string aso_url;
                {
                    string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.auto.signIn.mama.url.get";
                    var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                                .AddHeaders("X-Requested-With", "XMLHttpRequest")
                                .AddHeaders("Cookie", _cookies);
#if DEBUG
#else
                    client.Proxy = _proxy;
#endif
                    if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                    var response = client.Request(url);
                    var body = response.Body();
                    /*
                     {"success":false,"msgInfo":"用户淘宝未登录","msgCode":"USER_TB_NOT_LOGIN"}
                    {"model":{"url":"https://www.alimama.com/aso/tvs?domain=taobao&sign_account=670430e31dbb7459635d7db887fbc39b&sign_time=1717670916&token=64616532303JDaxNfPy83okP3kLScwCkGiuMcyC4Pcyn92UtF465646233393431&target=6874747073JDaxNfPy83okP3kLScwCkGiuMcyC4PcynF6D&defaultLoginURL=https%3A%2F%2Flogin.taobao.com%2Fmember%2Flogin.jhtml%3Ffrom%3Dalimama"},"success":true}
                     */

                    var root = body.Convert2JsonElement();

                    aso_url = root.PathRead("model.url", string.Empty);
                    bool success = root.Read("success", false);
                    if (!success)
                    {
                        _ = new LoggerLibrary("account", "error")
                            .Info(url, body)
                            .SaveAsync();
                        return (false, body);
                    }
                }

                {

                    var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                                 .AddHeaders("X-Requested-With", "XMLHttpRequest")
                                  .AddHeaders("Cookie", _cookies);
#if DEBUG
#else
                    client.Proxy = _proxy;
#endif
                    //client.AllowAutoRedirect = false;
                    if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                    var response = client.Request(aso_url);
                    List<Cookie> cookies_list = response.ResponseMessage.GetCookies();
                    var body = response.Body();
                }

                {
                    string url = "https://pub.alimama.com/common/getUnionPubContextInfo.json";
                    var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
                                .AddHeaders("X-Requested-With", "XMLHttpRequest")
                                .AddHeaders("Cookie", _cookies);
#if DEBUG
#else
                    client.Proxy = _proxy;
#endif
                    if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
                    var response = client.Request(url);
                    var body = response.Body();
                    /*
                     {"invalidKey":null,"info":{"ok":true,"message":null},"ok":true,"data":{"nnormalGradeLevel":3,"mmNick":"tb628735153169@alimama","hasHighCommPerm":1,"ip":"121.206.54.236","avatar":"//img.alicdn.com/bao/uploaded/i3/6000000006221/O1CN01S9dQzd1vpGrjjldrF_!!6000000006221-0-userheaderimgshow.jpg","userType":1,"env":"product","imgUrlPrefix":"//img.alicdn.com/tfscom","memberid":6172912691,"hasPubPermission":"1","newVersion":1}}
                     */
                }

                new DBContext.Table("tk_pool")
                    .Add("status", 1)
                    .Add("last_time", DateTime.Now)
                    .Where("name=@name", new { name = _accountName })
                    .Update();
                _ = TkPoolCore.List(true);

                NotifyCore.Notify(new NifyMessage
                {
                    message = $"【淘客{_accountId}:{_accountName}】cookie 续期",
                    tags = ["green_circle"]
                });
                EndPointCore.NotifyReload(true);
                //NotifyCore.AnPushNotify("Cookie更新", $"【淘宝联盟:{_accountName}】cookie 续期");

                return (true, string.Empty);
            }
            catch (Exception ex)
            {
                _ = new LoggerLibrary("account", "error")
                    .Info(ex.Message, ex.StackTrace)
                    .SaveAsync();

                string message = $"【cookie续期异常】{_accountName}\n\n{ex.Message}\n{ex.StackTrace}";
                NotifyCore.Notify(new NifyMessage
                {
                    message = message,
                    priority = NifyMessagePriority.high,
                    tags = ["red_circle"]
                });

                return (false, "cookie续期异常");
            }

        }

    }
}
