/**
O * Copyright (c) 2013 DuoKu Inc.
 */

package com.caimai.platform.demo.activity;

import java.util.UUID;

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

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.caimai.platform.demo.R;
import com.duoku.platform.DkErrorCode;
import com.duoku.platform.DkPlatform;
import com.duoku.platform.DkProtocolConfig;
import com.duoku.platform.DkProtocolKeys;
import com.duoku.platform.IDKSDKCallBack;
import com.duoku.platform.ui.DKContainerActivity;
import com.duoku.platform.ui.DKPaycenterActivity;

/**
 * Main Activity
 */
public class MainActivity extends BaseActivity implements OnClickListener {
    private ImageView mChangeAccountView;
    private TextView mGoldAmountView;
    private ImageView mRecharge;
    private ImageView mAccountPic;
    private AlertDialog dlg;
    public static String userid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mChangeAccountView = (ImageView) findViewById(R.id.dk_changeaccount);
        mGoldAmountView = (TextView) findViewById(R.id.dk_goldnum_text);
        mRecharge = (ImageView) findViewById(R.id.dk_recharge);

        mChangeAccountView.setOnClickListener(this);
        mGoldAmountView.setOnClickListener(this);
        mRecharge.setOnClickListener(this);

        mAccountPic = (ImageView) findViewById(R.id.dk_account_pic);
        mAccountPic.setOnClickListener(this);

        // 切换帐号功能支持回调。
        setDKChangeAccountCallBack();

        DkPlatform.showFloatView(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        // 充值
        if (mRecharge == v) {
            showRechargeAlert();
        }
    }

    public Intent getAccountIntent() {
        Bundle bundle = new Bundle();
        bundle.putInt(DkProtocolKeys.FUNCTION_CODE,
                DkProtocolConfig.FUNCTION_ACCOUNT);
        Intent intent = new Intent(this, DKContainerActivity.class);
        intent.putExtras(bundle);
        return intent;
    }

    private void setDKChangeAccountCallBack() {
        DkPlatform.setDKChangeAccountCallBack(new IDKSDKCallBack() {

            @Override
            public void onResponse(String paramString) {
                int resultCode = 0;
                JSONObject jsonObj;
                String _userid = "";
                try {
                    jsonObj = new JSONObject(paramString);
                    resultCode = jsonObj
                            .getInt(DkProtocolKeys.FUNCTION_STATE_CODE);// 用户登录状态
                    _userid = jsonObj
                            .getString(DkProtocolKeys.USER_ID);// 用户userid
                    if (!TextUtils.isEmpty(_userid)) {
                        userid = _userid;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                switch (resultCode) {
                    case DkErrorCode.DK_LOGIN_SUCCESS: {
                        // TODO 登录成功，不管之前是什么登录状态，游戏内部都要切换成新的用户
                        Toast.makeText(MainActivity.this, "登录成功",
                                Toast.LENGTH_SHORT).show();
                    }
                        break;
                    case DkErrorCode.DK_LOGIN_CANCELED: {
                        // TODO取消登录回调
                        Toast.makeText(MainActivity.this, "用户取消登录",
                                Toast.LENGTH_SHORT).show();
                    }
                        break;
                    default:
                        break;
                }

            }
        });
    }

    /**
     * 参数说明
     * 
     * @param amount 定额支付消费金额（人民币），如购买1元的物品或者游戏币，则amount为1；
     * @param exchangeRatio 人民币和游戏币兑换比，例如1元兑换100金币，则兑换比为100，需要在开发中心配置
     * @param strGamebiName 游戏币名称，如金币、符石、元宝等
     * @param strOrderId cp生成的订单号，充值结束后，百度移动服务器会通知业务服务器该订单号及充值结果
     * @param strPayDesc 支付描述，cp可以在此处自定义字段完成自己的需求，若不需要请传入”none”，请勿传null及空串
     * @param cpUserid 传入登录接口返回的userid
     * @return 返回Intent对象
     */
    // 特别注意：此处的参数二和参数三，均需在百度移动游戏开发者平台去进行配置，若不配置或配置错误，将会导致支付异常
    private Intent getRechargeIntent(int amount, int exchangeRatio,
            String strGamebiName, String strOrderId, String strPayDesc, String cpUserid) {
        Bundle bundle = new Bundle();
        bundle.putInt(DkProtocolKeys.FUNCTION_CODE,
                DkProtocolConfig.FUNCTION_Pay);
        bundle.putString(DkProtocolKeys.FUNCTION_AMOUNT, amount + ""); // 金额（转换成String）
        bundle.putString(DkProtocolKeys.FUNCTION_EXCHANGE_RATIO, exchangeRatio
                + ""); // 兑换比例
                       // （转换成String）
        bundle.putString(DkProtocolKeys.FUNCTION_ORDER_ID, strOrderId); // 订单号
        bundle.putString(DkProtocolKeys.FUNCTION_PAY_DESC, strPayDesc); // 支付描述
        bundle.putString(DkProtocolKeys.FUNCTION_GAMEBI_NAME, strGamebiName); // 游戏币名称
        bundle.putString(DkProtocolKeys.FUNCTION_USERID, cpUserid); // sdk下发的userid
        Intent intent = new Intent(this, DKPaycenterActivity.class);
        intent.putExtras(bundle);

        return intent;
    }

    /**
     * 进入代币充值界面
     */
    private void recharge(String strAmount) {
        UUID guid = UUID.randomUUID();
        String strOrderId = guid.toString();
        strOrderId = strOrderId.replace("-", "".trim());

        int amount = Integer.valueOf(strAmount);
        int exchangeRatio = 100;// 人民币和游戏币兑换比，例如1元兑换100金币，则兑换比为100，需要在开发中心配置
        // 退出支付中心回调接口，cp收到该通知后可根据参数四去自家服务器查询订单是否成功
        String cpUserid = userid;// 调用登录接口返回给用户的userid，例如961015611
        DkPlatform.invokeActivity(
                this,
                getRechargeIntent(amount, exchangeRatio, "金币", strOrderId,
                        "acv", cpUserid), new IDKSDKCallBack() {

                    @Override
                    public void onResponse(String paramString) {
                        Log.i(getClass().getName(), paramString);

                        try {
                            JSONObject jsonObject = new JSONObject(paramString);

                            int mStateCode = jsonObject
                                    .getInt(DkProtocolKeys.FUNCTION_STATE_CODE); // 状态码
                            String mMessage = jsonObject
                                    .getString(DkProtocolKeys.FUNCTION_MESSAGE); // 信息
                            String mOrderId = (!jsonObject
                                    .isNull(DkProtocolKeys.FUNCTION_ORDER_ID)) ? jsonObject
                                    .getString(DkProtocolKeys.FUNCTION_ORDER_ID)
                                    : ""; // 订单号

                            if (mStateCode == DkErrorCode.DK_ORDER_NEED_CHECK) { // 需要查询订单
                                Toast.makeText(MainActivity.this,
                                        "退出充值中心,此时应去查询订单:" + mOrderId + "的状态！",
                                        Toast.LENGTH_LONG).show();
                            } else if (mStateCode == DkErrorCode.DK_ORDER_NOT_CHECK) { // 不需要查询订单
                                Toast.makeText(MainActivity.this, mMessage,
                                        Toast.LENGTH_LONG).show();
                            }

                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void showRechargeAlert() {

        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        final View DialogView = inflater.inflate(R.layout.chargedialog, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(DialogView);

        dlg = builder.create();
        dlg.show();

        final EditText ed = (EditText) DialogView
                .findViewById(R.id.dk_chargetype);
        Button btConfirm = (Button) DialogView.findViewById(R.id.dk_confirm);
        Button btCancel = (Button) DialogView.findViewById(R.id.dk_cancel);
        btConfirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String chargeNum = ed.getText().toString();

                if (TextUtils.isEmpty(chargeNum) || "0".equals(chargeNum)) {
                    Toast.makeText(MainActivity.this, "充值金额不得为0或者空", Toast.LENGTH_SHORT)
                            .show();
                    return;
                }

                // 单次最大支付金额为99999元,且不得为0和空
                if (isNumeric(chargeNum)) {
                    if (chargeNum.length() > 5) {
                        Toast.makeText(MainActivity.this, "请输入正确金额",
                                Toast.LENGTH_LONG).show();
                    }
                    else {
                        dlg.dismiss();
                        recharge(chargeNum);
                    }
                } else
                    Toast.makeText(MainActivity.this, "请输入正确金额",
                            Toast.LENGTH_LONG).show();
            }
        });
        btCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });

    }

    /**
     * 关闭悬浮窗的操作
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        DkPlatform.destroy(this); // 释放资源
    }

    @Override
    public void finish() {
        DkPlatform.closeFloatWindow();
        super.finish();
    }

    public boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}