using dodohold.core;
using System.Text.Json;
using System.Threading;
using Top.Api.Response;


namespace molilian.core
{
    public partial class TaokeOpenCore
    {
        static string _test_base64String = string.Empty;
        public TkConfigDTO _config;

        private static string _end_point;
        static TaokeOpenCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }

        public TaokeOpenCore()
        {
            _config = TkConfigCore.Get();
        }


        public async Task<APIResult> PromotionQueryAsync(string img, string oaid = "", string ip = "", bool recommand = true, bool debug = false)
        {
            PromotionQueryDTO result = new()
            {
                end_point = _end_point,
                ip = ip,
                oaid = oaid,
                img = img
            };
            if (string.IsNullOrEmpty(oaid))
            {
                result.success = false;
                result.message = "调用失败";
                result.reason = "无效OAID";
                _ = TkLogCore.PromotionImgLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                }, APIResultCodeEnum.OK, new JsonSerializerOptions
                {
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
            }

            if (string.IsNullOrEmpty(img))
            {
                result.success = false;
                result.message = "调用失败";
                result.reason = "无效图片";
                _ = TkLogCore.PromotionImgLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                }, APIResultCodeEnum.OK, new JsonSerializerOptions
                {
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
            }
            try
            {
                var account = TkPoolCore.GetOne(TkPoolCore.TkAction.promotionQuery);
                if (account == null)
                {
                    result.success = false;
                    result.message = "调用失败";
                    result.reason = "没有匹配账号";
                    _ = TkLogCore.PromotionImgLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.message,
                        result.reason,
                    }, APIResultCodeEnum.OK, new JsonSerializerOptions
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    });
                }


                TaobaoOpenPlus taobao = new(account.appkey, account.appSecret, account.open_pid, debug);
                int timeout = _config.similar_timeout;
#if DEBUG
                timeout = 5000;
#endif
                using var cts = new CancellationTokenSource();
                cts.CancelAfter(timeout);

                DateTime stime = DateTime.Now;

                var apiDelayTask = Task.Delay(500, cts.Token);
                var apiRequestTask = Task.Run(() =>
                {
                    return taobao.PromotionQueryRequest(img, oaid);

                }, cts.Token);

                TbkThorMfrsPromotionQueryResponse data;
                var apiCompletedTask = await Task.WhenAny(apiRequestTask, apiDelayTask);
                if (apiCompletedTask == apiRequestTask)
                {
                    data = await apiRequestTask;
                    if (data.IsError)
                    {
                        result.success = false;
                        result.message = "调用失败";
                        result.reason = data.ErrMsg;
                        _ = TkLogCore.PromotionImgLogAsync(result);
                        return new APIResult(new
                        {
                            result.success,
                            result.message,
                            result.reason,
                        }, APIResultCodeEnum.OK, new JsonSerializerOptions
                        {
                            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                        });
                    }
                    if (!"0".Equals(data.Status))
                    {
                        result.success = false;
                        result.message = "调用失败";
                        result.reason = data.Desc;
                        _ = TkLogCore.PromotionImgLogAsync(result);
                        return new APIResult(new
                        {
                            result.success,
                            result.message,
                            result.reason,
                        }, APIResultCodeEnum.OK, new JsonSerializerOptions
                        {
                            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                        });
                    }
                }
                else
                {

                }


                //500ms后再提交一次
                _ = Task.Run(() =>
                {
                    return taobao.PromotionQueryRequest(img, oaid);
                });


                var ts = DateTime.Now - stime;
                result.elapsedTime2 = (int)ts.TotalMilliseconds;


                //result.url = data.Url;
                result.url = $"https://mo.m.taobao.com/etao/search_pic_detail?appKey={account.appkey}&oaid={oaid}&pid={account.open_pid}";

                string cookies = string.Empty;
                var requestTask = Task.Run(async () =>
                {
                    if (recommand)
                    {
                        //DateTime stime = DateTime.Now;
                        //(result.PromotionImg, cookies) = await taobao.GetRecommendData(TaobaoOpenPlus.RecommendRequestType.ori, oaid, cookies, cts.Token);
                        //var ts = DateTime.Now - stime;
                        //result.elapsedTime4 = (int)ts.TotalMilliseconds;

                        var similarPromotionTask = taobao.GetRecommendDataWithRetry(TaobaoOpenPlus.RecommendRequestType.first, oaid, cookies, cts.Token);
                        var promotionImgTask = taobao.GetRecommendDataWithRetry(TaobaoOpenPlus.RecommendRequestType.ori, oaid, cookies, cts.Token);

                        await Task.WhenAll(similarPromotionTask, promotionImgTask);

                        (result.SimilarPromotion, cookies, result.elapsedTime3) = await similarPromotionTask;
                        (result.PromotionImg, cookies, result.elapsedTime4) = await promotionImgTask;
                    }
                    else
                    {
                        result.elapsedTime3 = 1;
                        (result.PromotionImg, cookies, result.elapsedTime4) = await taobao.GetRecommendDataWithRetry(TaobaoOpenPlus.RecommendRequestType.ori, oaid, cookies, cts.Token);
                    }
                    result.similarPromotion = result.SimilarPromotion.Convert2Json();
                    result.promotionImg = result.PromotionImg.Convert2Json();
                    return result;


                }, cts.Token);

                var delayTask = Task.Delay(timeout, cts.Token);
                var completedTask = await Task.WhenAny(requestTask, delayTask);
                if (completedTask == requestTask)
                {
                    result = await requestTask;
                }
                else
                {
                    //============================== 放弃转链-请求超时 ==============================
                    cts.Cancel();
                    result.success = false;
                    result.message = "调用失败";
                    result.reason = "请求超时";
                    if (!recommand) result.elapsedTime3 = 1;

                    _ = TkLogCore.PromotionImgLogAsync(result);
                    return new APIResult(new
                    {
                        result.success,
                        result.message,
                        result.reason,
                    }, APIResultCodeEnum.OK, new JsonSerializerOptions
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    });
                }


                //(result.SimilarPromotion, cookies) = await taobao.GetRecommendData(TaobaoOpenPlus.RecommendRequestType.first, oaid, cookies);
                //(result.PromotionImg, cookies) = await taobao.GetRecommendData(TaobaoOpenPlus.RecommendRequestType.ori, oaid, cookies);
                //result.similarPromotion = result.SimilarPromotion.Convert2Json();
                //result.promotionImg = result.PromotionImg.Convert2Json();

                result.success = true;
                result.message = "调用成功";
                _ = TkLogCore.PromotionImgLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                    similarPromotion = result.SimilarPromotion,
                    promotionImg = result.PromotionImg,
                    result.url,
                }, APIResultCodeEnum.OK, new JsonSerializerOptions
                {
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

            }
            catch (Exception ex)
            {
                result.success = false;
                result.message = "调用失败";
                result.reason = ex.Message;
                _ = TkLogCore.PromotionImgLogAsync(result);
                return new APIResult(new
                {
                    result.success,
                    result.message,
                    result.reason,
                }, APIResultCodeEnum.OK, new JsonSerializerOptions
                {
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
            }

        }

    }

}
