package com.fq.channel.sdk;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.fq.channel.sdk.base.config.FqConfig;
import com.fq.channel.sdk.base.constants.ConstSet;
import com.fq.channel.sdk.base.interfaces.FQPluginApi;
import com.fq.channel.sdk.base.interfaces.PluginResultHandler;
import com.fq.channel.sdk.base.utils.FqLog;
import com.fq.threelib.gson.Gson;
import com.fq.threelib.gson.JsonObject;
import com.nearme.game.sdk.GameCenterSDK;
import com.nearme.game.sdk.callback.ApiCallback;
import com.nearme.game.sdk.callback.GameExitCallback;
import com.nearme.game.sdk.common.model.biz.PayInfo;
import com.nearme.game.sdk.common.model.biz.ReportUserGameInfoParam;
import com.nearme.platform.opensdk.pay.PayResponse;

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

public class SdkPluginOppo extends FQPluginApi {

    private static final String TAG = "SdkPluginOppo";

    /**
     * 初始化
     */
    @Override
    public void init(Context activity, final PluginResultHandler handler) {
        FqLog.i(TAG, "init");
        String secret = (String) FqConfig.get().get("oppo_gameSecret");
        if (null != handler && secret != null) {
            GameCenterSDK.init(secret, activity);
            fqSdkSuccess(handler);
        } else {
            fqSdkError(handler);
        }
    }

    /**
     * 登录
     */
    @Override
    public void login(final Context activity, final PluginResultHandler handler) {
        FqLog.i(TAG, "login ");

        GameCenterSDK.getInstance().doLogin(activity, new ApiCallback() {
            @Override
            public void onSuccess(String content) {
                FqLog.i(TAG, "login success: " + content);
                GameCenterSDK.getInstance().doGetTokenAndSsoid(new ApiCallback() {

                    @Override
                    public void onSuccess(String resultMsg) {
                        FqLog.i(TAG, "doGetTokenAndSsoid->onSuccess: " + resultMsg);
                        JsonObject json = new Gson().fromJson(resultMsg, JsonObject.class);
                        JsonObject result = new JsonObject();
                        result.add("ssoid", json.get("ssoid"));
                        result.add("token", json.get("token"));

                        loginFqSdkSuccess(handler, "oppo", result);
                    }

                    @Override
                    public void onFailure(String content, int resultCode) {
                        fqSdkError(handler, content);
                    }
                });
            }

            @Override
            public void onFailure(String resultMsg, int resultCode) {
                fqSdkError(handler, resultMsg);
            }
        });
    }

    @Override
    public void pay(final Context context, final Map<String, Object> map,
                    final PluginResultHandler handler) {
        FqLog.i(TAG, "pay map:" + (map != null ? map.toString() : ""));

        String orderId = String.valueOf(map.get(ConstSet.PAY_ORDER_ID));
        String extral = String.valueOf(map.get(ConstSet.PAY_EXTRAL_INFO));
        float price = Float.valueOf((String) map.get(ConstSet.PAY_PRICE));
        String productName = String.valueOf(map.get(ConstSet.PAY_PRODUCT_NAME));
        String productDes = String.valueOf(map.get(ConstSet.PAY_PRODUCT_DES));
        String notifyUrl = String.valueOf(map.get(ConstSet.PAY_NOTIFY_URl));
        int amount = 0;
        try {
            amount = (int) (price * 100); // 支付金额，单位分
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        final PayInfo payInfo = new PayInfo(
                orderId + "",
                "oppo支付", amount);
        payInfo.setProductDesc(productDes);
        payInfo.setProductName(productName);
        payInfo.setCallbackUrl(notifyUrl);
        FqLog.i(TAG, "pay notifyUrl:" + notifyUrl);
        GameCenterSDK.getInstance().doPay(context, payInfo, new ApiCallback() {

            @Override
            public void onSuccess(String resultMsg) {
                FqLog.i(TAG, "onSuccess");
                if (handler != null) {
                    fqSdkSuccess(handler);
                }
            }

            @Override
            public void onFailure(String resultMsg, int resultCode) {
                FqLog.i(TAG, "onFailure：" + resultMsg);
                if (PayResponse.CODE_CANCEL == resultCode) {
                    fqSdkCancel(handler);
                } else {
                    fqSdkError(handler);
                }
            }
        });
    }

    /**
     * 退出
     *
     * @param context
     * @param prh
     */
    public void exit(Context context, final PluginResultHandler prh) {
        FqLog.i(TAG, "exit");
        GameCenterSDK.getInstance().onExit((Activity) context, new GameExitCallback() {

            @Override
            public void exitGame() {
                FqLog.i(TAG, "exitGame");
                if (null != prh) {
                    exitFqSdk(prh);
                }
            }
        });
    }

    /**
     * 注销
     */
    public void logout(final Context context, final PluginResultHandler cb) {
        Log.d(TAG, "logout");
    }

    @Override
    public void changeAccount(Activity activity, final PluginResultHandler prh) {
        FqLog.i(TAG, " changeAccount ");
    }

    /**
     * 游戏角色信息
     *
     * @param data
     */
    public void setRoleInfo(Bundle data) {
        if (null == data) {
            FqLog.e(TAG, "setRoleInfo  Bundle is null");
            return;
        }
        String roleId = data.getString("roleId");// 角色id
        String roleName = data.getString("roleName");
        String roleLevel = data.getString("roleLevel");// 角色等级
        String zoneId = data.getString("zoneId");
        String zoneName = data.getString("zoneName");
        String serverId = data.getString("serverId");
        String serverName = data.getString("serverName");
        int dataType = data.getInt("dataType");
        switch (dataType) {
            //这个在登入的时候调用
            case 3:
                FqLog.i(TAG, "setExtraBundle: roleId:" + roleId + ",roleName:" + roleName + ",roleLevel:" + roleLevel + ",serverId:" + serverId + ",serverName:" + serverName + ",chapter:Idreamsky");
                GameCenterSDK.getInstance().doReportUserGameInfoData(new ReportUserGameInfoParam(roleId, roleName, Integer.valueOf(roleLevel), serverId, serverName, "Idreamsky", new HashMap<String, Number>()), new ApiCallback() {

                    @Override
                    public void onSuccess(String resultMsg) {
                        FqLog.i(TAG, "数据上报成功！");
                    }

                    @Override
                    public void onFailure(String resultMsg, int resultCode) {
                        FqLog.i(TAG, "数据上报失败！");
                    }
                });
                break;

            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    }

    @Override
    public int getPayId() {
        return 4;
    }

    /**
     * 释放资源时调用，当用户退出界面或者游戏的时候，
     * 调用此接口，释放资源才允许退出！
     *
     * @param context
     */
    public void releaseSdkResource(Context context) {
        Log.i(TAG, "releaseSdkResource");

        Toast.makeText(context, "释放SDK资源", Toast.LENGTH_SHORT).show();

        try {
            /**渠道存在退出界面,此处游戏必须调用,begin*/
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(startMain);
            /**渠道存在退出界面,此处游戏必须调用,end*/
        } catch (Exception e) {
            Log.e(TAG, "releaseSdkResource 抛出异常！");
        }
    }

    /**
     * 复写生命周期方法,里面调用
     */
    public void onStart(Activity context) {
        Log.i(TAG, "onStart");
    }

    public void onCreate(Activity context, Bundle handler) {
        Log.i(TAG, "onCreate");
    }

    public void onRestart(Activity context) {
        Log.i(TAG, "onRestart");
    }

    public void onResume(Activity context) {
        Log.i(TAG, "onResume");
    }

    public void onPause(Activity context) {
        Log.i(TAG, "onPause");
    }

    public void onStop(Activity context) {
        Log.i(TAG, "onStop");
    }

    public void onDestroy(Activity context) {
        Log.i(TAG, "onDestroy");
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        FqLog.i(TAG, "onActivityResult requestCode:" + requestCode + " resultCode:" + resultCode + " data:" + data);
    }

    public void onNewIntent(Intent intent) {
        Log.i(TAG, "onNewIntent");
    }

    @Override
    public void attachBaseContext(Context context) {

    }

    @Override
    public void onApplicationCreate(Context context) {

    }

    public void onSaveInstanceState(Activity context, Bundle outState) {
        Log.i(TAG, "onSaveInstanceState");
    }
}
