package com.xxrv.wallet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.util.RxJavaManager;
import com.ruiwenliu.wrapper.util.listener.TextChangedListener;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.Cookie;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.login.bean.SendCodeBean;
import com.xxrv.wallet.R;
import com.xxrv.wallet.R2;
import com.xxrv.wallet.api.WalletApi;
import com.xxrv.wallet.event.SetPasswordSuccessEvent;
import com.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class SetPayPwdActivity extends BaseStatusActivity<CommonPresenter> {

    @BindView(R2.id.ll_send_code)
    LinearLayout llSendCode;
    @BindView(R2.id.edt_phone)
    EditText edtPhone;
    @BindView(R2.id.edt_identify_code)
    EditText edtIdentifyCode;
    @BindView(R2.id.btn_item_send)
    Button btnSend;
    @BindView(R2.id.btn_item_next)
    Button btnNext;
    @BindView(R2.id.img_clear_phone)
    ImageView imgClearPhone;

    private Disposable mDisposable;


    public static Intent getIntent(Context context) {
        return new Intent(context, SetPayPwdActivity.class);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType){
            case 0:
                showToast("验证码发送成功！");
                break;
            case 2:
                startActivity(SetPayPwdActivity2.getIntent(mActivity,getPhone(),getCode()));
                break;
        }
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_set_pay_pwd;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("设置支付密码");
        editListener(edtPhone);
        editListener(edtIdentifyCode);
        initRxbus();
        BeanUserInfo.UserInfo userInfo = getUserInfo();

        if (userInfo !=null){
            edtPhone.setText(userInfo.getUsername());
            edtPhone.setEnabled(false);
        }
    }

    private void initRxbus() {
        RxBus.tObservable(SetPasswordSuccessEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new com.frame.base.bus.Observer<SetPasswordSuccessEvent>(disposable) {
                    @Override
                    public void onNext(SetPasswordSuccessEvent event) {
                        finish();
                    }
                });
    }

    /**
     * 文本输入监听
     *
     * @param editText
     */
    private void editListener(final EditText editText) {
        editText.addTextChangedListener(new TextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (getPhone().length() > 0 && getCode().length() > 0) {
                    btnNext.setEnabled(true);
                    btnNext.setBackground(getResources().getDrawable(R.drawable.bg_next_btn_able));
                } else {
                    btnNext.setEnabled(false);
                    btnNext.setBackground(getResources().getDrawable(R.drawable.bg_next_btn_unable));
                }
            }
        });
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.e("xxxxx", charSequence.toString());
        }


        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.e("xxxxx", charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    @OnClick({R2.id.btn_item_send, R2.id.btn_item_next})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_item_send){
            if (TextUtils.isEmpty(getPhone())) {
                showToast(mActivity.getString(com.rv.home.R.string.rv_phone_hint));
                return;
            }
            sendCode(60);
        }else if (id == R.id.btn_item_next){
             setNext();
        }
    }

    /**
     * 下一步
     */
    private void setNext() {
        if (TextUtils.isEmpty(getPhone())) {
            showToast(mActivity.getString(com.rv.home.R.string.rv_phone_hint));
            return;
        }

         if (TextUtils.isEmpty(getCode())){
             showToast("验证码不能为空！");
             return;
         }

        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("phone", getPhone());
        map.put("mobilecode", getCode());
        mPresenter.getData(RvFrameConfig.HOST,2, WalletApi.HTTP_URL_CHECK_CHECKCODE, BaseBean.class, map,headMap, true);
    }

    /**
     * 获得手机号
     *
     * @return
     */
    private String getPhone() {
        return edtPhone.getText().toString().trim();
    }

    /**
     * 获得验证码
     *
     * @return
     */
    private String getCode() {
        return edtIdentifyCode.getText().toString().trim();
    }


    /**
     * 发送验证码
     */
    private void sendCode() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        map.put("type", 4);
        map.put("code", Cookie.getStringValue(getApplicationContext(), "code"));
        mPresenter.postData(0, ApiConfig.HTTP_URL_SEND_CODE, SendCodeBean.class, map, true);
    }


    /**
     * 发送验证码
     *
     * @param timeLong 验证码时长
     */
    private void sendCode(final int timeLong) {
        RxJavaManager.getInstance().sendCode(timeLong, new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                btnSend.setEnabled(false);
                sendCode();
            }
        }, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(Long aLong) {
                btnSend.setText("" + aLong + "s");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

                btnSend.setEnabled(true);
                btnSend.setText(mActivity.getString(com.rv.home.R.string.rv_login_rest));

            }
        });

    }

    /**
     * 停止计时
     */
    public void stopCarousel() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopCarousel();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopCarousel();
    }
}
