package com.sheep.gamegroup.view.activity;

import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.text.InputType;
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.BaseUMActivity;
import com.sheep.gamegroup.di.components.DaggerLoginComponent;
import com.sheep.gamegroup.di.modules.LoginModule;
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.presenter.LoginContract;
import com.sheep.gamegroup.presenter.LoginPresenter;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.ChannelContent;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.PreferenceUtils;
import com.sheep.gamegroup.util.SelfCountDownTimer;
import com.sheep.gamegroup.util.TestUtil;
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.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.LOGIN_QQ;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.LOGIN_WX;

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

public class LoginAct extends BaseUMActivity implements LoginContract.View {

    @Inject
    LoginPresenter mPresenter;
    @BindView(R.id.login_agreement_cb)
    AppCompatCheckBox loginAgreementCb;
    @BindView(R.id.login_agreement_tv)
    TextView loginAgreementTv;
    @BindView(R.id.login_agreement_ll)
    LinearLayout loginAgreementLl;
    @BindView(R.id.iv_wx)
    ImageView ivWx;
    @BindView(R.id.iv_qq)
    ImageView ivQq;
    @BindView(R.id.login_other_ll)
    LinearLayout loginOtherLl;
    @BindView(R.id.login_et_account)
    AppCompatEditText loginEtAccount;
    @BindView(R.id.login_et_code)
    AppCompatEditText loginEtCode;
    @BindView(R.id.login_btn_code)
    TextView loginBtnCode;
    @BindView(R.id.login_et_scope)
    AppCompatEditText loginEtScope;
    @BindView(R.id.test_change)
    TextView testChange;
    @BindView(R.id.test_change_user)
    TextView testChangeUser;


    @Override
    protected int getLayoutId() {
        return R.layout.login_act_layout;
    }
    private LoginAct activity;
    @Override
    public void initView() {
        activity = this;
        DaggerLoginComponent.builder()
                .netComponent(SheepApp.get(this).getNetComponent())
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
        TestUtil.testChange(this, (TextView) findViewById(R.id.test_change));
        TestUtil.testChangeUser(this, (TextView) findViewById(R.id.test_change_user));

        if (TestUtil.isTest()) {
            loginEtAccount.setInputType(InputType.TYPE_CLASS_TEXT);
            loginEtAccount.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)});
        }
    }


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

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

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

    @Override
    public void initData() {

    }

    private void goWeixin() {
        LOGIN_WX.onEvent();
        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) {
                mPresenter.logByAuther(1, data.get("access_token"), data.get("openid"));
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                hideProgress();
                String str = t.getMessage();
                if (str.indexOf("2008") > 0) {
                    G.showToast("微信授权失败,请先安装微信客户端 在登录吧！");

                } else {
                    G.showToast("微信授权失败  请检查网络是否正常");

                }

            }

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

    }


    private void loginQQ() {
        LOGIN_QQ.onEvent();
        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) {
//                mPresenter.logByAuther(2,data.get("openid"));
                mPresenter.logByAuther(2, 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) {

                hideProgress();
            }
        });


    }


    @Override
    public void NetSuccess(int code, String msg, String invitation_code) {
        G.showToast(msg);
        hideProgress();
        Jump2View.getInstance().goHomePageView(this, invitation_code);

    }

    @Override
    public void NetError(int code, String errorMsg) {
        G.showToast(errorMsg);
        hideProgress();

    }


    @OnClick({R.id.login_agreement_tv, R.id.iv_wx, R.id.iv_qq, R.id.login_btn_code, R.id.login_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_agreement_tv:
                Jump2View.getInstance().tryShowAgreement(this, new Action1<String>() {
                    @Override
                    public void call(String msg) {
                        if (!TextUtils.isEmpty(msg)) {
                            G.showToast(msg);
                        }
                    }
                });
                break;
            case R.id.iv_wx:
                if (checkAgreement())
                    goWeixin();
                break;
            case R.id.iv_qq:
                if (checkAgreement())
                    loginQQ();
                break;
            case R.id.login_btn_code:
                etPhone = loginEtAccount.getText().toString().trim();
                getCaptcha();
                break;
            case R.id.login_commit:
                etPhone = loginEtAccount.getText().toString().trim();
                etCode = loginEtCode.getText().toString().trim();
                if (TestUtil.isTest() && TextUtils.isEmpty(etCode) && !TextUtils.isEmpty(etPhone)) {
                    goMain(etPhone);
                    TestUtil.addUser(etPhone);
                    return;
                }
                loginByPhoneCaptcha();
                break;
        }
    }
    private void goMain(String openId) {
        SpUtils.saveToken(getApplicationContext(), openId);
        Jump2View.getInstance().goHomePageView(this, null);
        ActivityManager.getInstance().endActivity(LoginAct.class);
        finish();
    }

    /**
     * 登录
     */
    private void loginByPhoneCaptcha() {
        if (!checkPhoneInput()) {
            return;
        }
        if (!checkCodeInput()) {
            return;
        }
        String scope = loginEtScope.getText().toString();
        if(TextUtils.isEmpty(scope)){
            scope = ChannelContent.getInstance().getChannel_name();
        }
        showProgress();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", etPhone);
        jsonObject.put("sec_code", etCode);
        jsonObject.put("invitation_code", scope);
        PreferenceUtils.setPrefString(SheepApp.mContext, UMConfigUtils.LOGIN_TYPE, UMConfigUtils.Source.SHEEP);
        SheepApp.getInstance().getNetComponent().getApiService().loginByCaptcha(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
                        if (baseMessage == null) {
                            return;
                        }
                        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().setUserEntity(loginEty.getUser());
                        }

                        Jump2View.getInstance().goHomePageView(activity, EntityUtils.getUserCode(loginEty));
                        TestUtil.saveUser(loginEty);

                    }
                });

    }
    private String etPhone;
    private String etCode;
    private boolean canGetCaptchaPhone = true;
    private SelfCountDownTimer selfCountDownTimer;
    /**
     * 获取验证码
     */
    private void getCaptcha() {

        if (!canGetCaptchaPhone) {
            return;
        }
        if (!checkPhoneInput()) {
            return;
        }
        selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
        canGetCaptchaPhone = true;
        getCaptcha(etPhone, new Action1<BaseMessage>() {
            @Override
            public void call(BaseMessage baseMessage) {
                if(baseMessage != null)
                    selfCountDownTimer.start();
            }
        });
    }

    public void getCaptcha(String etPhone, final Action1<BaseMessage> action1) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", etPhone);
        SheepApp.getInstance().getNetComponent().getApiService().getCaptcha(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        action1.call(null);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        action1.call(baseMessage);
                    }
                });

    }
    private boolean checkPhoneInput() {
        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() {
        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;
    }
    private boolean checkAgreement() {
        if (loginAgreementCb.isChecked()) {
            return true;
        }
        G.showToast("温馨提示：您必须同意用户协议才能继续体验小绵羊APP！");
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (selfCountDownTimer != null) {
            selfCountDownTimer.cancel();
        }
    }

}
