package com.rv.home.rv.module.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.util.RxJavaManager;
import com.ruiwenliu.wrapper.util.listener.TextChangedListener;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.BaseLoginActivity;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.login.bean.RegisteredBean;
import com.rv.home.rv.module.ui.login.bean.SendCodeBean;
import com.umeng.socialize.bean.SHARE_MEDIA;

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;

public class RegisteredActivity extends BaseLoginActivity<CommonPresenter> {
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.iv_clear_phone)
    ImageView ivClearPhone;
    @BindView(R2.id.et_phone_code)
    EditText etPhoneCode;
    @BindView(R2.id.iv_clear_code)
    ImageView ivClearCode;
    @BindView(R2.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R2.id.et_pwd)
    EditText etPwd;
    @BindView(R2.id.iv_clear_pwd)
    ImageView ivClearPwd;
    @BindView(R2.id.et_again_pwd)
    EditText etAgainPwd;
    @BindView(R2.id.iv_clear_again_pwd)
    ImageView ivClearAgainPwd;
    @BindView(R2.id.cb_annotations)
    CheckBox cbAnnotations;
    @BindView(R2.id.tv_registered)
    TextView tvRegistered;
    @BindView(R2.id.tv_agreement)
    TextView tvAgreement;


    private Disposable mDisposable;
    private boolean pwdShow;//密码
    private boolean confirmShow;//确认密码
    private int mType;

    public static Intent getIntent(Context context, int type) {
        return new Intent(context, RegisteredActivity.class).putExtra("type", type);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        mType = intent.getIntExtra("type", 0);
        titleView.setTitle(mActivity.getString(mType == 0 ? R.string.rv_phone_registered : R.string.rv_forget_pwd));
        tvRegistered.setText(mActivity.getString(mType == 0 ? R.string.rv_registered : R.string.rv_reset_pwd));
        cbAnnotations.setVisibility(mType == 0 ? View.VISIBLE : View.GONE);
        tvAgreement.setVisibility(mType == 0 ? View.VISIBLE : View.GONE);
        editListener(etPhone);
        editListener(etPhoneCode);
        editListener(etPwd);
        editListener(etAgainPwd);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                showToast(mActivity.getString(R.string.rv_phone_code_toast));
                break;
            case 1:
                processLoginData((RegisteredBean) result);
                break;
            case 10:
                setDataUser((BeanUserInfo) result);
                break;
        }
    }

    @OnClick({R2.id.iv_clear_phone, R2.id.iv_clear_code, R2.id.tv_get_code, R2.id.iv_clear_pwd, R2.id.iv_clear_again_pwd, R2.id.tv_agreement, R2.id.tv_registered})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.iv_clear_phone) {
            clearEditData(etPhone);
        } else if (view.getId() == R.id.iv_clear_code) {
            clearEditData(etPhoneCode);
        } else if (view.getId() == R.id.tv_get_code) {
            if (TextUtils.isEmpty(getPhone())) {
                showToast(mActivity.getString(R.string.rv_phone_hint));
                return;
            }
            sendCode(60);
        } else if (view.getId() == R.id.iv_clear_code) {
            pwdShow = !pwdShow;
            ivClearPwd.setSelected(pwdShow);
            etPwd.setTransformationMethod(pwdShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        } else if (view.getId() == R.id.iv_clear_pwd) {
            confirmShow = !confirmShow;
            ivClearPwd.setSelected(confirmShow);
            etPwd.setTransformationMethod(confirmShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());

        } else if (view.getId() == R.id.iv_clear_again_pwd) {
            confirmShow = !confirmShow;
            ivClearAgainPwd.setSelected(confirmShow);
            etAgainPwd.setTransformationMethod(confirmShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        } else if (view.getId() == R.id.tv_agreement) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title","用户协议")
                    .withString("url",ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type",15)
                    .navigation();
        } else if (view.getId() == R.id.tv_registered) {
            if (getPwd().length() < 8) {
                showToast(mActivity.getString(R.string.rv_pwd_length));
                return;
            }
            if (!getPwd().equals(getAgainPwd())) {
                showToast(mActivity.getString(R.string.rv_pwd_same));
                return;
            }

            if (mType == 1) {
                resetPwd();
                return;
            }
            if (cbAnnotations.isChecked() == false) {
                showToast(mActivity.getString(R.string.rv_confirm_agreement));
                return;
            }
            userRegister();
        }
    }


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

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

    /**
     * 注册
     */
    private void userRegister() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        headMap.put("dataType", "json");
        headMap.put("contentType", "application/json;charset-UTF-8");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        map.put("mobilecode", getCode());
        map.put("password", getPwd());
        mPresenter.postData(RvFrameConfig.AUTH_POST, 1, ApiConfig.HTTP_URL_USER_REGISTER, RegisteredBean.class, map, headMap, true);
    }

    /**
     * 重置密码
     */
    private void resetPwd() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        map.put("mobilecode", getCode());
        map.put("password", getPwd());
        mPresenter.postData(1, ApiConfig.HTTP_URL_PWD_RESET, RegisteredBean.class, map, true);
    }


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

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

    /**
     * 获得输入密码
     *
     * @return
     */
    private String getPwd() {
        return etPwd.getText().toString().trim();
    }

    ;

    /**
     * 获得再次输入密码
     *
     * @return
     */
    private String getAgainPwd() {
        return etAgainPwd.getText().toString().trim();
    }

    ;

    /**
     * 清除编辑数据
     */
    private void clearEditData(EditText text) {
        text.setText("");
    }

    /**
     * 文本输入监听
     *
     * @param editText
     */
    private void editListener(final EditText editText) {
        editText.addTextChangedListener(new TextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (editText.getId() == R.id.et_phone) {
                    ivClearPhone.setVisibility(getPhone().length() > 0 ? View.VISIBLE : View.GONE);
                } else if (editText.getId() == R.id.et_phone_code) {
                    ivClearCode.setVisibility(getCode().length() > 0 ? View.VISIBLE : View.GONE);
                } else if (editText.getId() == R.id.et_pwd) {
                    ivClearPwd.setVisibility(getPwd().length() > 0 ? View.VISIBLE : View.GONE);
                } else if (editText.getId() == R.id.et_again_pwd) {
                    ivClearAgainPwd.setVisibility(getAgainPwd().length() > 0 ? View.VISIBLE : View.GONE);
                }
//                switch (editText.getId()) {
//                    case R.id.et_phone:
//                        ivClearPhone.setVisibility(getPhone().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                    case R.id.et_phone_code:
//                        ivClearCode.setVisibility(getCode().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                    case R.id.et_pwd:
//                        ivClearPwd.setVisibility(getPwd().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                    case R.id.et_again_pwd:
//                        ivClearAgainPwd.setVisibility(getAgainPwd().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                }
                if (etPhone.length() > 0 && etPhoneCode.length() > 0 && etPwd.length() > 0 && etAgainPwd.length() > 0) {
                    tvRegistered.setEnabled(true);
                    tvRegistered.setSelected(true);
                } else {
                    tvRegistered.setEnabled(false);
                    tvRegistered.setSelected(false);
                }


            }
        });
    }

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

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

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

                tvGetCode.setEnabled(true);
                tvGetCode.setText(mActivity.getString(R.string.rv_login_rest));

            }
        });

    }

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


    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

    }
}
