package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.di.components.DaggerPhoneComponent;
import com.sheep.gamegroup.di.modules.PhoneModule;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.presenter.PhoneContract;
import com.sheep.gamegroup.presenter.PhonePresenter;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.SelfCountDownTimer;

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.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.xutils.ex.DbException;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

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

public class PhoneAct extends BaseActivity implements PhoneContract.View {
    Activity activity;
    @BindView(R.id.phone_et_account)
    AppCompatEditText phoneEtAccount;
    @BindView(R.id.phone_et_code)
    AppCompatEditText phoneEtCode;
    @BindView(R.id.phone_btn_code)
    TextView phoneBtnCode;
    @BindView(R.id.phone_sure_tv)
    TextView phoneSureTv;
    @BindView(R.id.phone_iv)
    ImageView phone_iv;

    @Inject
    PhonePresenter phonePresenter;
    @BindView(R.id.phone_tip_tv)
    TextView phoneTipTv;

    private SelfCountDownTimer selfCountDownTimer;
    private boolean canGetCaptchaPhone = true;

    private String etPhone;
    private String etCode;
    private int showNotice;//0:登录，1：旧手机号，2：新手机号

    private int  bindPhone;


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

    @Override
    public void initView() {
        activity = this;
        showNotice = getIntent().getIntExtra("show_notice", 0);
        TitleBarUtils
                .getInstance()
                .setTitle(this, "手机号登录")
                .setTitleFinish(this);
        DaggerPhoneComponent.builder()
                .netComponent(SheepApp.get(this).getNetComponent())
                .phoneModule(new PhoneModule(this))
                .build()
                .inject(this);
//        testData();
    }

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

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

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

    @Override
    public void initData() {
        if (showNotice == 0) {
            phoneTipTv.setVisibility(View.GONE);
        }else if(showNotice == 1){
            phoneTipTv.setVisibility(View.GONE);
            phone_iv.setVisibility(View.GONE);
        }else if(showNotice == 2){
            phoneTipTv.setVisibility(View.GONE);
            phone_iv.setVisibility(View.GONE);
        }
        else {
            phoneTipTv.setVisibility(View.VISIBLE);

        }

    }

    @OnClick({R.id.phone_et_account, R.id.phone_et_code, R.id.phone_btn_code, R.id.phone_sure_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.phone_et_account:
                break;
            case R.id.phone_et_code:
                break;
            case R.id.phone_btn_code:
                etPhone = phoneEtAccount.getText().toString().trim();
                getCaptcha();
                break;
            case R.id.phone_sure_tv:
                etPhone = phoneEtAccount.getText().toString().trim();
                etCode = phoneEtCode.getText().toString().trim();
                if(BuildConfig.DEBUG && TextUtils.isEmpty(etCode) && TextUtils.isEmpty(etPhone)){
                    goMain();
                    return;
                }
                loginByPhoneGaptcha();
                break;
        }
    }

    private boolean checkPhoneInput() {
        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() {
        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;
    }

    /**
     * 获取验证码
     */
    private void getCaptcha(){

        if (!canGetCaptchaPhone) {
            return;
        }
        if(!checkPhoneInput()){
            return;
        }
        selfCountDownTimer.reset(SelfCountDownTimer.FULL_SECOND);
        phonePresenter.getCaptcha(etPhone);
        canGetCaptchaPhone = false;
        selfCountDownTimer.start();
    }
    /**
     * 登录
     */
    private void loginByPhoneGaptcha(){
        if(!checkPhoneInput()){
            return;
        }
        if(!checkCodeInput()){
            return;
        }

        showProgress();
        phonePresenter.loginByCaptcha(etPhone, etCode);
    }

    @Override
    public void returnGaptcha(Object o) {
        Log.e("---Gaptcha-", o.toString());

    }

    /**
     * 验证码获取失败
     * @param o
     */
    @Override
    public void gaptchaFail(BaseMessage o) {
        hideProgress();
        G.showToast(o.getMsg() + "");

    }

    @Override
    public void returnLogindata(Object o) {
        hideProgress();
        if (o == null) {
            return;
        }
        BaseMessage baseMessage = (BaseMessage) o;
//        JSONObject a = JSON.parseObject(o.toString());
        Log.e("------data", baseMessage.getData() + "");
        LoginEntity loginEty = JSONObject.parseObject(JSONObject.toJSONString(baseMessage.getData()), LoginEntity.class);
        SpUtils.login(activity, loginEty.getToken());
        try {
            MyDbManager.getInstance().saveOrUpdateUser(loginEty.getUser());
            UserEntity userEntity = MyDbManager.getInstance().dbFindUser();
            Log.e("------userEntity", userEntity.getNickname() + "|" + userEntity.getMobile() + "");
            showToast("登录成功");
//            G.showToast(userEntity.getNickname() + "|" + userEntity.getMobile());
        } catch (Exception e) {
            e.printStackTrace();
        }

        Jump2View.getInstance().goHomePageView(activity, null);
        ActivityManager.getInstance().endActivity(LoginAct.class);
        finish();
        Log.e("---login_-", o.toString());
    }

    @Override
    public void loginFail(BaseMessage o) {
        hideProgress();
        G.showToast(o.getMsg() + "");
//        testData();
    }

    @Override
    public void changeTelSuccess(BaseMessage o) {

    }

    @Override
    public void changeTelFail(BaseMessage o) {

    }

    @Override
    public void bindTelSuccess(BaseMessage o) {

    }

    @Override
    public void bindTelFail(BaseMessage o) {

    }

    @Override
    public void bindTelSmsSuccess(BaseMessage o) {

    }

    @Override
    public void bindTelSmsFail(BaseMessage o) {

    }


    /**
     * 监听软键盘
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER){
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if(inputMethodManager.isActive()){
                inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    private void goMain() {
        // TODO: 2018/3/22  测试界面，过后删除s
        SpUtils.login(getApplicationContext(), "13626@395a75211751465f54789a7f459089bd");
//        startActivity(new Intent(this, ActMain.class));
        Jump2View.getInstance().goHomePageView(this, null);
        ActivityManager.getInstance().endActivity(LoginAct.class);
        finish();
    }


    private void testData(){
        try{
            String data = "{\n" +
                    "  \"data\": {\n" +
                    "    \"token\": \"12@38948cb4b6e74079615b154a80e3054b\",\n" +
                    "    \"user\": {\n" +
                    "      \"id\": 12,\n" +
                    "      \"mobile\": \"17628083502\",\n" +
                    "      \"nickname\": \"17628083502\",\n" +
                    "      \"balance\": 0,\n" +
                    "      \"invitation_code\": \"076031871\",\n" +
                    "      \"parent_code\": \"\",\n" +
                    "      \"total_asset\": 0,\n" +
                    "      \"last_login_time\": 1521280845,\n" +
                    "      \"create_time\": 1521279330,\n" +
                    "      \"update_time\": 1521279330,\n" +
                    "      \"avatar\": \"\",\n" +
                    "      \"access_token\": \"VOC1Qkg_R_KdbylyvvWwQA\",\n" +
                    "      \"refresh_token\": \"ZPgcoYhPSYWaZ5m-ySVoKw\",\n" +
                    "      \"open_id\": \"3135079\",\n" +
                    "      \"real_name\": \"\",\n" +
                    "      \"id_number\": \"\",\n" +
                    "      \"bank_card\": \"\",\n" +
                    "      \"total_withdraw\": 0,\n" +
                    "      \"wx_openid\": \"\"\n" +
                    "    }\n" +
                    "  }\n" +
                    "}";
            String showStr = "登录失败";
            Log.e("---login_-", data);
            JSONObject a = JSON.parseObject(data);
            Log.e("------data",a.get("data")+"");
            LoginEntity loginEty = JSON.parseObject(a.get("data").toString(), LoginEntity.class);
            SpUtils.login(activity, loginEty.getToken());
            try {
                MyDbManager.getInstance().saveOrUpdateUser(loginEty.getUser());
                UserEntity userEntity = MyDbManager.getInstance().dbFindUser();
                Log.e("------userEntity",userEntity.getNickname()+"|"+userEntity.getMobile()+"");
                showToast(userEntity.getNickname()+"|"+userEntity.getMobile());
            } catch (DbException e) {
                e.printStackTrace();
            }
            showStr = "登录成功";
//            String s1 = "523cbac3be1748ba65be01af9ca4412da011cc0196baf9fa54ce8d1f8b12b986";
//            String s2 = "2b08e160271fd9eeb8de2a7372782478425fe733e79b086fb4cb9353b793eaa6";
//
//            String e1 = "123123";
//            String d1 = "xxxx";
////        String hexStr = HexUtils.bytes2HexStr(Kfzssafe.XByteEncode(e1.getBytes()));
////        Log.e("j加密密1--", hexStr);
//            Log.e("解密2--", XXTEA.bytes2HexStr(XXTEA.Encrypt(e1, XXTEA.KEY).getBytes("utf-8")));
//            Log.e("解密3--", XXTEA.Decrypt(s1, XXTEA.KEY));
//            Log.e("解密4--", XXTEA.Decrypt(s2, XXTEA.KEY));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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