package com.android.chmo.ui.activity.me;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.chmo.R;
import com.android.chmo.app.ChmoApplication;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.AlipayRes;
import com.android.chmo.http.response.PayRes;
import com.android.chmo.http.service.OrderService;
import com.android.chmo.model.AliPayResult;
import com.android.chmo.utils.LoginUtils;
import com.google.gson.Gson;

import butterknife.BindView;
import butterknife.OnClick;


public class RechargeActivity extends BaseActivity {
    @BindView(R.id.balance)
    TextView balanceView;

    @BindView(R.id.inputValue)
    TextView valueEdit;
    @BindView(R.id.rechargeValue)
    TextView rechareView;

    @BindView(R.id.alipay_check)
    RadioButton alipayRadio;

    private float rechareValue = 0;

    private View checkView;

    @Override
    protected int getContentResId() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView() {
        balanceView.setText(ChmoApplication.getApp().getLoginUser().getCoin_a() + "元");

        valueEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
               String text = s.toString();
                if(!TextUtils.isEmpty(text)) {
                    if(null != checkView) {
                        checkView.setSelected(false);
                    }
                    try {
                        rechareValue = Float.parseFloat(text);
                        rechareView.setText(rechareValue + "元");
                    }catch (Exception e) {
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoginUtils.refreshUser();
    }

    @OnClick({R.id.value1,R.id.value2,R.id.value3,R.id.value4})
    public void valueSelect(View v){
        if(null != checkView) {
            checkView.setSelected(false);
        }
        switch (v.getId()) {
            case R.id.value1:
                rechareValue = 200;
                checkView = v;
                break;
            case R.id.value2:
                rechareValue = 500;
                checkView = v;
                break;
            case R.id.value3:
                rechareValue = 1000;
                checkView = v;
                break;
            case R.id.value4:
                rechareValue = 2000;
                checkView = v;
                break;
        }
        checkView.setSelected(true);
        valueEdit.setText("");
        rechareView.setText(rechareValue + "元");
    }


    @OnClick(R.id.pay)
    public void pay() {
        if(rechareValue == 0) {
            showToast("请选择充值金额");
            return;
        }
        alipay();
    }



    private  void alipay() {
        showLoading();
        OrderService.alipay(rechareValue, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                AlipayRes res = new Gson().fromJson(result,AlipayRes.class);
                if (res.msg.equals("success")) {
                    alipayRequest(res);
                }else {
                    showToast("订单提交失败");
                }
            }

            @Override
            public void onFailure(String error) {
                hideLoading();
                showToast("订单提交失败");
            }
        });
    }

    private void alipayRequest(final AlipayRes res) {
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                AliPayResult payResult = new AliPayResult((String)msg.obj);
                int result = 0;
                if (payResult.getResultStatus().equals("9000")) {
                    showToast("支付成功");
                    result = 1;
                    valueEdit.setText("");
                    rechareValue = 0;
                    if(null != checkView) {
                        checkView.setSelected(false);
                        checkView = null;
                    }
                }else if(payResult.getResultStatus().equals("8000")){
                    // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                    showToast("支付结果确认中");
                    return;
                }else {
                    showToast("支付失败");
                    result = 0;
                }

                payResultCallback(res, result);
            }
        };

      Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                String result = alipay.pay(res.data,true);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void payResultCallback(AlipayRes res, int result) {
        OrderService.alipayResult(res.paypk, res.outtradeno, result, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                PayRes payRes = new Gson().fromJson(result,PayRes.class);
                if(payRes.msg.equals("success")) {
                    balanceView.setText(payRes.coin_a + "元");
                    setResult(RESULT_OK);
                }
            }

            @Override
            public void onFailure(String error) {
            }
        });
    }
}
