package com.rv.rvmine.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.base.utils.tools.android.NetworkUtil;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.util.RxJavaManager;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.login.bean.SendCodeBean;
import com.rv.rvmine.R;
import com.rv.rvmine.R2;
import com.rv.rvmine.SwitchFragmentListener;

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

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

public class BindPhoneSecondFragment extends BaseFragment<CommonPresenter> {

    @BindView(R2.id.tv_phone)
    TextView tvPhone;
    @BindView(R2.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R2.id.et_phone_code)
    EditText etPhoneCode;
    @BindView(R2.id.btn_next)
    Button btnNext;
    private String phone;

    private Disposable mDisposable;

    @Override
    public int getViewLayout() {
        return R.layout.fragment_bind_phone_second;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ((SwitchFragmentListener) _mActivity).setTitle("验证手机号");
        phone = getArguments().getString("phone");
        if (!TextUtils.isEmpty(phone))
            tvPhone.setText(phone);

        etPhoneCode.addTextChangedListener(watcher);

        tvGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getPhone())) {
                    showToast(getString(com.rv.home.R.string.rv_phone_hint));
                    return;
                }
                if (getPhone().length() != 11) {
                    showToast("手机号码不正确");
                    return;
                }
                sendCode();
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getPhone()) || getPhone().length() != 11) {
                    showToast("手机号码不正确");
                    return;
                }

                if (TextUtils.isEmpty(getCode())) {
                    showToast("短信验证码为空");
                    return;
                }
                checkMobilecode();
            }
        });
    }

    /**
     * 获得手机号
     *
     * @return
     */
    private String getPhone() {
        return phone;
    }

    private String getCode() {
        return etPhoneCode.getText().toString().trim();
    }

    /**
     * 发送验证码
     */
    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 checkMobilecode() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("phone", getPhone());
        map.put("mobilecode", getCode());
        mPresenter.getData(1, ApiConfig.HTTP_URL_CHECK_MOBILE_CODE, BaseBean.class, map, true);
    }


    @Override
    protected void loadData(Bundle savedInstanceState) {

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 0) {
            showToast(getString(com.rv.home.R.string.rv_phone_code_toast));
            sendCode(60);
        } else if (requestType == 1) {
            ((SwitchFragmentListener) _mActivity).next();
        }
    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        if (getContext() != null && !NetworkUtil.isNetworkAvailable(getContext())) {
            showToast("网络异常，请检察您的网络");
            return;
        }
        if (!TextUtils.isEmpty(errorMsg))
            showToast(errorMsg);
    }

    /**
     * 发送验证码
     *
     * @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);

            }
        }, 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(getString(com.rv.home.R.string.rv_login_rest));

            }
        });
    }

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

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

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!TextUtils.isEmpty(getCode()) && getCode().length() >= 4) {
                btnNext.setBackgroundResource(R.drawable.shape_rv_bg_fdc349);
            } else {
                btnNext.setBackgroundResource(R.drawable.shape_rv_bg_fde6b5);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
