package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.di.components.DaggerChangePhoneComponent;
import com.sheep.gamegroup.di.modules.PhoneModule;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.presenter.PhoneContract;
import com.sheep.gamegroup.presenter.PhonePresenter;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.SelfCountDownTimer;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.ex.DbException;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ljy on 2018/3/27.
 */

public class ChangeTelAct extends BaseActivity implements PhoneContract.View{
    @BindView(R.id.tel_tv)
    TextView telTv;
    @BindView(R.id.sure_change_tv)
    TextView sureTv;
    @BindView(R.id.show_change_layout)
    LinearLayout showChangeLayout;
    @BindView(R.id.phone_et_account)
    AppCompatEditText phoneEtAccount;
    @BindView(R.id.phone_et_code)
    AppCompatEditText phoneEtCode;
    @BindView(R.id.phone_et_code_old)
    AppCompatEditText phone_et_code_old;
    @BindView(R.id.phone_btn_code)
    TextView phoneBtnCode;
    @BindView(R.id.phone_btn_code_old)
    TextView phone_btn_code_old;
    @BindView(R.id.phone_tip_tv)
    TextView phone_tip_tv;
    @BindView(R.id.phone_sure_tv)
    TextView phoneSureTv;
    @BindView(R.id.change_phone_layout)
    LinearLayout changePhoneLayout;

    @Inject
    PhonePresenter presenter;

    private Activity activity;
    private final int CHANGGE_CLICK = 0;//切换手机按钮点击后
    private final int OLD_PHONE_CLICK = 1;//旧手机获取验证码后

    private int oldOrNew;   //1,绑定过   0，未绑定过

    private int step = 1;   //1、获取旧手机验证码 2、提交旧手机验证码 3、提交新手机号码 4、提交新手机获取的验证码
    private String sec_code;
    private String auth_code;
    private String mobile;

    private String hitStr = "请输入手机号";
    private String noticeStr = "绑定手机号";
    private UserEntity userEntity = null;
    String mobiles;

    //验证码倒计时
    private SelfCountDownTimer selfCountDownTimer;
    private boolean canGetCaptchaPhone = true;

    @Override
    protected int getLayoutId() {
        return R.layout.changge_tel_layout;
    }

    @Override
    public void initView() {
        activity = this;
        DaggerChangePhoneComponent.builder()
                .netComponent(SheepApp.get(activity).getNetComponent())
                .phoneModule(new PhoneModule(this))
                .build()
                .inject(this);

        TitleBarUtils.getInstance()
                .setTitle(this, noticeStr)
                .setTitleFinish(this);
        try {
            userEntity = MyDbManager.getInstance()
                    .dbFindUser();
        } catch (DbException e) {
            e.printStackTrace();
        }
        mobiles = SpUtils.getPhone(activity);
        if(mobiles != null && !TextUtils.isEmpty(mobiles)){//提示
            oldOrNew = 1;
            showChangeLayout.setVisibility(View.VISIBLE);
            changePhoneLayout.setVisibility(View.GONE);
            telTv.setText(mobiles+"");
            return;
        }
        refreshData();
    }

    @Override
    public void initListener() {
        selfCountDownTimer = new SelfCountDownTimer(60 * 1000, 1000, SelfCountDownTimer.FULL_SECOND) {
            @Override
            public void onTimerRest() {
                canGetCaptchaPhone = true;
                phoneBtnCode.setText(getString(R.string.get_captcha));
                phone_btn_code_old.setText(getString(R.string.get_captcha));
            }

            @Override
            public void onTimerTick(long millisUntilFinished, int counTime) {
                String textStr = counTime + " s";
                phoneBtnCode.setText(textStr);
                phone_btn_code_old.setText(textStr);
            }

            @Override
            public void onTimerFinish() {
                canGetCaptchaPhone = true;
                phoneBtnCode.setText(getString(R.string.get_captcha));
                phone_btn_code_old.setText(getString(R.string.get_captcha));
            }
        };
    }

    @Override
    public void initData() {


    }

    /**
     * refresh
     */
    public void refreshData(){
        showChangeLayout.setVisibility(View.GONE);
        changePhoneLayout.setVisibility(View.VISIBLE);
        if(oldOrNew == 1){
            hitStr = "请输入手机号码";
            noticeStr = "验证原手机";
            phoneEtAccount.setHint(hitStr+"");
//            phoneEtAccount.setText(mobiles+"");
        }else{
            step = 0;
            hitStr = "请输入手机号码";
            noticeStr = "绑定手机号";
            phoneEtAccount.setHint(hitStr+"");
            TitleBarUtils.getInstance()
                    .setTitle(this, noticeStr)
                    .setTitleFinish(this);
        }
    }

    @OnClick({ R.id.phone_btn_code, R.id.phone_sure_tv, R.id.sure_change_tv, R.id.phone_btn_code_old})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.phone_btn_code:
                sec_code = null;
                mobile = phoneEtAccount.getText().toString() +"";
                if(!checkPhoneInput(mobile)){
                    return;
                }
                if (!canGetCaptchaPhone) {
                    return;
                }
                if(oldOrNew == 0){
                    selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("mobile", mobile+"");
                    presenter.smsBindMobile(jsonObject);
                    canGetCaptchaPhone = false;
                    selfCountDownTimer.start();
                    return;
                }
                step = 3;
                submit();
                break;
            case R.id.phone_sure_tv://更换手机号
                sec_code = phoneEtCode.getText().toString()+"";
                mobile = phoneEtAccount.getText().toString() +"";
                if(!checkPhoneInput(mobile)){
                    return;
                }
                if(!checkCodeInput(sec_code)){
                    return;
                }
                if(oldOrNew == 0){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("mobile", mobile+"");
                    jsonObject.put("sec_code", sec_code+"");
                    presenter.bindPhone(jsonObject);
                    return;
                }
                step = 4;
                submit();
                UMConfigUtils.onEvent(UMConfigUtils.Event.USER_BIND_PHONE);
                break;
            case R.id.sure_change_tv:
                sec_code = phone_et_code_old.getText().toString()+"";
                if(!checkCodeInput(sec_code)){
                    return;
                }
                step = 2;
                submit();
//                Jump2View.getInstance().goPhoneLoginView(ChangeTelAct.this, 1);
                break;
            case R.id.phone_btn_code_old://旧手机获取验证码
                if (!canGetCaptchaPhone) {
                    return;
                }
                sec_code = null;
                step = 1;
                submit();
                break;
        }
    }

    /**
     * 提交
     */
    private void submit(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("step", step+"");
        switch (step){
            case 1:

                selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
                canGetCaptchaPhone = false;
                selfCountDownTimer.start();
                break;
            case 2:
                jsonObject.put("sec_code", sec_code+"");
                break;
            case 3:
                jsonObject.put("auth_code", auth_code+"");
                jsonObject.put("mobile", mobile+"");
                selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
                canGetCaptchaPhone = false;
                selfCountDownTimer.start();
                break;
            case 4:
                jsonObject.put("sec_code", sec_code+"");
                jsonObject.put("auth_code", auth_code+"");
                jsonObject.put("mobile", mobile+"");
                break;
        }
        presenter.switchPhone(jsonObject);
    }

    @Override
    public void returnGaptcha(Object o) {
        Log.e("---Gaptcha-", o.toString());
//        G.showToast(o.getMsg() + "");
    }

    @Override
    public void gaptchaFail(BaseMessage o) {
        G.showToast(o.getMsg() + "");
    }

    @Override
    public void returnLogindata(Object o) {

    }

    @Override
    public void loginFail(BaseMessage o) {

    }

    @Override
    public void changeTelSuccess(BaseMessage o) {
        try{
//            if(step == 1 || step == 3){
//                changeTelSuccess
//            }
            if(step == 2){
                oldOrNew = 1;

//                handler.sendEmptyMessage(CHANGGE_CLICK);
                refreshData();
                phoneBtnCode.setText(getString(R.string.get_captcha));
                canGetCaptchaPhone = true;
                if(selfCountDownTimer != null)
                    selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
            }else if(step == 4){
                SpUtils.savePhone(activity,mobile);
                G.showToast(o.getMsg()+"");

                EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.REFRESH_DATA_PHONE));
                finish();
            }
            if(o == null){
                G.showToast("网络错误");
                return;
            }
            if(o.getData() == null || o.getData().equals("")){
//                G.showToast(o.getMsg()+"");
                return;
            }
            G.showToast((o.getMsg()).equals("")?"提交成功":o.getMsg()+"");
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(o.getData()));
            auth_code = jsonObject.getString("auth_code");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void changeTelFail(BaseMessage o) {
        if(o == null){
            G.showToast("网络错误");
            return;
        }
        G.showToast(o.getMsg()+"");
    }

    @Override
    public void bindTelSuccess(BaseMessage o) {
        G.showToast(o.getMsg()+"");
        finish();
    }

    @Override
    public void bindTelFail(BaseMessage o) {
        G.showToast(o.getMsg()+"");
    }

    @Override
    public void bindTelSmsSuccess(BaseMessage o) {

    }

    @Override
    public void bindTelSmsFail(BaseMessage o) {
        G.showToast(o.getMsg() + "");

    }


    private boolean checkPhoneInput(String etPhone) {
        if (TextUtils.isEmpty(etPhone)) {
            showToast(getString(R.string.input_your_phone));
            return false;
        }
        if (etPhone.length() != 11) {
            showToast(getString(R.string.toast_warning_phone_number_size));
            return false;
        }
        return true;
    }
    private boolean checkCodeInput(String etCode) {
        if (TextUtils.isEmpty(etCode)) {
            showToast(getString(R.string.input_your_captcha));
            return false;
        }
        if (etCode.length() != 6) {
            showToast(getString(R.string.toast_warning_phone_captcha_image_code_size));
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(selfCountDownTimer != null){
            selfCountDownTimer.cancel();
        }
    }
}
