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.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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.rv.home.rv.module.basic.bean.BeanUserInfo;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.login.bean.CheckLoginBean;
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;

/**
 * Created :Auser
 * Date: 2019/5/21.
 * Desc:绑定手机号
 */
public class BingPhoneActivity 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.tv_bind)
    TextView tvBind;

    private String mOpenid;
    private String mHeadImg;
    private String mName;
    private int mIsQQ;
    private String mUnionid;
    private Disposable mDisposable;

    public static Intent getIntent(Context context, String openid, String headImg, int isQQ, String name, String uId) {
        return new Intent(context, BingPhoneActivity.class)
                .putExtra("openid", openid)
                .putExtra("headImg", headImg)
                .putExtra("isQQ", isQQ)
                .putExtra("name", name)
                .putExtra("uId", uId);
    }


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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(mActivity.getString(R.string.rv_phone_bind));
        mOpenid = intent.getStringExtra("openid");
        mHeadImg = intent.getStringExtra("headImg");
        mName = intent.getStringExtra("name");
        mIsQQ = intent.getIntExtra("isQQ", 1);
        mUnionid = intent.getStringExtra("uId");
        editListener(etPhone);
        editListener(etPhoneCode);
    }

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

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                showToast(mActivity.getString(R.string.rv_phone_code_toast));
                break;
            case 1:
                CheckLoginBean checkLoginBean = (CheckLoginBean) result;
                switch (checkLoginBean.getData().getType()) {
                    case 0:
                        showToast(mIsQQ == 1 ? "该手机号已经绑定过一个QQ，请您更换手机号！" : "该手机号已经绑定过一个微信，请您更换手机号！");
                        break;
                    case 1:
                        otherLoginBind(getPhone(), getCode(), "", mName, mHeadImg, mOpenid, 1, mIsQQ, mUnionid);
                        break;
                    case 2:
                        startActivity(ConfirmPwdActivity.getIntent(mActivity, mOpenid, mHeadImg, mIsQQ, mName, getPhone(), getCode(), mUnionid));
                        finish();
                        break;
                }
                break;
            case 2:
                processLoginData((RegisteredBean) result);
                break;
            case 10:
                setDataUser((BeanUserInfo)result);
                break;
        }
    }


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

    @OnClick({R2.id.iv_clear_phone, R2.id.iv_clear_code, R2.id.tv_get_code, R2.id.tv_bind})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_clear_phone) {
            clearEditData(etPhone);
        } else if (id == R.id.iv_clear_code) {
            clearEditData(etPhoneCode);
        } else if (id == R.id.tv_get_code) {
            if (TextUtils.isEmpty(getPhone())) {
                showToast(mActivity.getString(R.string.rv_phone_hint));
                return;
            }
            sendCode(60);
        } else if (id == R.id.tv_bind) {
            checkPhone();
        }
    }

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


    /**
     * 检查手机号是否绑定
     */
    private void checkPhone() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        mPresenter.postData(1, ApiConfig.HTTP_URL_CHECK_PHONE, CheckLoginBean.class, map, true);
    }

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

    /**
     * 获得验证码
     *
     * @return
     */
    private String getCode() {
        return etPhoneCode.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);
                }

                if (etPhone.length() > 0 && etPhoneCode.length() > 0) {
                    tvBind.setEnabled(true);
                    tvBind.setSelected(true);
                } else {
                    tvBind.setEnabled(false);
                    tvBind.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) {

    }


}
