package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
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.presenter.PhoneContract;
import com.sheep.gamegroup.presenter.PhonePresenter;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
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 javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 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;
    @BindView(R.id.no_bind_tel_img)
    ImageView no_bind_tel_img;
    @BindView(R.id.phone_icon_iv)
    ImageView phone_icon_iv;
    @BindView(R.id.code_icon_iv)
    ImageView code_icon_iv;

    @Inject
    PhonePresenter presenter;

    private Activity activity;

    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 = "绑定手机号";
    String mobiles;

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

    private int where_from;

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

    @Override
    public void initView() {
        activity = this;
        GlideImageLoader.setImage(no_bind_tel_img, "http://cdngame.kuaifazs.com/no_bind_tel_img.png");
        GlideImageLoader.setImage(phone_icon_iv, "http://cdngame.kuaifazs.com/phone_icon_iv.png");
        GlideImageLoader.setImage(code_icon_iv, "http://cdngame.kuaifazs.com/code_icon_iv.png");
        DaggerChangePhoneComponent.builder()
                .netComponent(SheepApp.getInstance().getNetComponent())
                .phoneModule(new PhoneModule(this))
                .build()
                .inject(this);
        where_from = getIntent().getIntExtra("where_from", 0);
        TitleBarUtils titleBarUtils = TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitle(this, noticeStr)
                .setTitleFinish(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toFinish();
                    }
                });
        int skip_login = SpUtils.getOrder(SpUtils.SKIP_LOGIN_FLAG);
        switch (where_from) {
            case FROM_SPLASH://非第一次登录(如：登录后直接重启)，老用户需要绑定手机号
                if(skip_login == 1){

                    startMainAct();
                }else {
                    titleBarUtils.setRightBtn(this, "跳过", 0, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            SpUtils.saveOrder(SpUtils.SKIP_LOGIN_FLAG, 1);
                            startMainAct();
                        }
                    });
                }

                break;
            case FROM_LOGIN://用户可以跳过
                if(skip_login == 1){

                    startMainAct();
                }else {
                    titleBarUtils.setRightBtn(this, "跳过", 0, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Jump2View.getInstance().checkLabel(activity, new Action1<BaseMessage>() {
                                @Override
                                public void call(BaseMessage baseMessage) {
                                    SpUtils.saveOrder(SpUtils.SKIP_LOGIN_FLAG, 1);
                                    startMainAct();
                                }
                            });
                        }
                    });
                }
                break;
            case 30001:
            default:
                break;
        }
        mobiles = DataUtil.getInstance().getUserMobile();
        if (!TextUtils.isEmpty(mobiles)) {//提示
            oldOrNew = 1;
            showChangeLayout.setVisibility(View.VISIBLE);
            changePhoneLayout.setVisibility(View.GONE);
            telTv.setText(mobiles);
            return;
        }
        refreshData();
    }

    /**
     * 跳转到首页
     */
    private void startMainAct() {
        Intent intent = new Intent(activity, ActMain.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
        G.showToast(activity.getString(R.string.login_success));
        activity.finish();
    }

    private void toFinish() {
        switch (where_from) {
            case FROM_SPLASH://非第一次登录(如：登录后直接重启)，老用户需要绑定手机号
                startMainAct();
                break;
            case FROM_LOGIN://第一次登录，老用户需要绑定手机号
                Jump2View.getInstance().checkLabel(activity, new Action1<BaseMessage>() {
                    @Override
                    public void call(BaseMessage baseMessage) {
                        startMainAct();
                    }
                });
                break;
            case 30001://新用户必须绑定手机号，正常情况是会在登录成功后
                Jump2View.getInstance().gotoLoginAgain();
            default:
                finish();
                break;
        }
    }

    @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() {
                onTimerRest();
            }
        };
    }

    @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);
        }
    }

    @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) {
                DataUtil.getInstance().setUserMobile(mobile);
                G.showToast(o);
                CommonUtil.getInstance().updateUserInfo(null);
                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);
        switch (where_from) {
            case FROM_LOGIN:
            case 30001:
                Jump2View.getInstance().checkLabel(activity, new Action1<BaseMessage>() {
                    @Override
                    public void call(BaseMessage baseMessage) {
//                        Intent intent = new Intent(activity, ActMain.class);
//                        activity.startActivity(intent);
//                        activity.finish();
                        startMainAct();
                    }
                });
                break;
            case FROM_SPLASH://非第一次登录(如：登录后直接重启)，老用户需要绑定手机号
                Intent intent = new Intent(activity, ActMain.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            default:
                finish();
                break;
        }
    }

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

    @Override
    public void bindTelSmsSuccess(BaseMessage o) {
        G.showToast("请查看手机验证码");
    }

    @Override
    public void bindTelSmsFail(BaseMessage o) {
        G.showToast(o);
        selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);

    }


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

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

    @Override
    public void onBackPressed() {
        toFinish();
    }

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

    public static final int FROM_LOGIN = 1;//第一次登录，老用户需要绑定手机号
    public static final int FROM_SPLASH = 2;//非第一次登录(如：登录后直接重启)，老用户需要绑定手机号
}
