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

import android.annotation.SuppressLint;
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.alibaba.android.arouter.facade.annotation.Route;
import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
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.frame.rv.config.RvFrameConfig;
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 com.umeng.socialize.utils.SocializeUtils;

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;

/**
 * Created :Auser
 * Date: 2019/5/14.
 * Desc:用户登录
 */
@Route(path = Constance.ACTIVITY_URL_LOGINRV)
public class LoginRvActivity extends BaseLoginActivity<CommonPresenter> {
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.et_phone_code)
    EditText etPhoneCode;
    @BindView(R2.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R2.id.iv_clear_phone)
    ImageView ivClearPhone;
    @BindView(R2.id.iv_clear_code)
    ImageView ivClearCode;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
    private Disposable mDisposable;
    private String mOpenid;
    private String mUnionid;
    private String mHeadImg;
    private int mLoginType;
    private String mName;

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

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(getString(R.string.rv_phone_login));
        editListener(etPhone);
        editListener(etPhoneCode);
//        etPhone.setText(""+mActivity.getPackageName());
        initRxbus();
    }

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

    @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:
            case 2:
                processLoginData((RegisteredBean) result);
                break;
            case 10:
                setDataUser((BeanUserInfo)result);
                break;
        }
    }

    @OnClick({R2.id.tv_get_code, R2.id.tv_login, R2.id.iv_weixin, R2.id.iv_qq, R2.id.tv_pwd_login, R2.id.tv_registered, R2.id.iv_clear_phone, R2.id.iv_clear_code})
    public void onViewClicked(View view) {

        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.tv_login) {

            codeLogin();
        } else if (view.getId() == R.id.iv_weixin) {
            umLogin(SHARE_MEDIA.WEIXIN);
        } else if (view.getId() == R.id.iv_qq) {
            umLogin(SHARE_MEDIA.QQ);
        } else if (view.getId() == R.id.tv_pwd_login) {
            startActivity(PwdLoginActivity.getIntent(mActivity));
        } else if (view.getId() == R.id.tv_registered) {
            startActivity(RegisteredActivity.getIntent(mActivity, 0));
        } else if (view.getId() == R.id.iv_clear_phone) {
            clearEditData(etPhone);
        } else if (view.getId() == R.id.iv_clear_code) {
            clearEditData(etPhoneCode);
        }
    }

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

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

    /**
     * 第三方登陆，未注册走该方法
     *
     * @param errorMsg
     * @param errorType
     */
    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        if (errorType == RvFrameConfig.HTTP_STATE_OTHER_LOGIN) {
            startActivity(BingPhoneActivity.getIntent(mActivity, mOpenid, mHeadImg, mLoginType, mName, mUnionid));
        }
    }

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

    /**
     * 第三方登录
     */
    private void otherLogin(String openid, int isQQ) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("openid", openid);
        map.put("isQQ", isQQ);
        mPresenter.postData(1, ApiConfig.HTTP_URL_OTHER_LOGIN, RegisteredBean.class, map, true);
    }

    /**
     * 验证码登录
     */
    private void codeLogin() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        map.put("mobilecode", getCode());
        map.put("type", 2);
        mPresenter.postData(2, ApiConfig.HTTP_URL_PWD_LOGIN, RegisteredBean.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 (getPhone().length() > 0 && getCode().length() > 0) {
                    tvLogin.setEnabled(true);
                    tvLogin.setSelected(true);
                } else {
                    tvLogin.setEnabled(false);
                    tvLogin.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();
        }
    }


    /**
     * 登录成功回调
     *
     * @param share_media
     * @param i
     * @param data
     */
    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
        if (dialog != null) {
            SocializeUtils.safeCloseDialog(dialog);
        }
        mOpenid = data.get("openid");
        mHeadImg = data.get("iconurl");
        mLoginType = share_media.getName().equals("qq") ? 1 : 0;
        if (mLoginType == 0) {
            mUnionid = data.get("unionid");
        }
        mName = data.get("name");
        otherLogin(mOpenid, mLoginType);
    }


}
