using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using UnityEngine;

namespace tysdk
{
    public partial class TYSdkFacade : MonoBehaviour
    {  
        /*================================================

                   ____                                  _   
                  |  _ \ __ _ _   _ _ __ ___   ___ _ __ | |_ 
                  | |_) / _` | | | | '_ ` _ \ / _ \ '_ \| __|
                  |  __/ (_| | |_| | | | | | |  __/ | | | |_ 
                  |_|   \__,_|\__, |_| |_| |_|\___|_| |_|\__|
                              |___/                          
        =================================================*/
        
        public async Task<PaymentInfo> Pay(string prodId, string prodPrice, string prodName, int count,string pType)
        {
            if (!IsLoggedIn) return new PaymentInfo() { code = "-1", msg = "未登录" };
            
            var orderId = System.Guid.NewGuid().ToString();
            var extraDic = new Dictionary<string,object>() {
                {"paytime" , System.DateTime.UtcNow.Ticks},
                {"sum" , float.Parse(prodPrice) * count},
            };
            string extraInfo = Newtonsoft.Json.JsonConvert.SerializeObject(extraDic);
            //to base64
            extraInfo = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(extraInfo));

#if UNITY_EDITOR
            
            await Task.Yield();
            var result = new PaymentInfo()
            {
                code = "0",
                msg = "success",
                count = count,
                orderId = orderId,
                productId = prodId,
                price = prodPrice
            };

            return result;
#elif UNITY_ANDROID
       
            var taskSource = new TaskCompletionSource<PaymentInfo>();
            callbacks.Add("PayResult", (ITYSdkCallback callback) =>
            {
                taskSource.SetResult((PaymentInfo)callback);
            });
            UnityBridgeFunc.UnityKnowNew(prodId, prodPrice, prodName, count.ToString(), orderId, extraInfo,pType);
            var result = await taskSource.Task;
            result.count = count;
            result.orderId = orderId;
            result.productId = prodId;
            result.price = prodPrice;
            return result;

#elif UNITY_IOS
            var taskSource = new TaskCompletionSource<PaymentInfo>();
            callbacks.Add("PayResult", (ITYSdkCallback callback) =>
            {
                taskSource.SetResult((PaymentInfo)callback);
            });
      UnityBridgeFunc.UnityKnowNew(prodId, prodPrice, prodName, count.ToString(), orderId, extraInfo,pType);
            var result = await taskSource.Task;
            result.count = count;
            result.orderId = orderId;
            result.productId = prodId;
            result.price = prodPrice;
            return result;
#endif
        }

        //支付的回调
        public void PayResult(string json)
        {
            Debug.Log("[TYSdkFacade] pay callback:" + json);
            var jresult = JObject.Parse(json);
            var result = new PaymentInfo();
            result.code = jresult["code"].ToString();
            result.msg = jresult["errStr"].ToString();

            if (callbacks.TryGetValue("PayResult", out var action))
            {
                action.Invoke(result);
                callbacks.Remove("PayResult");
            }
        }
        
        // Get Pay list
        public async Task<SKUDetail> ThirdExtend()
        {
            if (!IsLoggedIn) return new SKUDetail() { code = "-1", msg = "未登录" };

#if UNITY_EDITOR || UNITY_IOS
            await Task.Yield();
            var result = new SKUDetail();
            return result;
#elif UNITY_ANDROID
       
            var taskSource = new TaskCompletionSource<SKUDetail>();
            callbacks.Add("PayTypeResult", (ITYSdkCallback callback) =>
            {
                taskSource.SetResult((SKUDetail)callback);
            });
            UnityBridgeFunc.ThirdExtend();
            var result = await taskSource.Task;
            return result;

#endif
        }

        //商品列表的回调
        public void PayTypeResult(string json)
        {
            Debug.Log("[thirdExtend] pay callback:");
            var jresult = JObject.Parse(json);
            var result = new SKUDetail();
            result.code = jresult["code"].ToString();
            result.msg = jresult["thirdExtend_errStr"].ToString();

            if (callbacks.TryGetValue("PayTypeResult", out var action))
            {
                action.Invoke(result);
                callbacks.Remove("PayTypeResult");
            }
        }
    }
}
