package com.sheep.gamegroup.view.activity;

import android.content.Intent;
import android.support.annotation.StringDef;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
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.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.SelfCountDownTimer;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.jiuyan.samllsheep.BuildConfig;
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.TitleBarUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Locale;
import java.util.Map;

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

/**
 * 验证手机号后绑定第三方账号QQ或者微信
 * Created by realicing on 2018/9/3.
 * realicing@sina.com
 */
public class ActModifyThird extends BaseActivity {
    public static final String THIRD_TYPE_QQ = "modifyqzone";
    public static final String THIRD_TYPE_WX = "modifywechat";
    @BindView(R.id.modify_third_mobile_et)
    AppCompatEditText modifyThirdMobileEt;
    @BindView(R.id.modify_third_code_btn)
    TextView modifyThirdCodeBtn;
    @BindView(R.id.modify_third_code_et)
    AppCompatEditText modifyThirdCodeEt;

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

    private String type;
    @Override
    public void initView() {
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitle(this, "验证手机号")
                .setTitleFinish(this);
        type = getIntent().getStringExtra("type");
        if(StringUtils.isMobile(DataUtil.getInstance().getUserMobile())) {
            modifyThirdMobileEt.setText(DataUtil.getInstance().getUserMobile());
            modifyThirdMobileEt.setEnabled(false);
        }
        if(BuildConfig.DEBUG){
            modifyThirdMobileEt.setInputType(InputType.TYPE_CLASS_TEXT);
            modifyThirdMobileEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)});
        }
    }

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

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

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

    private String genre;


    @StringDef({THIRD_TYPE_QQ, THIRD_TYPE_WX})
    @Retention(RetentionPolicy.SOURCE)
    public @interface THIRD_TYPE {
    }
    @Override
    public void initData() {
        genre = getIntent().getStringExtra("type");
    }
    @OnClick({R.id.modify_third_code_btn, R.id.modify_third_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.modify_third_code_btn:
                getCaptcha(view);
                break;
            case R.id.modify_third_commit:
                toCommit(view);
                break;
        }
    }
    private String mMobile;
    /**
     * 获取验证码
     * captcha	string
     genre	string
     enum：modifyqzone,modifywechat
     mobile	string
     step	string
     enum：first,second
     * @param view
     */
    public void getCaptcha(View view) {
        //检查手机号
        final String mobile = modifyThirdMobileEt.getText().toString().trim();
        if(!StringUtils.isMobile(mobile)){
            G.showToast("请填写正确的手机号!");
            return;
        }
        modifyThirdCodeBtn.setEnabled(false);
        //提交数据获取验证码
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("genre", genre);
        jsonObject.put("mobile", mobile);
        jsonObject.put("step", "first");
        SheepApp.getInstance().getNetComponent().getApiService().modifyThirdSms(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        mMobile = mobile;
                        G.showToast("验证码已经发送");
                        modifyThirdCodeEt.requestFocus();
                        selfCountDownTimer.start();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        modifyThirdCodeBtn.setEnabled(true);
                    }
                });
    }
    /**
     * 检验验证码
     * @param view
     */
    public void toCommit(View view) {
        final String captcha = modifyThirdCodeEt.getText().toString().trim();
        if(TextUtils.isEmpty(captcha)){
            G.showToast("请输入验证码");
            if(BuildConfig.DEBUG && modifyThirdMobileEt.getText().toString().length() > 11){
                authorization_code = modifyThirdMobileEt.getText().toString().trim();
                modifyThird();
            }
            return;
        }
        //提交数据获取验证码
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("captcha", captcha);
        jsonObject.put("genre", genre);
        jsonObject.put("mobile", mMobile);
        jsonObject.put("step", "second");
        SheepApp.getInstance().getNetComponent().getApiService().modifyThirdSms(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        authorization_code = baseMessage.getData(String.class);
                        modifyThird();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }
    private String authorization_code;//验证手机成功后得到的token

    private void modifyThird() {
        switch (type){
            case THIRD_TYPE_QQ:
                modifyQQ();
                break;
            case THIRD_TYPE_WX:
                modifyWX();
                break;
        }
    }

    private void modifyQQ() {
        UMShareAPI.get(this).doOauthVerify(this, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                showProgress();
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                modifyThird("qzone", data.get("access_token"), data.get("openid"));
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                G.showToast("QQ授权失败  请检查网络是否正常");
                hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                G.showToast("您取消了QQ授权");
                hideProgress();
            }
        });
    }
    private void modifyWX() {
        UMShareAPI.get(this).doOauthVerify(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                showProgress();
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                modifyThird("wechat", data.get("access_token"), data.get("openid"));
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                G.showToast("微信授权失败  请检查网络是否正常");
                hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                G.showToast("您取消了微信授权");
                hideProgress();
            }
        });
    }

    /**
     * aaccess_token	string
     authorization_code	string
     open_id	string
     platform	string
            qzone, wechat
     s_from	string
            sheep, web_sheep
     */
    private void modifyThird(String platform, String access_token, String openid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", access_token);
        jsonObject.put("authorization_code", authorization_code);
        jsonObject.put("open_id", openid);
        jsonObject.put("platform", platform);
        jsonObject.put("s_from", "sheep");
        SheepApp.getInstance().getNetComponent().getApiService().modifyThird(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage);
                        CommonUtil.getInstance().updateUserInfo(null);
                        finish();
                    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        if(selfCountDownTimer != null)
            selfCountDownTimer.cancel();
        super.onDestroy();
    }
}
