package cn.m4399.single.demo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import cn.m4399.single.api.RechargeOrder;
import cn.m4399.single.api.RechargeListener;
import cn.m4399.single.api.SingleOperateCenter;

import static cn.m4399.single.demo.MainActivity.TAG;
import static cn.m4399.single.demo.MainActivity.TOAST_PREFIX;

/*
 * 充值辅助类
 */
class RechargeController {
    private Activity mainActivity;
    private ArrayList<String> mSKUList = new ArrayList<>(); //临时存储购买成功的物品，当activity在活动时显示出来

    RechargeListener singleRechargeListener = new RechargeListener() {

        /*
         * 充值过程结束时SDK回调此方法
         *
         * 充值过程结束并不代表订单生命周期全部完成，SDK还需要查询订单状态，游戏
         * 要根据订单状态决定是否发放物品等
         *
         * @param msg 表示充值结果的友好的文本说明
         *
         */
        @Override
        public void onRechargeFinished(boolean success, String msg) {
            Log.d(TAG, "Pay: [" + success + ", " + msg + "]");
            showInToast(msg);
        }

        /*
         * 充值过程成功完成后，SDK会查询订单状态，根据订单状态状态正常则通知游戏发放物品
         *
         * @param shouldDeliver
         *  是否要发放物品
         * @param o
         *  封装了最后提交的订单信息的对象，主要包含以下成员，各成员都有getter方法
         *  payChannel：   充值渠道
         *  orderId：      	充值订单号
         *  je：			充值金额
         *  goods：        	购买的物品
         *
         * @return
         *  物品发放过程是否成功
         */

        @Override
        public synchronized boolean notifyDeliverGoods(boolean shouldDeliver, RechargeOrder o) {
            if (shouldDeliver) {
                Log.d(TAG, String.format(getString(R.string.demo_fmt_distribution_of_goods), o.toString()));
                showInToast(String.format(getString(R.string.demo_fmt_distribution_of_goods), o.toString()));
                mSKUList.add(String.format(getString(R.string.demo_fmt_recharge_detail), o.money(), o.commodity()));

                // 如果游戏因为某些原因发放失败，应返回false
                return true;
            }
            return false;
        }
    };

    RechargeController(Activity mainActivity) {
        this.mainActivity = mainActivity;
    }

    @SuppressLint("InflateParams")
    void doRecharge() {
        final View sv = LayoutInflater.from(mainActivity).inflate(R.layout.demo_dialog_recharge, null);
        final TextView tvMoney = sv.findViewById(R.id.demo_id_order_money);
        tvMoney.setText(String.valueOf(prevMoney()));
        final CheckBox checkSupportExcess = sv.findViewById(R.id.demo_id_check_se);
        checkSupportExcess.setChecked(prevSupportExcess());
        final TextView tvSubject = sv.findViewById(R.id.demo_id_edt_order_commodity);
        tvSubject.setText(prevCommodity());
        final CheckBox checkHasSubject = sv.findViewById(R.id.demo_id_has_subject);
        checkHasSubject.setChecked(prevHasSubject());

        new AlertDialog.Builder(mainActivity)
                .setTitle(R.string.demo_action_start_pay)
                .setView(sv)
                .setNegativeButton(R.string.demo_action_cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(R.string.demo_action_pay, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!TextUtils.isEmpty(tvMoney.getText())) {
                            RechargeOrder order =
                                    // 充值金额，整数，基本要求大于1，小于50000
                                    new RechargeOrder(Integer.parseInt(tvMoney.getText().toString()))
                                    //是否支持超出金额，这里是一个独立的接口，只要在充值之前调用都有作用
                                    .supportExcess(checkSupportExcess.isChecked())
                                    //是否传入商品名，这会影响商品在充值界面的显示
                                    .commodity(checkHasSubject.isChecked() ? tvSubject.getText().toString() : null)
                                    // 透传参数，JSON 字符串
                                    .passthrough(getString(R.string.demo_label_test_extra));
                            SingleOperateCenter.recharge(mainActivity, order);

                            dialog.dismiss();
                            KeepOrder(order, tvSubject.getText().toString());
                        }
                    }
                })
                .create()
                .show();
    }

    @SuppressLint("InflateParams")
    void showCommodities() {
        View container = LayoutInflater.from(mainActivity).inflate(R.layout.demo_dialog_products, null);
        ListView skuListView = container.findViewById(R.id.product_list);
        skuListView.setAdapter(new ArrayAdapter<>(mainActivity, android.R.layout.simple_list_item_1, mSKUList));

        new AlertDialog
                .Builder(mainActivity)
                .setTitle(mainActivity.getString(R.string.demo_title_buy_goods, mSKUList.size()))
                .setView(container)
                .setPositiveButton(getString(R.string.demo_action_sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    private String getString(int id) {
        return mainActivity.getString(id);
    }

    private void showInToast(String msg) {
        Toast.makeText(mainActivity, TOAST_PREFIX + msg, Toast.LENGTH_SHORT).show();
    }

    private void KeepOrder(RechargeOrder o, String subjectText) {
        pref().edit()
                .putInt("key_input_money", o.money())
                .putBoolean("key_support_excess", o.supportExcess())
                .putBoolean("key_has_subject", !TextUtils.isEmpty(o.commodity()))
                .putString("key_subject_text", subjectText)
                .apply();
    }

    private int prevMoney() {
        return pref().getInt("key_input_money", 1);
    }

    private boolean prevSupportExcess() {
        return pref().getBoolean("key_support_excess", true);
    }

    private boolean prevHasSubject() {
        return pref().getBoolean("key_has_subject", true);
    }

    private String prevCommodity() {
        return pref().getString("key_subject_text", mainActivity.getString(R.string.demo_value_order_product_sample));
    }

    private SharedPreferences pref() {
        return PreferenceManager.getDefaultSharedPreferences(mainActivity);
    }
}
