using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.ImageSearch20210501.Models;
using AlibabaCloud.SDK.ImageSearch20210501;
using Tea;
using dodohold.core;
using Environment = System.Environment;
using Topsdk.Top;
using Topsdk.Top.Defaultability;
using Topsdk.Top.Defaultability.Domain;
using Topsdk.Top.Defaultability.Request;
using Topsdk.Top.Defaultability.Response;


namespace molilian.core
{

    public partial class AliyunPlus
    {
        private static string _end_point;
        private static int _timeout = 5000;
        static AliyunPlus()
        {
            _end_point = Environment.GetEnvironmentVariable("IMG_EndPoint");
            if (string.IsNullOrEmpty(_end_point))
            {
#if DEBUG
                _end_point = "imagesearch.cn-shanghai.aliyuncs.com";
#else
                //_end_point = "imagesearch-vpc.cn-shanghai.aliyuncs.com";
                _end_point = "imagesearch.cn-shanghai.aliyuncs.com";
#endif
            }

        }


        public async Task<SearchByPicResponse> SearchByPicAsync(string base64String, string pid)
        {
            if (string.IsNullOrEmpty(base64String)) return null;
            if (string.IsNullOrEmpty(pid)) return null;

            try
            {
                byte[] bytes = Convert.FromBase64String(base64String);

                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new();

                Config config = new()
                {
                    AccessKeyId = _app_key,
                    AccessKeySecret = _app_secret,
                    Endpoint = _end_point,
                    ConnectTimeout = _timeout,
                    RegionId = "cn-shanghai"
                };
                Client client = new(config);
                SearchByPicAdvanceRequest request = new()
                {
                    PicContentObject = new MemoryStream(bytes),
                    Pid = pid,
                    Crop = true,
                    Num = 20,
                    Fields = "itemId,Url,CouponShareUrl,DeeplinkUrl,DeeplinkCouponShareUrl,UserType,ShopTitle,Title,PicUrl,ZkFinalPrice,ReservePrice,PriceAfterCoupon,CouponAmount,CouponStartTime,CouponEndTime,Volume,Provcity"
                };

                // 选填，需要返回的字段list。不同的字段用逗号分割。默认 PicUrl,ReservePrice,Title,Url,ZkFinalPrice
                // request.Fields = "Title,PicUrl,ReservePrice,ZkFinalPrice,UserType,Provcity,Nick,SellerId,Volume,LevelOneCategoryName,CategoryName,CouponTotalCount,CouponRemainCount,CouponStartTime,CouponEndTime,CouponStartFee,CouponAmount,CouponInfo,CommissionRate,CouponShareUrl,Url,ShopTitle";
                // 选填，图片类目
                //request.CategoryId = 88888888;
                // 选填，是否需要进行主体识别。默认true
                //request.Crop = false;

                // 选填，返回结果的起始位置。取值范围：0-499。默认值：0。
                //request.Start = 0;
                // 选填，返回结果的数目。取值范围：1-20。默认值：10。
                //request.Num = 2;

                // 选填，渠道ID。用于淘宝联盟中的渠道区分。
                //request.relationId = 1145;


                var response = await client.SearchByPicAdvanceAsync(request, runtime);
                return response;
            }
            catch (TeaException error)
            {
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                Console.WriteLine(error.Message);
                // 诊断地址
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);


                int.TryParse($"{error.DataResult["statusCode"]}", out int statusCode);
                SearchByPicResponse response = new();
                response.Body = new();
                response.Body.Success = false;
                response.Body.Code = statusCode;
                response.Body.Message = $"{error.DataResult["Code"]},{error.DataResult["Message"]}";


                LoggerLibrary log = new("SearchByPic", "tea");
                log.Info(error.Message);
                _ = log.SaveAsync();
                return response;
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                Console.WriteLine(error.Message);
                // 诊断地址
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);


                LoggerLibrary log = new("SearchByPic", "error");
                log.Info(error.Message);
                log.Info(error.Data["Recommend"].Convert2Json());
                _ = log.SaveAsync();


            }

            return null;
        }


        public async Task<GetProductInfoByIdsResponse> GetProductInfoByIds(string itemIds, string pid)
        {
            if (string.IsNullOrEmpty(itemIds)) return null;
            if (string.IsNullOrEmpty(pid)) return null;

            try
            {

                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new();

                Config config = new()
                {
                    AccessKeyId = _app_key,
                    AccessKeySecret = _app_secret,
                    Endpoint = _end_point,
                    ConnectTimeout = _timeout,
                    RegionId = "cn-shanghai"
                };
                Client client = new(config);
                GetProductInfoByIdsRequest request = new()
                {
                    ItemIds = itemIds,
                    Pid = pid,
                    Fields = "itemId,Title,Nick,SellerId,ShortTitle,ShopTitle,SubTitle,PicUrl,ReservePrice,ZkFinalPrice,PriceAfterCoupon,CouponTotalCount,CouponRemainCount,CouponStartTime,CouponEndTime,CouponStartFee,CouponAmount,CouponInfo,CommissionRate,CouponShareUrl,DeeplinkCouponShareUrl,Url,DeeplinkUrl"
                };

                var response = await client.GetProductInfoByIdsWithOptionsAsync(request, runtime);
                return response;
            }
            catch (TeaException error)
            {
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                Console.WriteLine(error.Message);
                // 诊断地址
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);


                int.TryParse($"{error.DataResult["statusCode"]}", out int statusCode);
                GetProductInfoByIdsResponse response = new();
                response.Body = new();
                response.Body.Success = false;
                response.Body.Code = statusCode;
                response.Body.Message = $"{error.DataResult["Code"]},{error.DataResult["Message"]}";


                LoggerLibrary log = new("GetProductInfoByIds", "tea");
                log.Info(error.Message);
                _ = log.SaveAsync();
                return response;
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                Console.WriteLine(error.Message);
                // 诊断地址
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);


                LoggerLibrary log = new("GetProductInfoByIds", "error");
                log.Info(error.Message);
                log.Info(error.Data["Recommend"].Convert2Json());
                _ = log.SaveAsync();
            }
            return null;
        }

    }

}