using dodohold.core;
using Sayaka.Common;
using System.Drawing.Printing;
using System.Text.Json;

namespace molilian.core
{
    public partial class PddUnionPlus
    {

        public async Task queryEstimateRevenueList(DateTime startTime, DateTime endTime, CancellationToken cancellationToken = default)
        {
            var ts = DateTime.Now.Convert2UnixTimestamp(true);
            string cookies = _account.cookies;

            bool hasNext = true;
            int pageNo = 1;
            int pageSize = 100;
            while (hasNext)
            {
                var args = new
                {
                    startTime = startTime.ToString("yyyy-MM-dd"),
                    endTime = endTime.ToString("yyyy-MM-dd"),
                    orderPromotionType = 0,
                    pageNumber = pageNo,
                    pageSize
                };

                DateTime stime = DateTime.Now;
                string url = "https://jinbao.pinduoduo.com/network/api/order/stat/overall/list";
                var root = await this.RequestAsync(url, args.Convert2Json());
                TimeSpan ts2 = DateTime.Now - stime;

                string xx = ts2.TotalSeconds.ToString();

                var success = root.Read<bool>("success");
                if (!success) break;
                var list = root.ElementRead("result").ElementRead("list");
                string filter = "accountId=@accountId AND report_date=@report_date AND pid=@pid";
                var len = list.GetArrayLength();
                if (len == 0) break;
                foreach (var item in list.EnumerateArray())
                {
                    var report = item.GetRawText().Convert2Object<PddEstimateRevenueDTO>();

                    var exist = new DBContext.Table("pdd_estimate_revenue")
                        .Fields("id")
                        .Get<dynamic>(filter, new { report_date = report.calcDate, accountId = _account.id, report.pid });

                    var update = new DBContext.Table("pdd_estimate_revenue")
                        .Add("accountId", _account.id)
                        .Add("accountName", _account.name)
                        .Add("report_date", report.calcDate)

                        .Add("pid", report.pid)
                        .Add("pidName", report.pidName)
                        .Add("orderNum", report.orderNum)
                        .Add("orderAmount", report.orderAmount)
                        .Add("feeAmount", report.feeAmount)
                        .Add("avgPrice", report.avgPrice)
                        .Add("mallRelFeeAmount", report.mallRelFeeAmount)
                        .Add("lockFeeAmount", report.lockFeeAmount)
                        .Add("last_time", DateTime.Now);

                    if (exist == null)
                    {
                        update.Add("report_date", report.calcDate)
                        .Add("create_time", DateTime.Now)
                        .Create(DBContext.InsertType.REPLACE);
                    }
                    else
                    {
                        update.Where("id=@id", new { exist.id }).Update();
                    }
                }

                pageNo++;
            }
        }

        public async Task<int> queryMallBalance(CancellationToken cancellationToken = default)
        {
            try
            {
                var ts = DateTime.Now.Convert2UnixTimestamp(true);
                string cookies = _account.cookies;

                DateTime stime = DateTime.Now;
                string url = "https://jinbao.pinduoduo.com/network/api/finance/mallBalance";
                var root = await this.RequestAsync(url);
                TimeSpan ts2 = DateTime.Now - stime;

                string xx = ts2.TotalSeconds.ToString();

                var success = root.Read<bool>("success");
                if (!success) throw new Exception(root.Convert2Json());
                var balanceAmount = root.PathRead<int>("result.balanceAmount");
                var withdrawalAmount = root.PathRead<int>("result.withdrawalAmount");


                return new DBContext.Table("pdd_pool")
                     .Add("draw_balance", withdrawalAmount * 0.001)
                     .Where("id=@id", new { _account.id })
                     .Update();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("43001:会话已过期"))
                {
                    PddPoolCore.CookieDisabled(_account.id);
                }
                string message = $"【PDD报表接口异常】{_account.id}:{_account.name}\tmallBalance\n{ex.Message}\n{ex.StackTrace}";
                NotifyCore.Notify(new NifyMessage
                {
                    message = message,
                    priority = NifyMessagePriority.high,
                    tags = ["red_circle"]
                });
            }
            return 0;
        }

        public async Task<JsonElement> RequestAsync(string url, string data = null, CancellationToken cancellationToken = default)
        {
            string cookies = _account.cookies.Trim();
            string useragent = ProviderFakeUserAgent.RandomComputer;

            WebClientUtility client = new WebClientUtility();
            client.Proxy = _proxy;
#if DEBUG
            client.Proxy = null;
#endif
            client.SetContentType("application/json");
            client.AddHeaders("Referer", "https://jinbao.pinduoduo.com/data/data-analysis");
            client.AddHeaders("Origin", "https://jinbao.pinduoduo.com");
            client.UserAgent = useragent;
            client.AddHeaders("Cookie", cookies);
            if (!string.IsNullOrEmpty(data)) client.Post(data);
            var response = await client.RequestAsync(url, string.IsNullOrEmpty(data) ? "GET" : "POST", cancellationToken);
            string body = response.Body();
            var root = body.Convert2JsonElement();

            //string message = string.Empty;
            // todo 这里我会做一些 日志 处理


            var success = root.Read<bool>("success");
            if (!success)
            {
                var errorCode = root.Read<int>("errorCode");
                var errorMsg = root.Read<string>("errorMsg");

                _ = new LoggerLibrary("PddUnion", "unsuccessful").Info(url, data).Info(body).SaveAsync();
                throw new APIException($"{errorCode}:{errorMsg}");
            }
            return root;
        }



    }
}
