package com.funcheer.channel.sdk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.fqchannelsdk.R;
import com.fq.channel.sdk.api.FqGame;
import com.fq.channel.sdk.api.IExit;
import com.fq.channel.sdk.api.IResult;
import com.fq.channel.sdk.api.bean.LoginInfo;
import com.fq.channel.sdk.api.bean.PaymentInfo;
import com.fq.channel.sdk.base.constants.ConstSet;
import com.fq.channel.sdk.base.net.HttpManager;
import com.fq.channel.sdk.base.net.callback.BaseCallback;
import com.fq.channel.sdk.base.exception.BaseException;
import com.fq.channel.sdk.base.utils.FqLog;

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

import java.util.HashMap;

/**
 * @Description: 描述
 * @Author: FLuty
 * @CreateDate: 2020/3/24 09:49
 */
public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fq_activity_main);
        FqLog.i(TAG, "onCreate: ");
        initUI();
        initSDK();
        FqGame.onCreate(savedInstanceState);
    }

    //跟游戏的主Activity走
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        FqGame.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        FqGame.onNewIntent(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FqGame.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        FqLog.i(TAG, "onRestart: ");
        FqGame.onRestart();
    }

    @Override
    protected void onStart() {
        super.onStart();
        FqLog.i(TAG, "onStart: ");
        FqGame.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        FqLog.i(TAG, "onResume: ");
        FqGame.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        FqLog.i(TAG, "onPause: ");
        FqGame.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
        FqLog.i(TAG, "onStop: ");
        FqGame.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FqLog.i(TAG, "onDestroy: ");
        FqGame.onDestroy();
    }

    private void initUI() {
        findViewById(getResourceId("fq_login", "id")).setOnClickListener(this);
        findViewById(getResourceId("fq_switch_account", "id")).setOnClickListener(this);
        findViewById(getResourceId("fq_logout", "id")).setOnClickListener(this);
        findViewById(getResourceId("fq_charge", "id")).setOnClickListener(this);
        findViewById(getResourceId("fq_report_data", "id")).setOnClickListener(this);
        findViewById(getResourceId("fq_exit", "id")).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.fq_login:
                login();
                break;

            case R.id.fq_switch_account:
                try {
                    switch_account();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;

            case R.id.fq_logout:
                logout();
                break;

            case R.id.fq_report_data:
                dataReport();
                break;

            case R.id.fq_charge:
                charge();
                break;

            case R.id.fq_exit:
                exit();
                break;

            default:
                break;
        }
    }

    private int getResourceId(String name, String defType) {
        return this.getResources().getIdentifier(name, defType, this.getPackageName());
    }

    private void initSDK() {
        FqGame.init(MainActivity.this, new IResult<String>() {
            @Override
            public void onSuccess(String s) {
                FqLog.i(TAG, "init success: " + s);
            }

            @Override
            public void onFail(String failMsg) {
                FqLog.i(TAG, "init fail:" + failMsg);
            }
        });
    }


    private void login() {
        FqGame.login(MainActivity.this, new IResult<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo s) {
                FqLog.i(TAG, "login success: " + s.getUid());
            }

            @Override
            public void onFail(String failMsg) {
                FqLog.i(TAG, "login fail:" + failMsg);
            }
        });
    }

    public void charge() {

        //get price
        String priceString = ((EditText)findViewById(getResourceId("fq_charge_price",
                "id"))).getText().toString();
        if (TextUtils.isEmpty(priceString)){
            showResult("请先填入价格");
            return;
        }

        float price = Float.parseFloat(priceString);
        FqLog.d(TAG,"price : "+price);
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderAmount("1");            //订单金额           必须字段
        paymentInfo.setSubject("1元宝");              //商品名             必须字段
        paymentInfo.setCpBillNo("cp_order001");    //CP订单号           必须字段
        paymentInfo.setServerId("1");               //区服ID             必须字段
        paymentInfo.setExtraInfo("FqGameSdk");      //拓展信息            必须字段
//        paymentInfo.setUid(uid);                    //登录时成功拿到的UID  必须字段
//        paymentInfo.setRoleName("Hello");           //角色名             必须字段
        paymentInfo.setRemark("remark");            //订单备注            非必须字段

//        paymentInfo.setRoleLevel("5");              //角色等级            非必须字段
//        paymentInfo.setRoleId("Role_001");          //订单备注            非必须字段
//        paymentInfo.setPartyName("帮派");            //帮派               非必须字段
//        paymentInfo.setServerName("区服名");         //区服名              非必须字段


        FqGame.pay(MainActivity.this,paymentInfo, new IResult<String>() {
            @Override
            public void onSuccess(String s) {
                FqLog.i(TAG,"pay success: "+s);
            }

            @Override
            public void onFail(String failMsg) {
                FqLog.i(TAG,"pay fail:"+failMsg);
            }
        });
    }

    private void exit() {// 退出接口
        FqGame.exit(MainActivity.this, new IExit() {
            @Override
            public void onExit() {
                //退出游戏
                System.exit(0);
            }

            @Override
            public void onNoConfirmDialogExit() {
                //渠道不存在退出界面,此处游戏必须弹出自己的退出确认框。
                showGameExitView();
            }
        });
    }

    private void showGameExitView() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("游戏自带退出界面");
        builder.setCancelable(false);
        builder.setPositiveButton("退出",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {


                        exitAppProcess(MainActivity.this);
                    }
                });
        builder.show();
    }

    private void dismissFloatView() {
    }

    private void showFloatView() {
    }

    private void dataReport() {
        //get report data type
        String dataReportTypeString = ((EditText) findViewById(getResourceId("fq_report_type",
                "id"))).getText().toString();
        if (TextUtils.isEmpty(dataReportTypeString)) {
            showResult("请先填入上报类型");
            return;
        }

        int dataReportType = Integer.parseInt(dataReportTypeString);

        /**设置统计参数的方法,游戏在参数发出变化时都需要调用接口设置参数*/
        /**====================================================
         * ConstSet.DATA_KEY_ROLE_ID 当前登录的玩家角色ID
         * ConstSet.DATA_KEY_ROLE_NAME 当前登录的玩家角色名
         * ConstSet.DATA_KEY_ROLE_LEVEL 当前登录的玩家角色等级
         * ConstSet.DATA_KEY_SERVER_ID 当前登录的游戏区服ID
         * ConstSet.DATA_KEY_SERVER_NAME 当前登录的游戏区服名称
         * ConstSet.DATA_KEY_BALANCE 当前用户游戏币余额
         * ConstSet.DATA_KEY_VIP_LEVEL 当前用户VIP等级
         * ConstSet.DATA_KEY_PARTY_NAME 当前用户所属帮派
         * ConstSet.DATA_KEY_PARTY_NAME 角色创建时间(单位：秒)，该时间请务必传入服务端真实角色创建时间。
         * ConstSet.DATA_KEY_ROLE_LEVEL_TIME 角色等级变化时间(单位：秒)，该时间请务必传入服务端真实角色升级时间。
         *
         * ConstSet.DATA_KEY_DATA_TYPE 数据统计类型，以下所有统计点必接)：
         * 1、创建角色，data type为0；
         * 2、角色升级,data type为1；
         * 3、上传区服信息，data type为2；
         * 4、登录，data type为3；
         * 5、进入游戏,data type为4；
         * 6、支付，data type为5；
         * 7、选择服务器,data type为6；
         * 8、退出游戏，data type为7；
         =======================================================*/
        Bundle staticsData = new Bundle();
        staticsData.putString(ConstSet.DATA_KEY_ROLE_ID, "111");
        staticsData.putString(ConstSet.DATA_KEY_ROLE_NAME, "战士");
        staticsData.putString(ConstSet.DATA_KEY_ROLE_LEVEL, "65");
        staticsData.putString(ConstSet.DATA_KEY_SERVER_ID, "11");
        staticsData.putString(ConstSet.DATA_KEY_SERVER_NAME, "服务器");
        staticsData.putString(ConstSet.DATA_KEY_BALANCE, "102");
        staticsData.putString(ConstSet.DATA_KEY_VIP_LEVEL, "2");
        staticsData.putString(ConstSet.DATA_KEY_PARTY_NAME, "水果派");
        staticsData.putLong(ConstSet.DATA_KEY_ROLE_CREATE_TIME, System.currentTimeMillis() / 1000);
        staticsData.putLong(ConstSet.DATA_KEY_ROLE_LEVEL_TIME, System.currentTimeMillis() / 1000);
        staticsData.putString(ConstSet.DATA_KEY_ZONE_ID, "1");
        staticsData.putString(ConstSet.DATA_KEY_ZONE_NAME, "阿狸一区");
        staticsData.putInt(ConstSet.DATA_KEY_DATA_TYPE, dataReportType);
        FqGame.setRoleInfo(staticsData);
//        Idsfq.setExtraBundle(staticsData);
    }

    private void logout() {
    }

    private void switch_account() throws JSONException {
        HashMap hashMap = new HashMap<String, String>();
        JSONObject custom = new JSONObject();
        custom.put("ssoid", "ssoid");
        custom.put("token", "token");
        hashMap.put("channelType", "ansen");
        hashMap.put("gameId", "123");
        hashMap.put("imei", "123");
        hashMap.put("channelId", "123");
        hashMap.put("channelParams", custom.toString());

        HttpManager.getInstance().post("http://192.168.1.152:9099/api/sdk/channel/v1/login", hashMap, new BaseCallback<String>() {
            @Override
            public void onFailure(BaseException msg) {
                Log.i(TAG, "onFailure: ");
            }

            @Override
            public void onSuccess(int code, String msg, String data) {
                Log.i(TAG, "onResponse: " + data);
            }
        });
    }

    private void showResult(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void exitAppProcess(Activity activity) {
        if (!activity.isFinishing()) {
            activity.finish();
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean isConsume = super.onKeyDown(keyCode, event);
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                isConsume = true;
                exit();
                break;
        }

        return isConsume;
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FqGame.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
