package com.fq.channel.sdk;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.fq.channel.sdk.base.constants.FqConfig;
import com.fq.channel.sdk.base.interfaces.FQPluginApi;
import com.fq.channel.sdk.base.interfaces.PluginResult;
import com.fq.channel.sdk.base.interfaces.PluginResultHandler;
import com.fq.channel.sdk.base.utils.FqLog;
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.ReportUserGameInfoParam;

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

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

public class SdkPluginOppo extends FQPluginApi {

    private static final String TAG = "SdkPluginOppo";

    /**
     * 数据统计
     */
    private int dataType;
    private String roleId, roleName, roleLevel, zoneId, zoneName, serverId, serverName, balance, vipLevel, partyName;

    /**
     * 初始化
     */
    @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);
            initFqSdkSuccess(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);
                        try {
                            JSONObject json = new JSONObject(resultMsg);
                            JSONObject result = new JSONObject();
                            result.put("ssoid",json.getString("ssoid"));
                            result.put("token",json.getString("token"));

                            HashMap<String, String> loginAuthData = new HashMap<>();
                            loginAuthData.put("channelType","oppo");
                            loginAuthData.put("channelParams",result.toString());
                            loginFqSdkSuccess(handler,loginAuthData);

                        } catch (JSONException e) {
                            loginFqSdkError(handler, e.getMessage());
                        }
                    }

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

            @Override
            public void onFailure(String resultMsg, int resultCode) {
                loginFqSdkError(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() : ""));

//        final PayInfo payInfo = new PayInfo(
//                orderId + "",
//                orderId + "__" + game_id + "__" + paramType, price * 100); //分为单位，转换成为元
//        payInfo.setProductDesc(productDes);
//        payInfo.setProductName(productName);
//        payInfo.setCallbackUrl("");
//        GameCenterSDK.getInstance().doPay(context, payInfo, new ApiCallback() {
//
//            @Override
//            public void onSuccess(String resultMsg) {
//                FqLog.i(TAG, "onSuccess");
//                if (handler != null) {
//                    payFqSdkSuccess(handler);
//                }
//            }
//
//            @Override
//            public void onFailure(String resultMsg, int resultCode) {
//                FqLog.i(TAG, "onFailure："+resultMsg);
//                if (PayResponse.CODE_CANCEL != resultCode) {
//                    payFqSdkError(handler);
//                } else {
//                    // 取消支付处理
//                    payFqSdkCancel(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) {
                    prh.onHandlePluginResult(new PluginResult(
                            PluginResult.Status.OK));
                }
            }
        });
    }

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

        Builder builder = new Builder(context);
        builder.setTitle("注销");
        builder.setMessage("是否注销？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "注销成功");
                cb.onHandlePluginResult(new PluginResult(
                        PluginResult.Status.OK));
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "注销失败");
                cb.onHandlePluginResult(new PluginResult(
                        PluginResult.Status.ERROR));
            }
        });
        builder.show();
    }

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


    private void showTips(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {

            @Override
            public void run() {
//				Activity activity = IdsLingdoCache.get().getCurrentActivity();
//				if (null != activity){
//					Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
//				}
            }
        });
    }

    /**
     * 游戏角色信息
     *
     * @param data
     */
    public void setRoleInfo(Bundle data) {
        if (null == data) {
            data = new Bundle();
        }
        Log.i(TAG, "setExtraBundle data:" + data.toString());

        roleName = data.getString("roleName");// 角色名称
        roleLevel = data.getString("roleLevel");//当前登录的玩家角色等级
        roleId = data.getString("roleId");// 角色名称
        serverId = data.getString("serverId"); //当前登录的游戏区服ID
        serverName = data.getString("serverName");//当前登录的游戏区服名称
        balance = data.getString("balance");//当前用户游戏币余额
        vipLevel = data.getString("vipLevel");//当前用户VIP等级
        partyName = data.getString("partyName");//当前用户所属帮派
        zoneId = data.getString("zoneId");//角色所在区域唯一标示
        zoneName = data.getString("zoneName");//角色所在区域名称
        dataType = data.getInt("dataType");//统计判断类型

        StringBuffer reportData = new StringBuffer();
        reportData.append("[");
        reportData.append(" roleName:" + roleName);
        reportData.append(" roleLevel:" + roleLevel);
        reportData.append(" roleId:" + roleId);
        reportData.append(" serverId:" + serverId);
        reportData.append(" serverName:" + serverName);
        reportData.append(" balance:" + balance);
        reportData.append(" vipLevel:" + vipLevel);
        reportData.append(" partyName:" + zoneId);
        reportData.append(" zoneName:" + zoneName);
        reportData.append(" dataType:" + dataType);
        reportData.append("]");

        switch (dataType) {
            case 0://创建角色
                showTips("数据上报：创建角色 ");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 1://角色升级
                showTips("数据上报：角色升级");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 2:// 上传区服信息
                showTips("数据上报：上传区服信息");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 3://登录
                showTips("数据上报：登录");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 4://支付
                showTips("数据上报：进入游戏");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 5:// 选择服务器
                showTips("数据上报：支付");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 6://退出游戏
                showTips("数据上报：退出游戏");
                Log.i(TAG, "reportData" + reportData);
                break;

            case 7:// 备注（预留参数）
                showTips("数据上报：退出游戏");
                FqLog.i(TAG, "reportData" + reportData);
                break;
            default:
                break;
        }

        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) {

    }


    /**
     * 释放资源时调用，当用户退出界面或者游戏的时候，
     * 调用此接口，释放资源才允许退出！
     *
     * @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(Context context) {
        Log.i(TAG, "onStart");
    }

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

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

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

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

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

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

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.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(Context context, Bundle outState) {
        Log.i(TAG, "onSaveInstanceState");
    }
}
