package com.itant.shiwushu.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.itant.shiwushu.MainActivity;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.LAFBaseActivity;
import com.itant.shiwushu.bean.User;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.manager.UserManager;
import com.itant.shiwushu.tool.ActivityTool;
import com.itant.shiwushu.ui.forget.ForgetActivity;
import com.itant.shiwushu.ui.register.RegisterActivity;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

/**
 * Created by Jason on 2018/10/2.
 */

public class LoginActivity extends LAFBaseActivity implements View.OnClickListener, LoginContract.View {
    private static final String APP_ID = "1107887184";
    private Tencent mTencent;
    private String openId;
    private String token;
    private LoginPresenter presenter;

    private EditText et_email;
    private EditText et_password;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        findViewById(R.id.tv_register).setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.iv_login_qq).setOnClickListener(this);
        findViewById(R.id.tv_forget).setOnClickListener(this);

        et_email = findViewById(R.id.et_email);
        et_password = findViewById(R.id.et_password);

        // 1.4版本:此处需新增参数，传入应用程序的全局context，可通过activity的getApplicationContext方法获取
        mTencent = Tencent.createInstance(APP_ID, this.getApplicationContext());
        presenter = new LoginPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_forget:
                // 忘记密码
                ActivityTool.startActivity(this, ForgetActivity.class);
                break;

            case R.id.tv_register:
                // 注册
                ActivityTool.startActivity(this, RegisterActivity.class);
                break;

            case R.id.btn_login:
                // 用邮箱登录
                String userId = et_email.getText().toString();
                String password = et_password.getText().toString();
                if (TextUtils.isEmpty(userId)) {
                    ToastManager.getInstance().toastShort("邮箱不能为空");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    ToastManager.getInstance().toastShort("密码不能为空");
                    return;
                }

                presenter.login(userId, password);
                setLoading(true, true);
                break;

            case R.id.iv_login_qq:
                // QQ登录
                setLoading(true, true);
                mTencent.login(this, "all", loginListener);
                break;
        }
    }

    /***********************************QQ登录开始***********************************/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * QQ登录授权监听
     */
    IUiListener loginListener = new IUiListener() {
        @Override
        public void onComplete(Object response) {
            if (null == response) {
                // 返回为空，登录失败
                ToastManager.getInstance().toastShort("腾讯服务器异常");
                setLoading(false);
                return;
            }
            JSONObject jsonObject = (JSONObject) response;
            if (jsonObject != null && jsonObject.length() == 0) {
                // 返回为空，登录失败
                ToastManager.getInstance().toastShort("腾讯服务器异常");
                setLoading(false);
                return;
            }

            //登录成功，获取到了openId等信息
            try {
                token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
                String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
                openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
                if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                    mTencent.setAccessToken(token, expires);
                    mTencent.setOpenId(openId);

                    // 根据openId等信息获取QQ账号的头像、昵称等信息
                    UserInfo mInfo = new UserInfo(LoginActivity.this, mTencent.getQQToken());
                    mInfo.getUserInfo(qqInfoListener);
                }
            } catch(Exception e) {
                setLoading(false);
                ToastManager.getInstance().toastShort("腾讯服务器异常");
            }
        }

        @Override
        public void onError(UiError uiError) {
            setLoading(false);
            ToastManager.getInstance().toastShort("腾讯服务器异常");
        }

        @Override
        public void onCancel() {
            // 取消授权
            setLoading(false);
            ToastManager.getInstance().toastShort("取消授权");
        }
    };

    // QQ账号的头像、昵称等信息监听者
    IUiListener qqInfoListener = new IUiListener() {

        @Override
        public void onError(UiError e) {
            setLoading(false);
            ToastManager.getInstance().toastShort("腾讯服务器异常");
        }

        @Override
        public void onComplete(final Object response) {
            Message msg = new Message();
            msg.obj = response;
            msg.what = 0;
            mHandler.sendMessage(msg);
        }

        @Override
        public void onCancel() {
            setLoading(false);
            ToastManager.getInstance().toastShort("取消登录");
        }
    };

    /**
     * 切换回主线程
     */
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                loginOrRegister(response);
            }
        }
    };
    /***********************************QQ登录结束***********************************/

    /**
     * 拿着QQ的授权信息去登录
     * @param response
     */
    private void loginOrRegister(JSONObject response) {
        User user = new User();
        user.setUserId(openId);
        user.setToken(token);
        if (response.has("nickname")) {
            try {
                user.setNickName(response.getString("nickname"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (response.has("figureurl_qq_2")) {
            try {
                user.setHeadIcon(response.getString("figureurl_qq_2"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /*if (response.has("gender")) {
            try {
                user.setSex(response.getString("gender"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/

        String address = "";
        if (response.has("province")) {
            try {
                address += response.getString("province");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (response.has("city")) {
            try {
                address += response.getString("city");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 去注册或者登录
        presenter.qqLogin(openId, token, user.getNickName(), user.getHeadIcon());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.setView(null);
    }

    @Override
    public void onRequestComplete() {
        setLoading(false);
    }

    @Override
    public void onEmailLoginSuccess(User user) {
        onQQLoginSuccess(user);
    }

    @Override
    public void onEmailLoginFailed(String message) {
        onQQLoginFailed(message);
    }

    @Override
    public void onQQLoginSuccess(User user) {
        UserManager.getInstance().setUser(user);
        ActivityTool.startActivity(this, MainActivity.class);
        finish();
    }

    @Override
    public void onQQLoginFailed(String message) {
        ToastManager.getInstance().toastShort(message);
    }
}
