using dodohold.core;
using Spire.Pdf.Xmp;
using System.Data;
using System.Drawing.Printing;
using System.Text.Json;

namespace molilian.core
{
    public partial class AlimamaPlus
    {
        private const string base_bill_url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/new.settle.media.pre.income.daily.bill.detail.json";
        public int GetSettleBills(int sleep)
        {
            DateTime startTime = DateTime.Parse("2024-03-01");
            DateTime endTime = DateTime.Now;
            // 确保 startTime 小于 endTime
            if (startTime > endTime)
            {
                (startTime, endTime) = (endTime, startTime);
            }

            int pageNo = 1;
            string dataVersion = string.Empty;
            int pageSize = 20;

            bool hasNext = true;
            int total = 0;
            while (hasNext)
            {
                //        ?t=1717528348646&_tb_token_=576b361b883b8&pageNo=2&pageSize=20&endTime=2024-06-04&startTime=2024-05-05&dataVersion=20240603

                var ts = DateTime.Now.Convert2UnixTimestamp();
                string url = $"{base_bill_url}?t={ts}&_tb_token_={_tb_token}&pageNo={pageNo}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={endTime:yyyy-MM-dd}&dataVersion={dataVersion}";

                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);

                if (response.ResponseException != null)
                {
                    _ = new LoggerLibrary("api_error", "fail")
                        .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
                        .SaveAsync();
                    throw response.ResponseException;
                }
                var body = response.Body();
                JsonElement data;
                try
                {
                    var root = body.Convert2JsonElement();
                    var success = root.Read<bool>("success");
                    data = root.ElementRead("data");


                    //{"code":601,"info":{"ok":false,"message":"nologin"}}
                    if (!success && body.Contains("nologin"))
                    {
                        (success, string message) = RenewCookie();
                        if (!success)
                        {
                            TkPoolCore.Disabled(_accountId, _accountName, $"{body}");
                        }
                        return 0;
                    }

                    if (!success)
                    {
                        throw new APIException(body);
                    }
                }
                catch (Exception ex)
                {
                    throw new APIException(body);
                }
                using var conn = DBContext.GetOpenConnection();
                conn.Open();

                try
                {
                    foreach (var order in data.ElementRead("result").EnumerateArray())
                    {
                        TkSettleBillDTO item = order.GetRawText().Convert2Object<TkSettleBillDTO>();
                        // 处理每个订单数据 
                        item.accountId = _accountId;
                        item.accountName = _company;
                        int? id = conn.Replace(item);

                        total++;
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    conn.Dispose();
                }
                pageNo++;
                hasNext = data.Read<bool>("hasNext");
                dataVersion = data.Read<string>("dataVersion");

                if (sleep > 0) Thread.Sleep(sleep);
            }
            return total;
        }



    }
}
