package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CertificationUtil;
import com.sheep.gamegroup.util.ChannelContent;
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.StringUtils;
import com.sheep.gamegroup.util.TestUtil;
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 java.util.Locale;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

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

public class ActBindMobileRegister extends BaseActivity {

    @BindView(R.id.bind_mobile_register_phone_iv)
    ImageView bindMobileRegisterPhoneIv;
    @BindView(R.id.bind_mobile_register_phone_et)
    AppCompatEditText bindMobileRegisterPhoneEt;
    @BindView(R.id.bind_mobile_register_code_iv)
    ImageView bindMobileRegisterCodeIv;
    @BindView(R.id.bind_mobile_register_code_et)
    AppCompatEditText bindMobileRegisterCodeEt;
    @BindView(R.id.bind_mobile_register_code_tv)
    TextView bind_mobile_register_code_tv;
    private Activity activity;


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

    @Override
    public void initView() {
        activity = this;
        GlideImageLoader.setImage(bindMobileRegisterPhoneIv, "http://cdngame.kuaifazs.com/phone_icon_iv.png");
        GlideImageLoader.setImage(bindMobileRegisterCodeIv, "http://cdngame.kuaifazs.com/code_icon_iv.png");
        TitleBarUtils.getInstance()
                .setTitle(this, "绑定手机号")
                .setTitleFinish(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
    }

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

            @Override
            public void onTimerTick(long millisUntilFinished, int countTime) {
                bind_mobile_register_code_tv.setText(String.format(Locale.CHINA, "%d s", countTime));
            }

            @Override
            public void onTimerFinish() {
                selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
            }
        };
    }

    private LoginEntity loginEntity;
    @Override
    public void initData() {
        loginEntity = (LoginEntity) getIntent().getSerializableExtra(LoginEntity.class.getSimpleName());
        if(loginEntity == null)//必须传入LoginEntity才能保证正常运行
            finish();
    }

    private SelfCountDownTimer selfCountDownTimer;
    /**
     * 获取验证码
     * captcha	string
     验证码 第二步需要
     mobile	string
     platform	string
     登录返回来的platform
     scope	string
     传kfzs为官包 传空为邀请包
     step	string
     步骤：first发验证码 second绑定
     token	string
     登录返回来的token
     * @param view
     */
    public void getCaptcha(View view) {
        //检查手机号
        final String mobile = bindMobileRegisterPhoneEt.getText().toString().trim();
        if(!StringUtils.isMobile(mobile)){
            G.showToast("请填写正确的手机号!");
            return;
        }
        bind_mobile_register_code_tv.setEnabled(false);
        //提交数据获取验证码
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile", mobile);
        jsonObject.put("platform", loginEntity.getPlatform());
        jsonObject.put("scope", ChannelContent.getInstance().getChannel_name());
        jsonObject.put("step", "first");
        jsonObject.put("token", loginEntity.getToken());
        SheepApp.getInstance().getNetComponent().getApiService().bindMobileRegister(jsonObject)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                mMobile = mobile;
                                G.showToast("验证码已经发送");
                                bindMobileRegisterCodeEt.requestFocus();
                                selfCountDownTimer.start();
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                G.showToast(baseMessage);
                                bind_mobile_register_code_tv.setEnabled(true);
                            }
                        });
    }
    private String mMobile;//获取验证码成功后得到手机号
    /**
     * 提交
     * @param view
     */
    public void toCommit(View view) {
        //检查验证码
        final String captcha = bindMobileRegisterCodeEt.getText().toString().trim();
        if(TextUtils.isEmpty(captcha)){
            G.showToast("验证码不能为空!");
            return;
        }
        if(captcha.length() != 6){
            G.showToast(getString(R.string.toast_warning_phone_captcha_image_code_size));
            return;
        }
        //提交数据注册手机号并绑定第三方账号
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("captcha", captcha);
        jsonObject.put("mobile", mMobile);
        jsonObject.put("platform", loginEntity.getPlatform());
        jsonObject.put("scope", ChannelContent.getInstance().getChannel_name());
        jsonObject.put("step", "second");
        jsonObject.put("token", loginEntity.getToken());
        SheepApp.getInstance().getNetComponent().getApiService().bindMobileRegister(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        LoginEntity loginEty = null;
                        try {
                            loginEty = JSONObject.parseObject(JSONObject.toJSONString(baseMessage.getData()), LoginEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (loginEty != null) {
                            SpUtils.saveToken(activity, loginEty.getToken());
                            DataUtil.getInstance().initUserEntity(loginEty.getUser());
                        }
                        if(TextUtils.isEmpty(SheepApp.getInstance().getGameCode())){
                            Jump2View.getInstance().checkCommendApp(activity, EntityUtils.getUserCode(loginEty));
                        }else {
                            CertificationUtil.newInstance().addCurUserToSdkLoginUser();
                            CertificationUtil.newInstance().authCertificationCode(activity, SpUtils.getToken(SheepApp.getInstance()));
                        }
                        TestUtil.saveUser(loginEty);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }

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