
package com.unity3d.player;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.barton.log.GASDKFactory;
import com.barton.log.builder.GAConfiguration;
import com.barton.log.builder.ParamsBuilder;
import com.barton.log.ebarton.BaseUrl;
import com.barton.log.ebarton.EventType;
import com.barton.log.logapi.IGASDK;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tuyoo.gamesdk.api.SDKAPI;
import com.tuyoo.gamesdk.api.SDKCallBack;
import com.tuyoo.gamesdk.api.SDKWrapper;
import com.tuyoo.gamesdk.api.TuYooClientID;
import com.tuyoo.gamesdk.event.EventBus;
import com.tuyoo.gamesdk.event.EventConsts;
import com.tuyoo.gamesdk.event.data.PayEventData;
import com.tuyoo.gamesdk.event.data.WeixinShareData;
import com.tuyoo.gamesdk.model.InitParam;
import com.tuyoo.gamesdk.pay.model.PayType;
import com.tuyoo.gamesdk.util.SDKLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class SDKManager {

    private final static Handler handler = new Handler(Looper.getMainLooper());
    private static IGASDK gasdk;
    private static final String TAG = com.unity3d.player.SDKManager.class.getSimpleName();
    private static String curType = TuYooClientID.tyGuest;
    public static void InitSDK(Activity activity)
    {
        Log.e(TAG,"SDKManager:::InitSDK");
        Log.e(TAG,"SDK_APPID:::" + ConfigManager.SDK_APPID);
        Log.e(TAG,"SDK_CLIENTID:::" + ConfigManager.SDK_CLIENTID);
        Log.e(TAG,"SDK_LOGIN_SERVER_URL:::" + ConfigManager.SDK_LOGIN_SERVER_URL);
        activity.runOnUiThread(() -> {
            SDKAPI.getIns().lightModeEnable();
            try {
                SDKAPI.getIns().init(new InitParam.Builder()
                        .withActivity(activity)
                        .withAppId(ConfigManager.SDK_APPID)
                        .withClientId(ConfigManager.SDK_CLIENTID)
                        .withServerUrl(ConfigManager.SDK_LOGIN_SERVER_URL)
                        .build());
                TYUnityActivity.setSdkInited();
                SDKAPI.getIns().onActivityStart(activity);
                SDKAPI.getIns().onActivityResume(activity);
            } catch (Exception e) {
                System.out.println("initSDK Exception " +  e);
            }
        });
    }


    public static void parseLoginInfo(int i, String s) {
        try {
            JSONObject result = new JSONObject();
            result.put("code", i);
            if (i == 0) {
                JSONObject serverResponse = new JSONObject(s);
                JSONObject userInfo = serverResponse.getJSONObject("result");
                JSONObject userInfoReorganization = new JSONObject();
                userInfoReorganization.put("userId", userInfo.optString("userId"));
                userInfoReorganization.put("token", userInfo.optString("token"));
                userInfoReorganization.put("jwttoken", userInfo.optString("jwttoken"));
                userInfoReorganization.put("loginChannelTypeC", userInfo.optString("loginChannelTypeC"));
                JSONObject userInfoResult = new JSONObject();
                userInfoResult.put("result", userInfoReorganization);
                result.put("respObj", userInfoResult);
            } else {
                Log.e(TAG,"errStr:::::" +s);
                result.put("errStr", s);
            }

            UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.LOGIN_CALLBACK_FUNCTION_NAME, result.toString());
        } catch (Exception e) {
            Log.e(TAG,"SDKManager-parseLoginInfo-Exception" + e);
            SDKLog.e("SDKManager-parseLoginInfo-Exception" + e);
            UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.LOGIN_CALLBACK_FUNCTION_NAME, "{\"code\":1}}");
        }
    }

    //登录回调-统一的回调方法（保持回调仅有一个，否则可能会出现多次回调的情况）
    static SDKCallBack.Login mLogin = new SDKCallBack.Login() {
        @Override
        public void callback(int i, String s) {
            SDKLog.i("SDKCallBack.Login callback: " + i + " \n" + s);
            parseLoginInfo(i, s);
        }
    };

    static SDKCallBack.Pay mPay = new SDKCallBack.Pay() {
        @Override
        public void callback(int i, String s) {

            Log.e(TAG,"SDKCallBack.Pay callback: " + i + " \n" + s);
            SDKLog.i("SDKCallBack.Pay callback: " + i + " \n" + s);
            try {
                JSONObject result = new JSONObject();
                result.put("code", i);
                result.put("respObj", s);
                result.put("errStr", s);
                UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.PAY_CALLBACK_FUNCTION_NAME, result.toString());
            } catch (Exception e) {
                Log.e(TAG,"SDKManager-SDKCallBack.Pay-Exception" + e);
                SDKLog.e("SDKManager-SDKCallBack.Pay-Exception" + e);
                UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.PAY_CALLBACK_FUNCTION_NAME, "{\"code\":1}}");
            }
        }
    };

    public static void UnityResetServerUrl(String url) {
        SDKLog.i("UnityResetServerUrl : " + url);
        SDKAPI.getIns().updateServer(url);
    }

    public static void UnityLoginByTokenFun(String token) {
        SDKLog.i("UnityLoginByTokenFun : " + token);
        handler.post(new Runnable() {
            @Override
            public void run() {
                SDKAPI.getIns().loginByToken(token, mLogin);
            }
        });
    }

    public static void UnityGetIdentityFun(String type) {
        Log.e(TAG,"UnityGetIdentityFun : " + type);
        SDKLog.i("UnityGetIdentityFun : " + type);
        handler.post(new Runnable() {
            @Override
            public void run() {
                SDKAPI.getIns().loginByType(type, mLogin);
            }
        });
    }

    public static void UnityLogin(String type) {
        Log.e(TAG,"UnityLogin : " + type);
        SDKLog.i("UnityLogin : " + type);
        handler.post(new Runnable() {
            @Override
            public void run() {
                SDKAPI.getIns().loginByType(type, mLogin);
            }
        });
    }

    public static void UnityLogOutByChannel(String type) {
//         Log.e(TAG,"UnityLoginOut!!!");
        SDKLog.i("UnityLoginOut : ");
        handler.post(() -> SDKAPI.getIns().logout(type));
    }

    public static void LinkAccount(String type, String userId)
    {
        SDKAPI.getIns().getSnsInfo(type, (code, snsInfo, msg) -> {
            if(code == SDKCallBack.CODE_SUCCESS && snsInfo != null){
                SDKAPI.getIns().bindBySnsId(snsInfo, userId, mLogin);
            }else {
                UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.LOGIN_CALLBACK_FUNCTION_NAME, "{\"code\":1}}");
            }
        });
    }

    public static void LinkCheck(String type)
    {
        SDKAPI.getIns().getSnsInfo(type, (code, snsInfo, msg) -> {
            if(code == SDKCallBack.CODE_SUCCESS && snsInfo != null){
                SDKAPI.getIns().checkSnsInfo(snsInfo, (code1, msg1) -> {
                    if(code1 == SDKCallBack.CODE_SUCCESS && !TextUtils.isEmpty(msg1)){
                        try {
                            JSONObject jsonObject = new JSONObject(msg1).optJSONObject("result");
                            //返回信息中code为0时表示服务端查询成功，exit为1表示此渠道用户信息已产生过途游账号，可直接进行登录，exit为0表示此渠道用户信息未产生过途游账号，可以进行绑定
                            if(jsonObject.optString("code").equals("0")
                                    && jsonObject.optString("exist").equals("0")){
                                UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.CHECKLINK_CALLBACK_FUNCTION_NAME, "0");
                            }
                            else
                            {
                                UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.CHECKLINK_CALLBACK_FUNCTION_NAME, "1");
                            }
                        } catch (JSONException e) {
                            UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.CHECKLINK_CALLBACK_FUNCTION_NAME, "-1");
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.CHECKLINK_CALLBACK_FUNCTION_NAME, "-1");
                    }
                });
            }
            else
            {
                UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.CHECKLINK_CALLBACK_FUNCTION_NAME, "-1");
            }
        });
    }

    public static void UnityKnow(String productId, String productName, String productCount, String prodorderId, String appInfo) {
        SDKLog.i("UnityKnow : " + productId);
        HashMap<String, String> extraInfo = new HashMap<String, String>();
        extraInfo.put("appInfo", appInfo);
        SDKAPI.getIns().pay(productId, productName, productCount, Integer.parseInt(ConfigManager.SDK_GAMEID), mPay, prodorderId, extraInfo);
    }

    public static void UnityGetKnowTypeList(String productId)
    {
        Log.e(TAG,"UnityGetKnowTypeList:" + productId );
        final PayEventData.PayReq mPayReq = new PayEventData.PayReq();
        mPayReq.prodId = productId;
        SDKAPI.getIns().charge(mPayReq , new SDKCallBack.Base1() {
            @Override
            public void callback(int code, String msg) {
                SDKLog.e("====> code= " + code + "  msg= " + msg);
                try {
                    JSONObject result = new JSONObject();
                    result.put("code", code);
                    if(code == 0){
                        result.put("respObj", msg);
                    }else {
                        result.put("errStr", msg);
                    }
                    UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.PAY_TYPE_CALLBACK_FUNCTION_NAME, result.toString());
                } catch (Exception e) {
                    SDKLog.e("SDKManager-UnityGetKnowTypeList-Exception" + e);
                    UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.PAY_TYPE_CALLBACK_FUNCTION_NAME, "{\"code\":1}}");
                }
            }
        });
    }

    public static void UnityKnowNew(String productId, String productPrice, String productName, String productCount, String prodorderId, String appInfo, String ptype)
    {
        Log.e(TAG,"开始支付-----"+ "productId:" + productId+"   "+ "productPrice:" + productPrice+"   "+ "productName:" + productName +"   "+ "prodorderId:" + prodorderId +"   "+ "appInfo:" + appInfo  +"   "+ "ptype:" + ptype);

        PayEventData.PayData payData = new PayEventData.PayData();
        final PayEventData.PayReq mPayReq = new PayEventData.PayReq();
        mPayReq.prodId = productId;
        mPayReq.prodPrice = productPrice;
        mPayReq.prodName = productName;
        mPayReq.prodCount = productCount;
        // 此字段与服务端回调接口内的appInfo不对应，与orderId相对应
        mPayReq.appInfo = prodorderId;
        HashMap<String, String> map = new HashMap<String, String>();
        // 此字段（appInfo）可用于传递透传信息（此信息与服务端回调接口内的appInfo相对应）
        map.put("appInfo", appInfo);
        mPayReq.extra = map;
        payData.payReq = mPayReq;
        PayType payType = new PayType();
        payType.paytype = ptype;
        SDKAPI.getIns().payNew(payData, payType, mPay);
    }


    public static void thirdExtend()
    {
        Log.e(TAG,"====>java thirdExtend");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("action","ACTION_GET_SKU_DETAILS_LIST");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        SDKAPI.getIns().thirdExtend(jsonObject.toString(), new SDKCallBack.Extend() {
            @Override public void callback(int code, String msg) {

                Log.e(TAG,"====>thirdExtend code= " + code + "  msg= " + msg );
                try {
                    //获取成功，msg即为对应的json字符串
                    JSONObject result = new JSONObject();
                    result.put("code", code);
                    if(code == SDKCallBack.Extend.EXTEND_CODE_SUCCESS){
                        result.put("respObj", msg);
                    }else {
                        Log.e(TAG,"获取商品列表失败啦:" + msg);
                        result.put("thirdExtend_errStr", msg);
                    }
                    UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.PAY_TYPE_CALLBACK_FUNCTION_NAME, result.toString());
                } catch (Exception e) {
                    SDKLog.e("SDKManager-UnityGetKnowTypeList-Exception" + e);
                    UnityPlayer.UnitySendMessage(ConfigManager.UNITY_FACADE_NAME, ConfigManager.PAY_TYPE_CALLBACK_FUNCTION_NAME, "{\"code\":1}}");
                }
            }
        });
    }

    private static IGASDK GetGameGa(){
        if(gasdk == null){
            GAConfiguration.Builder builder = new GAConfiguration.Builder()
                    .withBaseUrl(BaseUrl.INTERNAL)
                    .withContext(SDKWrapper.getInstance().getContext())
                    .withClientId(ConfigManager.SDK_CLIENTID)
                    .withGameId(ConfigManager.SDK_GAMEID)
                    .withProjectId(ConfigManager.SDK_PROJECTID);
            gasdk = GASDKFactory.createGASDK(builder.build());
        }
        return gasdk;
    }

    public static void SetGaUserInfo(String userId)
    {
        Log.e(TAG,"SetGaUserInfo : " + userId);
        SDKLog.i("SetGaUserInfo : " + userId);
        GetGameGa().setUserId(userId);
    }

    public static void SetGaCommonInfo(String SetGaCommonInfo)
    {
        Log.e(TAG,"SetGaCommonInfo : " + SetGaCommonInfo);
        SDKLog.i("SetGaCommonInfo : " + SetGaCommonInfo);
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(SetGaCommonInfo, new TypeToken<Map<String, Object>>(){}.getType());
        for (String key : map.keySet()) {
            System.out.println("Key = " + key + ", Value = " + map.get(key));
            if(!TextUtils.isEmpty(key) &&  map.get(key) != null){
                GetGameGa().addCommonParameter(key, map.get(key).toString());
            }
        }
    }

    public static void GAReportParams(int type, String eventstr, String paramstr)
    {
        Log.e(TAG,"GAReportParams : " + type + " \n" + eventstr + " \n" + paramstr);

        SDKLog.i("GAReportParams : " + type + " \n" + eventstr + " \n" + paramstr);
        ParamsBuilder paramsBuilder = ParamsBuilder.newInstance();
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(paramstr, new TypeToken<Map<String, Object>>(){}.getType());
        for (String key : map.keySet()) {
            System.out.println("Key = " + key + ", Value = " + map.get(key));
            if(!TextUtils.isEmpty(key) &&  map.get(key) != null){
                paramsBuilder.append(key, map.get(key).toString());
            }
        }
        GetGameGa().track(EventType.TRACK, eventstr, paramsBuilder);
    }

}


