package com.hoolai.access.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.hoolai.access.open.fastaccess.channel.FastSdk;
import com.hoolai.access.open.fastaccess.channel.request.EventType;
import com.hoolai.access.open.fastaccess.channel.request.GoodsInfo;
import com.hoolai.access.open.fastaccess.channel.request.PayParams;
import com.hoolai.access.open.fastaccess.channel.request.PlayerInfo;
import com.hoolai.access.open.fastaccess.channel.request.ShareParams;
import com.hoolai.access.open.fastaccess.channel.request.ShareType;
import com.hoolai.access.open.fastaccess.channel.result.InitResult;
import com.hoolai.access.open.fastaccess.channel.result.LoginResult;
import com.hoolai.access.open.fastaccess.interf.HLAccountListener;
import com.hoolai.access.open.fastaccess.interf.HLPaymentListener;
import com.hoolai.access.open.fastaccess.interf.HLSystemListener;
import com.hoolai.access.open.fastaccess.utils.Logger;
import com.hoolai.access.open.fastaccess.utils.SPUtils;
import com.hoolai.access.open.fastaccess.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Hoolai_sdk接入说明
 * 接入文档地址 http://support.hoolai.com/docs/#/android/complete
 */
public class GameActivity extends Activity {

    private TextView contentTv;
    private LoginResult userResponse;
    private Button initBtn, loginBtn, logoutBtn;
    private EditText et_tv, et_rpc, et_pwd, et_itemId;
    private EditText et_ip_host, et_ip_pwd, et_ip_port;
    private boolean isInit;
    private int height;
    private int width;
    private boolean isEnterGame;
    private StringBuffer sb = new StringBuffer();
    private ScrollView scrollView;
    private LinearLayout linearLayout;
    private static final String ITME_ID = "itemId";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        AccessConfigMgr.cfgInstance().StartSocket("10.1.3.29", 3333, "aaa");
//        Logger.i("--------------------------------------------StartSocket");
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        setContentView(R.layout.activity_main);

        contentTv = findViewById(R.id.main_tv);
        et_tv = findViewById(R.id.et_main);
        et_rpc = findViewById(R.id.et_rpc);
        et_pwd = findViewById(R.id.et_pwd);
        et_itemId = findViewById(R.id.et_itemId);
        et_ip_host = findViewById(R.id.et_ip_host);
        et_ip_port = findViewById(R.id.et_ip_port);
        et_ip_pwd = findViewById(R.id.et_ip_pwd);
        scrollView = findViewById(R.id.main_scrollview);
        linearLayout = findViewById(R.id.main_linearlayout);
        initBtn = findViewById(R.id.init);
        loginBtn = findViewById(R.id.login);
        logoutBtn = findViewById(R.id.logout);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
        this.width = displayMetrics.widthPixels;
        this.height = displayMetrics.heightPixels;

        hoolaiSdkInit();

        et_itemId.setText("1");
        String itemId = SPUtils.getInstance().getStringValue(ITME_ID);
        if (!TextUtils.isEmpty(itemId)) {
            et_itemId.setText(itemId);
        }

//        FastSdk.checkPermission(this, "android.permission.READ_EXTERNAL_STORAGE", true);
//        FastSdk.checkPermission(this, "android.permission.READ_EXTERNAL_STORAGE", true);
//        FastSdk.checkPermissions(this, new String[] {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.READ_PHONE_STATE"
//                , "android.permission.CAMERA", "android.permission.ACCESS_FINE_LOCATION"}, true);
    }

    @Override
    public Resources.Theme getTheme() {
        Resources.Theme theme = super.getTheme();
        theme.applyStyle(android.R.style.Theme_NoTitleBar_Fullscreen, true);
        return theme;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        FastSdk.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        FastSdk.onStart(this);
    }

    @Override
    protected void onResume() {
        Logger.i("游戏页面onResume");
        super.onResume();
        FastSdk.onResume(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        FastSdk.onStop(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        FastSdk.onPause(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Logger.i("游戏页面onRestart");
        FastSdk.onRestart(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FastSdk.onDestroy(this);
    }

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

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

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

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        FastSdk.onConfigurationChanged(this, newConfig, getResources());
        ViewGroup.LayoutParams layoutParams = getWindow().getDecorView().getLayoutParams();
        if (layoutParams.width >= layoutParams.height) {
            layoutParams.width = width;
            layoutParams.height = height;
        } else {
            layoutParams.width = height;
            layoutParams.height = width;
        }
        getWindow().onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        //如果游戏需要捕获返回事件,请在这里做逻辑判断调用FastSdk.onBackPressed();
        FastSdk.onBackPressed();
        exit();
    }

    /**
     * hoolai sdk初始化,必须放到onCreate中,并且在主线程中调用
     */
    private void hoolaiSdkInit() {
        FastSdk.hlSystemListener = new HLSystemListener() {
            @Override
            public void onInitSuccess(InitResult result) {
                initBtn.setVisibility(View.GONE);
                loginBtn.setVisibility(View.VISIBLE);
                isInit = true;
                if (!contentTv.getText().toString().contains("登录成功")) {
                    sb.append("初始化成功!初始化结果：\n" + result.toString());
                    refreshView();
                }
                LogUtil.i("Hoolai sdk初始化成功:");
                Toast.makeText(GameActivity.this, "初始化成功！", Toast.LENGTH_SHORT).show();
                //                FastSdk.checkPermission(GameActivity.this, "android.permission.BLUETOOTH_SCAN");
            }

            @Override
            public void onInitFailed(String reason) {
                LogUtil.i("Hoolai sdk初始化失败:" + reason);
                Toast.makeText(GameActivity.this, "初始化失败:" + reason, Toast.LENGTH_SHORT).show();
                //sdk初始化失败
                //注意初始化未成功不得调用sdk任何接口,游戏可在这里做提示或者重新初始化操作

            }

            @Override
            public void onCustomExit() {
                Toast.makeText(GameActivity.this, "弹出游戏的退出界面", Toast.LENGTH_SHORT).show();
                /**
                 * demo 只作为参考，游戏应该根据自己所需逻辑实现
                 * 渠道没有退出二次确认框
                 * 根据需要加二次确认框
                 */
                // 渠道不存在退出界面，如百度移动游戏等，此时需在此处弹出游戏退出确认界面，否则会出现渠道审核不通过情况
                // 游戏实现自己的退出界面 ，实现退出逻辑，请勿直接照搬demo
                // 根据需要加二次确认框
                new AlertDialog.Builder(GameActivity.this)
                        .setTitle("游戏退出弹窗")
                        .setMessage("我是游戏的弹窗界面哦")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", (dialog, which) -> onExitSuccess(""))
                        .setCancelable(false).show();
            }

            @Override
            public void onExitSuccess(String result) {
                //当前渠道如果有退出界面，触发该回调
                //处理退出逻辑，
                moveTaskToBack(true);
                finish();
                //建议游戏按照下面代码逻辑，退出程序兼容性最好，否则可能会造成oppop、vivo等渠道退出不彻底，导致再次点击启动应用黑屏。
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                android.os.Process.killProcess(android.os.Process.myPid());
            }

            @Override
            public void onUpdate(String data) {

            }
        };
        FastSdk.hlAccountListener = new HLAccountListener() {
            @Override
            public void onRefreshUser(LoginResult result) {
                LogUtil.i("Hoolai refreshUser:" + result.toString());
                Toast.makeText(GameActivity.this, "小号切换成功" + result.getNickName(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onLoginSuccess(LoginResult result) {
                loginBtn.setVisibility(View.GONE);
                logoutBtn.setVisibility(View.VISIBLE);
                GameActivity.this.userResponse = result;
                sb.append("登录成功:" + result.toString());
                refreshView();
            }

            @Override
            public void onLoginFailed(String reason) {
                LogUtil.i("登录失败:" + reason);
                runOnUiThread(() -> {
                    sb.append(reason);
                    refreshView();
                });
            }

            @Override
            public void onLogout(Object... var1) {
                sb.append("已登出");
                logoutBtn.setVisibility(View.GONE);
                loginBtn.setVisibility(View.VISIBLE);
                refreshView();
            }
        };
        FastSdk.hlPaymentListener = new HLPaymentListener() {
            @Override
            public void onPaySuccess(String result) {
                sb.append("支付成功：" + result);
                refreshView();
            }

            @Override
            public void onPayFailed(String reason) {
                LogUtil.i("支付失败:" + reason);
                sb.append("支付失败：" + reason);
                refreshView();
            }

            @Override
            public void onQuerySuccess(final List<GoodsInfo> list) {
                LogUtil.i("商品信息获取成功:" + list.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (list.size() == 0) {
                            Toast.makeText(GameActivity.this, "商品信息获取为空", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //游戏获取到商品信息之后可以展示到游戏商品界面
                        //游戏需要有一套默认的商品信息配置,如果通过此接口获取不到商品信息时使用默认的商品配置

                        //---------------以下是demo代码-----------------------------------------------
                        Context context;
                        AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
                        ListView listView = new ListView(GameActivity.this);
                        listView.setAdapter(new ArrayAdapter(GameActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, list));
                        listView.setOnItemClickListener((parent, view1, position, id) -> {
                            GoodsInfo payInfo = list.get(position);
                            // 游戏支付时需要传的参数 示例
                            PayParams payParams = new PayParams();
                            payParams.setItemId(payInfo.getItemId());
                            payParams.setItemName(payInfo.getItemName());
                            payParams.setAmount(Integer.parseInt(payInfo.getItemPrice()));
                            payParams.setCount(Integer.valueOf(payInfo.getItemCount()));
                            //扩展信息，回调时原样返回,因为各渠道回调参数限制不一致。回调参数暂时只支持长度50。callBackInfo中不要使用这些符号：“|”、“=”、“+”、“/”。
                            payParams.setCallbackInfo("支付扩展信息,游戏透传参数" + UUID.randomUUID().toString().replace("-", ""));
//                    payParams.addExtendParam("isSupportThirdPayment", "true");//是否支持google之外的三方支付
//                    payParams.addExtendParam("payType", "1");// 1 钱包(默认此类型) 2 点卡,短代类支付,需要通过FastSdk.supportShortterm查询
//                    payParams.addExtendParam("currency", payInfo.getShowTag());//币种
                            FastSdk.pay(GameActivity.this, payParams);
                        });
                        builder.setView(listView);
                        builder.show();
                    }
                });
            }
        };
        FastSdk.onCreate(GameActivity.this);
    }

    //=========================以下是模拟游戏调用,都是必接接口========================================

    /**
     * 登录调用，必接
     *
     * @param view
     */
    public void onClickLogin(View view) {
//        SystemClock.sleep(50000);
        if (isInit) {
            FastSdk.login();
        } else {
            ToastUtils.toast("请初始化完成后操作");
        }
    }

    /**
     * 登出，必接
     */
    public void onClickInit(View view) {
        hoolaiSdkInit();
    }

    public void onClickLogout(View view) {
        if (isInit) {
            FastSdk.logout();
            if (userResponse != null) {
            } else {
                Toast.makeText(GameActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 海外版sdk需要通过此接口获取商品信息进行UI展示,商品信息会根据区域自动转化币种
     * 上国内渠道此接口可不接入，海外版必接
     */
    public void getPriceInfo(View view) {
        if (userResponse == null) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(userResponse.getUid() + "")) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }

        FastSdk.queryGoodsInfo();
//        FastSdk.checkPermissions(GameActivity.this, new String[]{"android.permission.BLUETOOTH_SCAN"});

    }

    /**
     * 支付调用，必接
     */
    public void doPay(View view) {
        pay(1);
    }


    public void customPay(View view) {
        String amount = String.valueOf(et_tv.getText());
        if (TextUtils.isEmpty(amount)) {
            Toast.makeText(GameActivity.this, "输入金额不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        pay(Integer.valueOf(amount));
    }

    private void pay(int amount) {
        if (userResponse == null) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isEnterGame) {
            Toast.makeText(this, "请先进服!", Toast.LENGTH_SHORT).show();
            return;
        }

        PayParams payParams = new PayParams();
        payParams.setItemId(et_itemId.getText().toString());//商品，要保证游戏内各个商品唯一（可以不传）
        //ItemName要求：这些特殊符号都不要有: + % # “ & / ? $ ^ *:) \ < > , |。否则会造成某些渠道支付报错如：华为渠道
        payParams.setItemName("钻石");//购买物品名称
        payParams.setAmount(amount);//金额(分)
        payParams.setCount(1);//购买商品数量，例如50元宝，传值50
        payParams.setCallbackInfo("callbackInfo");//扩展信息，回调时原样返回,因为各渠道回调参数限制不一致。回调参数暂时只支持长度50。callBackInfo中不要使用这些符号：“|”、“=”、“+”、“/”。
        payParams.setCurrency("CNY");//国内可不传或CNY
        payParams.setNotifyUrl("https://sdkhub-test.webapp.163.com/api/v1/test/notify/aebfw63ihmaaaaab");
//        payParams.setNotifyUrl("");
//        Map<String, String> map = new HashMap<>();
//        map.put("key", "");
//        payParams.setOpt(map);
        FastSdk.pay(GameActivity.this, payParams);
        SPUtils.getInstance().setStringValue(ITME_ID, et_itemId.getText().toString());
        //支付服务端回调地址,请在产品信息里配置。
    }

    /**
     * 退出接口调用，必接
     */
    public void onExit(View view) {
//        AudioTrackUtils.getInstance().stopPlay();
        exit();
    }

    public void exit() {
        FastSdk.exit();
    }

    /**
     * 账号管理,aab接入会展示账号管理界面
     *
     * @param view
     */
    public void onClickAccountmanage(View view) {      // 管理账号接口
        FastSdk.openAccountCenter(this);
    }


    /**
     * 数据上报,必接
     *
     * @param view
     */
    public void createRole(View view) {
        if (userResponse == null) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }
        Logger.i("上报创角");
        sendPlayRoleInfo(EventType.CreateRole);
        sendPlayRoleInfo(EventType.CustomerAction);
    }

    public void enterSever(View view) {
        if (userResponse == null) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }
        Logger.i("上报进服");
        isEnterGame = true;
        sendPlayRoleInfo(EventType.EnterServer);
    }

    public void levelUp(View view) {
        if (userResponse == null) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }
        Logger.i("上报升级");
        sendPlayRoleInfo(EventType.LevelUp);
    }

    public void share(View view) {
        startActivity(new Intent(this, ShareActivity.class));
    }

    private void sendPlayRoleInfo(EventType eventType) {
        PlayerInfo playerInfo = new PlayerInfo();
        playerInfo.setRoleId("1235761");//角色唯一标识id
        playerInfo.setRoleName("昵称2");
        playerInfo.setRoleLevel("11");
        playerInfo.setZoneId("100");
        playerInfo.setZoneName("华东大区");
        playerInfo.setServerId("100");
        playerInfo.setServerName("大唐战机");
        playerInfo.setBalance("66");
        playerInfo.setVip("1");
        playerInfo.setPartyName("帮派名称");
        playerInfo.setClassField("aaaa");
        playerInfo.setExtendAction("aaaatest");
        playerInfo.setExtra("a:arm,b:bom");//扩展信息,格式:key:value,key:value
        playerInfo.setPhylum("1");
        //对于sdk海外版自定义事件报送，需要在传ACTION的时候做如下处理，中文版可以忽略
        //userExtData.put(UserExtDataKeys.ACTION, "oversea_custom");
        //userExtData.put(UserExtDataKeys.CUSTOM_KEY,"海外版自定义事件名称");
        sb.append(eventType.getDesc() + "：\n" + playerInfo);
        refreshView();
        FastSdk.report(eventType, playerInfo);
    }


    public void setProxy(View v) {

//        settingProxy();
    }

    private void settingProxy() {
        String pwd = et_ip_pwd.getText().toString();
        String host = et_ip_host.getText().toString();
        String port = et_ip_port.getText().toString();
        if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(port)) {
//            FastSdk.setProxy(1, pwd, host, port);
            ToastUtils.toast("设置代理:" + host + ",pwd:" + pwd + ",prot:" + port);
            hoolaiSdkInit();
        } else {
            hoolaiSdkInit();
        }
    }

    public void setRpc(View v) {
        String pwd = et_pwd.getText().toString();
        String host = et_rpc.getText().toString();
        if (TextUtils.isEmpty(host) || TextUtils.isEmpty(pwd)) {
            ToastUtils.toast("ip或密码不可为空");
            return;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

        }
        return super.onKeyDown(keyCode, event);
    }

    private void refreshView() {
        sb.append("\n");
        contentTv.setText(sb);
        Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (scrollView == null || linearLayout == null) {
                    return;
                }
                //end要显示的位置，可以根据自己的需要来计算
                int end = (linearLayout.getMeasuredHeight() - scrollView.getHeight());
                if (end < 0) {
                    end = 0;
                }
                scrollView.scrollTo(0, end);
            }
        }, 500);//延迟500ms启动
    }

    public void openService(View view) {
        FastSdk.openService(this);
    }

    public void gameInfoData(View view) {
        String action = "game_xxx";
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("xxx", 123);
        hashMap.put("ooo", "321");
        FastSdk.gameDataReport(action, hashMap);
    }
}