package com.yidianling.user.mine;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.RoundCornerButton;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.user.R;
import com.yidianling.user.mine.data.AppDataManager;
import com.yidianling.ydl_pay.pay.PayActivity;
import com.yidianling.ydl_pay.pay.PayParams;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 充值
 * Created by softrice on 16/1/18.
 */
@Route(path = "/user/recharge")
public class RechargeActivity extends BaseActivity {
    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,true);
    }

    //    @BindView(R.id.recharge_rgv)
    RechargeGridView recharge_rgv;
    //    @BindView(R.id.recharge_design)
    TextView recharge_design;
    //    @BindView(R.id.recharge_tv)
    TextView recharge_tv;
    //    @BindView(R.id.recharge_et)
    EditText recharge_et;
    //    @BindView(R.id.rcb_next)
    RoundCornerButton rcb_next;
    private List<String> prices = new ArrayList<>();


    List<RoundCornerButton> mChild;

    float charge_money;

    public static Intent newIntent(Activity activity) {
        return new Intent(activity, RechargeActivity.class);
    }

    @Override
    protected int layoutResId() {
        return R.layout.user_mine_activity_recharge;
    }

    @Override
    protected void initDataAndEvent() {
        recharge_rgv = findViewById(R.id.recharge_rgv);
        recharge_design = findViewById(R.id.recharge_design);
        recharge_tv = findViewById(R.id.recharge_tv);
        recharge_et = findViewById(R.id.recharge_et);
        rcb_next = findViewById(R.id.rcb_next);
        rcb_next.setOnClickListener(v -> {
            if (judge()) {
                getRechageId();
            }
        });

        init();
    }


    void init() {

        initGV();

        recharge_tv.setOnClickListener(v -> {
            recharge_tv.setClickable(false);
            Animation translateAnimation = AnimationUtils.loadAnimation(RechargeActivity.this, R.anim.user_mine_recharge_text);
            recharge_tv.startAnimation(translateAnimation);
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    for (int i = 0; i < mChild.size(); i++) {
                        mChild.get(i).setBg(0xffeeeeee);
                        mChild.get(i).setTextColor(0xff000000);
                    }
                    charge_money = 0;
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    recharge_et.setVisibility(View.VISIBLE);
                    recharge_et.requestFocus();
                    recharge_et.setOnClickListener(v1 -> {
                        recharge_et.setCursorVisible(true);
                        for (int i = 0; i < mChild.size(); i++) {
                            mChild.get(i).setBg(0xffeeeeee);
                            mChild.get(i).setTextColor(0xff000000);
                        }
                        charge_money = 0;
                    });

                    final int[] local = new int[2];
                    recharge_et.getLocationOnScreen(local);

                    Timer timer = new Timer();
                    TimerTask timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            Instrumentation mInst = new Instrumentation();
                            mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                                    SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, local[0], local[1], 0));    //x,y 即是事件的坐标
                            mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                                    SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, local[0], local[1], 0));
                        }
                    };
                    timer.schedule(timerTask, 500);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        });

    }

    private void initGV() {
        for (int i = 0; i < 6; i++) {
            prices.add(String.valueOf(i * 50 + 50) + "元");
        }
        recharge_rgv.setTexts(prices);
        charge_money = Integer.valueOf(prices.get(0).replace("元", ""));
        mChild = recharge_rgv.getChildList();
        recharge_rgv.setItemClickListener((view, position) -> {
            if (recharge_et.getVisibility() == View.VISIBLE) {
                recharge_et.setText("");
                recharge_et.setCursorVisible(false);
            }
            for (int i = 0; i < mChild.size(); i++) {
                mChild.get(i).setBg(0xffeeeeee);
                mChild.get(i).setTextColor(0xff000000);
            }
            charge_money = Integer.valueOf(prices.get(position).replace("元", ""));
            mChild.get(position).setBg(getResources().getColor(R.color.platform_main_theme));
            mChild.get(position).setTextColor(0xffffffff);

        });
    }

    private static final int REQUEST_PAY = 0;

    private String payId;

    @SuppressLint("CheckResult")
    private void getRechageId() {
        showProgressDialog("");

        AppDataManager.INSTANCE.getHttp().getRechargeId(new RechargeParam(charge_money + ""))
                .compose(RxUtils.resultData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(recharge -> {
                    dismissProgressDialog();
                    PayParams payParams = new PayParams();
                    payParams.setTitle("充值");
                    payParams.setType(PayParams.RECHARGE);
                    payParams.setPayId(recharge.rechargeId);
                    payParams.setNeedPay(charge_money);
                    payParams.setBtnPayText("（￥" + charge_money + "）确认付款");
                    payId = recharge.rechargeId;

                    RechargeActivity.this.startActivityForResult(PayActivity.Companion.newIntent(RechargeActivity.this, payParams), REQUEST_PAY);

                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        dismissProgressDialog();
                        ToastHelper.Companion.show(msg);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PAY && resultCode == RESULT_OK) {
            if (data != null) {
                if (!TextUtils.isEmpty(data.getStringExtra("rechargeId"))) {
                    payId = data.getStringExtra("rechargeId");
                }
            }

            Intent intent = new Intent(this, RechargeResultActivity.class);
            intent.putExtra("money", String.valueOf(charge_money));
            intent.putExtra("rechargeId", payId);
            startActivity(intent);
            finish();
        }
    }

    private boolean judge() {
        if (charge_money != 0) {//说明点击了某个金额,而不是输入的
            return true;
        } else {//说明是输入的
            String tmp = recharge_et.getText().toString();
            if (TextUtils.isEmpty(tmp)) {//输入的金额是空
                ToastUtil.toastShort("请输入金额");
                recharge_et.setText("");
                return false;
            }
            if (tmp.charAt(0) == '0') {
                ToastUtil.toastShort("金额不能以0开头");
                recharge_et.setText("");
                return false;
            }
            charge_money = Float.valueOf(tmp);
            return true;
        }
    }

}
