using dodohold.core;
using Org.BouncyCastle.Ocsp;
using System.Text.RegularExpressions;


namespace molilian.core
{
    public partial class OtherApiPlus
    {

        private string _accountName;
        private string _key;
        private string _sessionKey;
        private string _style;
        private string _api_url;
        public OtherApiPlus(string accountName, string key, string sessionKey, string style, string api_url)
        {
            _accountName = accountName;
            _key = key;
            _sessionKey = sessionKey;
            _style = style;
            _api_url = api_url;
        }

        public TkDataDTO UnionParse(string content, ref TkDataDTO result)
        {
            string para = content.UrlEncode();
            string url = $"http://api.veapi.cn/tbk/hcapi?vekey={_key}&sessionkey={_sessionKey}&para={para}";

            var response = new WebClientUtility().Request(url);

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

            int error = root.Read<int>("error", 0);
            bool success = error == 0;
            string message = root.Read("msg", string.Empty);

            string taoToken = root.PathRead("data.ios_tbk_pwd", string.Empty);
            string num_iid = root.PathRead("data.num_iid", string.Empty);
            decimal couponAmount = root.PathRead<decimal>("data.coupon_amount", 0);

            string shortLinkurl = root.PathRead("data.coupon_short_url", string.Empty);

            string shortLink = AlimamaPlus.GetLink(taoToken);
            content = AlimamaPlus.ReplaceUrls(content, shortLink);

            if (!success)
            {
                shortLinkurl = AlimamaPlus.GetLink(content);
            }
            string deeplink_url = AlimamaPlus.GetDeeplink(shortLinkurl);


            result.channel = TkChannelEnum.tb;
            result.accountName = _accountName;
            result.success = success;
            result.message = message;
            result.content = content;
            result.couponAmount = couponAmount;
            result.taoToken = taoToken;
            result.shortLinkurl = shortLinkurl;
            result.deeplink_url = deeplink_url;
            result.num_iid = num_iid;
            return result;

        }


        public PromotionQueryDTO picSimilaritem(string pic, ref PromotionQueryDTO result)
        {
            string url = $"http://api.veapi.cn/tbk/picsimilaritem";

            string base64 = $"data:image/jpeg;base64,{pic}";

            var client = new WebClientUtility();
            client.SetContentType("application/x-www-form-urlencoded");
            client.Post("vekey", _key);
            client.Post("pic", base64);
            var response = client.Request(url);




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

            int error = root.Read<int>("error", 0);
            bool success = error == 0;
            string message = root.Read("msg", string.Empty);


            result.success = success;
            if (!success)
            {
                result.message = "调用失败";
                result.reason = message;
                return result;
            }

            List<PromotionQueryItemDTO> arr = [];

            var list = root.ElementRead("data");
            foreach (var e in list.EnumerateArray())
            {
                var item = e.ElementRead("Result");
                string itemId = item.Read<string>("ItemId", string.Empty);
                string h5_url = $"https://uland.taobao.com/item/edetail?id={itemId}";
                string deeplink_url = AlimamaPlus.GetDeeplink(h5_url);

                PromotionQueryItemDTO newItem = new PromotionQueryItemDTO();
                newItem.itemId = itemId;
                newItem.h5_url = h5_url;
                newItem.deeplink_url = deeplink_url;
                newItem.userType = item.Read<string>("UserType", string.Empty);
                newItem.shopTitle = item.Read<string>("ShopTitle", string.Empty);
                newItem.itemName = item.Read<string>("Title", string.Empty);
                newItem.pic = item.Read<string>("PicUrl", string.Empty);
                newItem.price = item.Read<string>("ReservePrice", string.Empty);
                newItem.zkFinalPrice = item.Read<string>("ZkFinalPrice", string.Empty);
                newItem.promotionPrice = item.Read<string>("PriceAfterCoupon", string.Empty);
                newItem.couponAmount = item.Read<string>("CouponAmount", string.Empty);
                newItem.couponEffectiveStartTime = item.Read<string>("CouponStartTime", string.Empty);
                newItem.couponEffectiveEndTime = item.Read<string>("CouponEndTime", string.Empty);
                newItem.sellCountStr = item.Read<string>("sellCountStr", string.Empty);
                newItem.provcity = item.Read<string>("Provcity", string.Empty);
                newItem.exposeTracks = $"https://api.molilian.com/tracks/track?track_id=7&unique_id={itemId}";
                newItem.clickTracks = $"https://api.molilian.com/tracks/track?track_id=8&unique_id={itemId}";

                arr.Add(newItem);
            }

            result.message = "OK";
            result.reason = string.Empty;
            result.PromotionImg = arr;




            //PromotionImg

            /*
             * 
        public string h5_url { get; set; } = string.Empty;
        public string deeplink_url { get; set; } = string.Empty;
        /// <summary>
        /// 店铺信息-卖家类型：1天猫，0淘宝,3淘特
        /// </summary>
        public string userType { get; set; } = string.Empty;
        public string shopTitle { get; set; } = string.Empty;
        public string itemId { get; set; } = string.Empty;
        public string itemName { get; set; } = string.Empty;
        public string pic { get; set; } = string.Empty;
        public string price { get; set; } = string.Empty;
        public string promotionPrice { get; set; } = string.Empty;
        public string couponAmount { get; set; } = string.Empty;
        public string couponEffectiveStartTime { get; set; } = string.Empty;
        public string couponEffectiveEndTime { get; set; } = string.Empty;
        public string sellCountStr { get; set; } = string.Empty;
        public string provcity { get; set; } = string.Empty;



{
	"error": "0",
	"msg": "查询成功",
	"data": [
		{
			"RankScore": "0.8065",
			"Result": {
				"CategoryName": "跑步鞋",
				"CommissionRate": "135",
				"CouponAmount": 50,
				"CouponEndTime": "2025-01-31",
				"CouponInfo": "满99.0元减50.0元",
				"CouponRemainCount": 99656,
				"CouponStartFee": "99.0",
				"CouponStartTime": "2024-12-24",
				"CouponTotalCount": "100000",
				"ItemId": "jOZk7gxcAfJZ6zGz8bFKjwSJte-Z9Z023UAg5djJmJSRp",
				"LevelOneCategoryName": "运动鞋new",
				"MaxCommission": {},
				"Nick": "",
				"PicUrl": "https://img.alicdn.com/i2/1994113638/O1CN015M0Aqf1ckFs5UI2eJ_!!0-item_pic.jpg",
				"PriceAfterCoupon": "109.00",
				"Provcity": "福建 泉州",
				"ReservePrice": "259.00",
				"SellerId": "1994113638",
				"ShopTitle": "361度户外旗舰店",
				"ShortTitle": "加绒保暖老爹鞋361女鞋运动鞋女",
				"SubTitle": "新款加绒女鞋运动鞋",
				"Title": "361女鞋运动鞋女2024冬季新款加绒保暖棉鞋轻便老爹鞋休闲跑步鞋",
				"UserType": 1,
				"Volume": 10,
				"ZkFinalPrice": "159"
			}
		}
    ]
	],
	"request_id": "4eZfpBu"
}
             */



            return result;

        }
        public async Task<TkDataDTO> UnionParseAsync(string content, string pid, TkDataDTO result, CancellationToken cancellationToken)
        {
            switch (_style)
            {
                case "ddx":
                    return await DdxParseAsync(content, pid, result, cancellationToken);
                case "veapi":
                default:
                    return await VeapiParseAsync(content, pid, result, cancellationToken);
            }
        }
        private async Task<TkDataDTO> VeapiParseAsync(string content, string pid, TkDataDTO result, CancellationToken cancellationToken)
        {
            string para = content.UrlEncode();
            string url = $"http://api.veapi.cn/tbk/generalconvert?vekey={_key}&para={para}&pid={pid}";
            if (!string.IsNullOrEmpty(_api_url))
            {
                url = _api_url;
                url = url.Replace("{apikey}", _key);
                url = url.Replace("{pid}", pid);
                url = url.Replace("{content}", para);
            }

            var response = await new WebClientUtility().RequestAsync(url, "GET", cancellationToken);

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

            int error = root.Read<int>("error", 0);
            bool success = error == 0;
            string message = root.Read("msg", string.Empty);
            var data = root.ElementRead("data");
            result.channel = TkChannelEnum.tb;
            result.accountName = _accountName;

            result.success = success;
            result.message = message;


            if (success)
            {
                result.content = content;
                result.message = string.Empty;
                result.commercial = true;

                result.couponAmount = data.Read<decimal>("coupon_amount", 0);
                result.mktId = data.Read<string>("isv_mktid", string.Empty);

                result.itemId = data.Read<string>("item_id", string.Empty);
                result.itemId = content.GetContentPart("item.htm?id=", "");
                // veapi 缺少商品pic 和 promotionPrice

                result.taoToken = data.Read<string>("cps_full_tpwd", string.Empty);

                result.item_url = AlimamaPlus.GetLink(result.taoToken);
                result.item_deeplink_url = AlimamaPlus.GetDeeplink(result.shortLinkurl);

                string coupon_full_tpwd = data.Read<string>("coupon_full_tpwd", string.Empty);
                if (!string.IsNullOrEmpty(coupon_full_tpwd)) result.taoToken = coupon_full_tpwd;

                result.shortLinkurl = AlimamaPlus.GetLink(result.taoToken);
                result.deeplink_url = AlimamaPlus.GetDeeplink(result.shortLinkurl);
                result.itemName = result.taoToken.GetContentPart(result.shortLinkurl, "").Trim();

                return result;
            }
            else
            {
                result.message = "转链失败";
                result.reason = message;
            }
            return result;

        }

        private async Task<TkDataDTO> DdxParseAsync(string content, string pid, TkDataDTO result, CancellationToken cancellationToken)
        {
            string para = result.rawContent.UrlEncode();
            string url = $"https://api.tbk.dingdanxia.com/tbk/tkl_privilege?apikey={_key}&pid={pid}&relation_id=3197256735&activityId=&extspk=&tb_auth_id=&tkl=XXX+{para}";
            if (!string.IsNullOrEmpty(_api_url))
            {
                url = _api_url;
                url = url.Replace("{apikey}", _key);
                url = url.Replace("{pid}", pid);
                url = url.Replace("{content}", para);
            }

            var client = new WebClientUtility();

#if DEBUG
            var response = await client.RequestAsync(url, "GET");
#else
            var response = await client.RequestAsync(url, "GET", cancellationToken);
#endif

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

            int code = root.Read<int>("code", 0);
            bool success = code == 200;
            string message = root.Read("msg", string.Empty);
            if (message.StartsWith("数据返回失败【"))
            {
                message = message.GetContentPart("数据返回失败【", "】");
            }

            var data = root.ElementRead("data");
            result.channel = TkChannelEnum.tb;
            result.accountName = _accountName;

            result.success = success;
            result.message = message;

            if (success)
            {
                result.content = content;
                result.message = string.Empty;
                result.commercial = true;

                result.couponAmount = data.Read<decimal>("coupon", 0);
                result.couponEffectiveStartTime = data.Read<string>("coupon_start_time", string.Empty);
                result.couponEffectiveEndTime = data.Read<string>("coupon_end_time", string.Empty);

                result.mktId = data.Read<string>("item_id", string.Empty);
                result.itemId = content.GetContentPart("item.htm?id=", "");


                result.pic = data.PathRead<string>("itemInfo.pict_url", string.Empty);
                result.sellerNickName = data.PathRead<string>("itemInfo.nick", string.Empty);
                result.promotionPrice = data.PathRead<decimal>("itemInfo.qh_final_price", 0);
                if (result.promotionPrice == 0)
                {
                    result.promotionPrice = data.PathRead<decimal>("itemInfo.zk_final_price", 0);
                }

                result.taoToken = data.Read<string>("long_item_tpwd", string.Empty);
                //string long_coupon_tpwd = data.Read<string>("long_coupon_tpwd", string.Empty);
                //if (!string.IsNullOrEmpty(long_coupon_tpwd)) result.taoToken = long_coupon_tpwd;

                result.shortLinkurl = AlimamaPlus.GetLink(result.taoToken);
                result.itemName = result.taoToken.GetContentPart(result.shortLinkurl, "").Trim();


                result.deeplink_url = AlimamaPlus.GetDeeplink(result.shortLinkurl);
                return result;
            }
            else
            {
                result.content = result.rawContent;
                switch (message)
                {
                    case "该口令无效，请检查后重新提交":
                    case "该商品已下架":
                        result.message = "转链失败";
                        result.reason = message;
                        result.subCode = TkSubCodeEnum.NoConvert;
                        break;
                    default:
                        result.message = "转链失败";
                        result.reason = message;
                        result.subCode = TkSubCodeEnum.NetError;
                        break;
                }
                return result;
            }

        }

    }

}
