using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Scripting;

namespace TyphoonUnitySDK
{
    /// <summary>
    /// google play sdk
    /// </summary>
    [Preserve]
    public class GooglePlaySdk : BaseSdk
    {
        public TyphoonSdkCallback CallbackInstance;

        public AndroidInstance AndroidInstance;

        public override void OnCreate()
        {
            SdkDebug.Log("on create google play sdk ...");
            //构建回调实例
            CallbackInstance = TyphoonSdkCallback.CreateInstance();
            CallbackInstance.gameObject.name = "TYPHOON_SDK_CALL_BACK";
            CallbackInstance.Initialize(ReceivePayCallBackResult);
            GameObject.DontDestroyOnLoad(CallbackInstance.gameObject);
            //创建android实例
            AndroidInstance = AndroidInstance.CreateInstance();
            AndroidInstance.gameObject.name = "TYPHOON_SDK_ANDROID_INSTANCE";
            AndroidInstance.Initialize();
            GameObject.DontDestroyOnLoad(AndroidInstance.gameObject);
            SdkDebug.Log("on create google play sdk success");
        }

        #region 初始化SDK

        public override void InitSdk(Action success, Action<string> fail)
        {
            SdkDebug.Log("InitSdk");
            AndroidInstance.CallWithSession(new SessionItem("initSdk", null, (res) =>
            {
                if (res == "ok")
                {
                    success?.Invoke();
                }
                else
                {
                    fail?.Invoke(res);
                }
            }));
        }

        #endregion

        #region 登录

        public override void Login(Action success, Action<string> fail)
        {
            SdkDebug.Log("Login");
            AndroidInstance.CallWithSession(new SessionItem("login", null, (res) =>
            {
                if (res == "ok")
                {
                    success?.Invoke();
                }
                else
                {
                    fail?.Invoke(res);
                }
            }));
        }

        #endregion

        #region 退出游戏

        public override bool IsSupportExitGame()
        {
            SdkDebug.Log("IsSupportExitGame");
            return AndroidInstance.CallReturn<bool>("isSupportExitGame");
        }

        public override void ExitGame()
        {
            SdkDebug.Log("ExitGame");
            AndroidInstance.Call("exitGame");
        }

        #endregion

        #region Banner

        public override void ShowBanner(string scene, BannerPosition position)
        {
            SdkDebug.Log("ShowBanner");
            AndroidInstance.Call("showBanner", scene, ((int)position));
        }

        public override void HideBanner(string scene = "")
        {
            SdkDebug.Log("HideBanner");
            AndroidInstance.Call("hideBanner", scene);
        }

        #endregion

        #region 视频广告

        public override bool GetVideoFlag()
        {
            SdkDebug.Log("GetVideoFlag");
            return AndroidInstance.CallReturn<bool>("getVideoFlag");
        }

        public override void ShowVideo(string scene, Action success, Action<string> fail)
        {
            SdkDebug.Log("ShowVideo");
            AndroidInstance.CallWithSession(new SessionItem("showVideo", new { scene = scene }, (res) =>
            {
                if (res == "ok")
                {
                    SdkDebug.Log($"show video success scene:{scene}");
                    success?.Invoke();
                }
                else
                {
                    SdkDebug.Log($"show video fail {res} scene:{scene}");
                    fail?.Invoke(res);
                }
            }));
        }

        #endregion

        #region 插页广告

        public override void ShowInters(string scene)
        {
            SdkDebug.Log("ShowInters");
            AndroidInstance.Call("showInters", scene);
        }

        #endregion

        #region 悬浮ICON

        public override void ShowFloatIcon(string scene, float screenXP, float screenYP)
        {
            SdkDebug.Log($"ShowFloatIcon spx:{screenXP}, spy:{screenYP}");
            AndroidInstance.Call("showFloatIcon", scene, screenXP, screenYP);
        }

        public override void HideFloatIcon(string scene)
        {
            SdkDebug.Log("HideFloatIcon");
            AndroidInstance.Call("hideFloatIcon", scene);
        }

        #endregion

        #region 原生模板

        public override void ShowNative(string scene)
        {
            SdkDebug.Log("ShowNative");
            AndroidInstance.Call("showNative", scene);
        }

        public override void HideNative(string scene)
        {
            SdkDebug.Log("HideNative");
            AndroidInstance.Call("hideNative", scene);
        }

        #endregion

        #region 支付

        //请求商品信息
        public override void RequestProductInfosAsync(Action<List<IapProductInfo>> success, Action<string> fail)
        {
            SdkDebug.Log("RequestProductInfosAsync ...");
            AndroidInstance.CallWithSession(new SessionItem("requestIapProductInfosAsync", null, (res) =>
            {
                SdkDebug.Log(res);
                try
                {
                    SdkDebug.Log("开始解析----");
                    var result = res.ToXObject<RequestProductInfoResult>();
                    if (result.state)
                    {
                        success?.Invoke(result.infos);
                    }
                    else
                    {
                        SdkDebug.Log($"请求商品信息失败 err  : {result.failMsg}");
                        fail?.Invoke(result.failMsg);
                    }
                }
                catch (Exception e)
                {
                    SdkDebug.Log($"请求商品信息失败 err 1: {e.Message}");
                    fail?.Invoke($"请求商品信息失败 err : {e.Message}");
                }
            }));
        }


        public override void Pay(string productId, int price, string productName, string productDesc)
        {
            SdkDebug.Log(
                $"支付 ... productId ：{productId} ,price ：{price} , productName ：{productName}, productDesc ：{productDesc} ");
            var data = new
            {
                productId,
                price,
                productName,
                productDesc
            };
            AndroidInstance.Call("pay", data.ToXJson());
        }


        public override void RequestOrders()
        {
            base.RequestOrders();
        }

        public override void ReceivePayCallBackResult(PayCallBackResult result)
        {
            SdkDebug.Log(
                $"收到支付回调 ReceivePayCallBackResult ：{result}");
            foreach (var item in result.items)
            {
                if (item.state)
                {
                    CommitOrder(item.extra.order_id);
                }

                PayCallback?.OnPayCallback(item.product_id, item.state, item.extra);
            }
        }

        private void CommitOrder(string orderId)
        {
            AndroidInstance.Call("commitOrder", orderId);
        }

        #endregion
    }
}