package com.gysdk.demo.elogin;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.g.gysdk.EloginActivityParam;
import com.g.gysdk.GYManager;
import com.g.gysdk.GYResponse;
import com.g.gysdk.GyCallBack;
import com.g.gysdk.GyPreloginResult;
import com.gysdk.demo.R;
import com.gysdk.demo.activity.BaseActivity;
import com.gysdk.demo.util.ViewUtil;

import org.json.JSONObject;

/**
 * 一键登录授权页面
 */
public class MyELoginActivityDialog extends BaseActivity {
    private static String TAG =  MyELoginActivityDialog.class.getSimpleName();

    // 隐私协议的打勾
    private CheckBox mCheckBox;
    // 一键登录按钮
    private View mLoginBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 沉浸式设置
        ViewUtil.setStatusBarTransparent(Color.TRANSPARENT, Color.TRANSPARENT, this);
        ViewUtil.setStatusBarLightMode(true, this);

        setContentView(R.layout.activity_login_dialog);

        // toolbar没到顶，不需要调整
        // toolbarMoveDownward();

        //设置大小
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        int widthPixels = outMetrics.widthPixels;
        int heightPixels = outMetrics.heightPixels;
        ViewUtil.setDialogTheme(this,
                widthPixels * 3 / 4, heightPixels * 3 / 4, 0, 0,
                false);

        TextView numberTv = findViewById(R.id.number_textview);
        TextView sloganTv = findViewById(R.id.slogan_textview);
        View loginBtn = findViewById(R.id.login_button);
        CheckBox checkBox = findViewById(R.id.privacy_checkbox);
        TextView privacyTv = findViewById(R.id.privacy_textview);

        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "点击了隐私协议checkBox，当前状态：" + ((CheckBox)v).isChecked());
            }
        });

        mCheckBox = checkBox;
        // gysdk需要对{@mLoginBtn}设置 setOnClickListener，请不要自行设置；app的逻辑请写在EloginActivityParam.setLoginOnClickListener中
        mLoginBtn = loginBtn;
        initPrivacyTv(privacyTv);
        initCustomerViews();

        EloginActivityParam eloginActivityParam = new EloginActivityParam()
                .setActivity(this)
                .setNumberTextview(numberTv)
                .setSloganTextview(sloganTv)
                .setLoginButton(loginBtn)
                .setPrivacyCheckbox(checkBox)
                .setPrivacyTextview(privacyTv)
                .setUiErrorListener(new EloginActivityParam.UIErrorListener() {
                    @Override
                    public void onError(String msg) {
                        //隐私协议未打勾、界面不合规、setLoginOnClickListener抛出异常等情况下的回调
                        Log.e(TAG, "UIErrorListener.onError:" + msg);
                        hideLoadingDialog();
                    }
                })
                .setLoginOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(TAG, "一键登录按钮 onLoginClick:");
                        if (!mCheckBox.isChecked()) {
                            showToast("请先仔细阅读协议并勾选，然后再点击登录");
                            // 抛出异常，避免sdk进行后续登录动作（否则eAccountLogin会回调onFailed错误）
                            throw new IllegalStateException("请先仔细阅读协议并勾选，然后再点击登录");
                        }
                        //启动登录时候的转圈圈
                        showLoadingDialog();
                    }
                });

        // 请在预登录成功之后、设置好privacyTv的内容之后再调用eAccountLogin
        GYManager.getInstance().eAccountLogin(eloginActivityParam, 5000, new GyCallBack() {
            @Override
            public void onSuccess(GYResponse response) {
                Log.d(TAG, "登录成功 response:" + response);
                showToast("登录成功");
                //停止登录时候的转圈圈
                hideLoadingDialog();
                //关闭一键登录界面
                finish();

                try {
                    JSONObject jsonObject = new JSONObject(response.getMsg());
                    JSONObject data = jsonObject.getJSONObject("data");
                    String token = data.getString("token");
                    long expiredTime = data.getLong("expiredTime");
                    Log.d(TAG, "token:" + token + "  expiredTime:" + expiredTime);
                    //将token汇报服务端进行取号
                    // ....由开发者自行实现
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(GYResponse response) {
                Log.e(TAG, "登录失败 response:" + response);
                try {
                    JSONObject jsonObject = new JSONObject(response.getMsg());
                    int errorCode = jsonObject.getInt("errorCode");
                    //...
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showToast("一键登录失败:" + response);
                //停止登录时候的转圈圈
                hideLoadingDialog();
                //关闭一键登录界面
                finish();
            }
        });
    }

    /**
     * 初始化隐私协议，请在onCreate/预登录成功之后&调用eAccountLogin之前就设置好，不允许动态改变
     * @param textView
     */
    private void initPrivacyTv(TextView textView) {
        textView.setLineSpacing(8.0F, 1.0F);
        textView.setMovementMethod(LinkMovementMethod.getInstance());

        GyPreloginResult preLoginResult = GYManager.getInstance().getPreLoginResult();

        textView.setText("");
        textView.append("登录即认可");
        textView.append(generateSpan(preLoginResult.getPrivacyName(), preLoginResult.getPrivacyUrl()));
        textView.append("、");
        textView.append(generateSpan("自定义协议1", "https://www.getui.com/about"));
        textView.append("、");
        textView.append(generateSpan("自定义协议2", "https://www.getui.com/verification"));
        textView.append("和");
        textView.append(generateSpan("自定义协议3", "https://docs.getui.com/geyan/"));
        textView.append("并使⽤用本机号码登录");
    }

    /**
     * 创建隐私协议的声明文本
     * @param name
     * @param url
     * @return
     */
    private SpannableString generateSpan(final String name, final String url) {
        SpannableString spannableString = new SpannableString(name);
        spannableString.setSpan(new ClickableSpan() {
            public void onClick(View view) {
                Log.d(TAG, "点击了隐私协议：" + name + "  " + url);
                MyELoginActivityPrivacyWeb.start(MyELoginActivityDialog.this, url, name);
            }

            public void updateDrawState(TextPaint ds) {
                try {
                    ds.setColor(0xFF3973FF);
                    ds.setUnderlineText(false);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }, 0, name.length(), 33);
        return spannableString;
    }

    /**
     * onDestroy
     */
    @Override
    public void onDestroy() {
        hideLoadingDialog();
        super.onDestroy();
    }

    /**
     * 初始化自定义组件
     */
    private void initCustomerViews() {
        // 比如自定义的其他登录方式等
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "switch button clicked.");
                finish();
            }
        };
        findViewById(R.id.weibo_login_button).setOnClickListener(onClickListener);
        findViewById(R.id.wechat_login_button).setOnClickListener(onClickListener);
        findViewById(R.id.qq_login_button).setOnClickListener(onClickListener);
    }
}
