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.frame.rv.config.RvFrameConfig;
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.component.utils.DateUtils;
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 com.rv.rvmine.bean.BindCallBackBean;
import com.yuyife.okgo.OkGoUtil;

import java.util.HashMap;
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 BindPhoneThirdFragment extends BaseFragment<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.btn_next)
    Button btnNext;
    private String oldPhone;

    private Disposable mDisposable;


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

    @Override
    protected void initView(Bundle savedInstanceState) {

        oldPhone = getArguments().getString("phone");
        ((SwitchFragmentListener) _mActivity).setTitle("验证手机号");
        etPhoneCode.addTextChangedListener(watcher);
        etPhone.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;
                }
                if (getPhone().equals(oldPhone)) {
                    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;
                }
                updateMobile();
//                ((SwitchFragmentListener) _mActivity).changeSuccess(oldPhone);
            }
        });
    }

    @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) {
            showToast("手机号更改成功");
            BindCallBackBean bean = (BindCallBackBean) result;
            if (!TextUtils.isEmpty(bean.getData()))
                OkGoUtil.setToken(bean.getData(), DateUtils.getCurDate());
            ((SwitchFragmentListener) _mActivity).changeSuccess(getPhone());
        }
    }

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

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

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

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

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

    private void updateMobile() {
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            Map<String, String> head = new HashMap<>();
            head.put("Authorization", OkGoUtil.getToken());

            Map<String, String> body = new HashMap<>();
            body.put("username", getPhone());
            body.put("mobilecode", getCode());
            mPresenter.postData(RvFrameConfig.HOST, 1, ApiConfig.HTTP_URL_UPDATE_PHONE, BindCallBackBean.class, body, head, true);

        }
    }

    /**
     * 停止计时
     */
    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(getPhone()) && getPhone().length() == 11 && !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) {

        }
    };

}
