package com.gysdk.demo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cmic.sso.sdk.AuthRegisterViewConfig;
import com.cmic.sso.sdk.utils.rglistener.CustomInterface;
import com.g.gysdk.GYManager;
import com.g.gysdk.GYResponse;
import com.g.gysdk.GyCallBack;
import com.g.gysdk.cta.AuthPageListener;
import com.g.gysdk.cta.ELoginThemeConfig;
import com.gysdk.demo.R;
import com.gysdk.demo.util.ConfigUtils;
import com.gysdk.demo.util.ViewUtil;
import com.gysdk.demo.view.Choose;
import com.gysdk.demo.view.ChooseAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.ButterKnife;

import static android.widget.LinearLayout.HORIZONTAL;
import static com.xiasuhuei321.loadingdialog.view.SizeUtils.dip2px;

/**
 * Time：2020-07-31 on 09:50.
 * Decription:.
 * Author:jimlee.
 */
public class ChooseEloginActivity extends BaseActivity implements AuthPageListener, ChooseAdapter.ItemClickListener {

    private final String TAG = this.getClass().getSimpleName();
    private boolean isLandscape;
    private boolean isTranslucent;
    private String phoneNum;
    private ELoginThemeConfig eLoginThemeConfig = null;
    private final int REQUEST_SETTING_CODE = 10;

    private List<Choose> chooseList = new ArrayList<>();

    RecyclerView mRecyclerView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtil.setStatusBarTransparent(Color.TRANSPARENT, Color.TRANSPARENT, this);
        ViewUtil.setStatusBarLightMode(false, this);
        setContentView(R.layout.activity_choose_elogin);

        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setNavigationIcon(R.drawable.ic_back_dark);

        initChooses();
        mRecyclerView = (RecyclerView) findViewById(R.id.choose_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        ChooseAdapter adapter = new ChooseAdapter(chooseList);
        adapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = 32;
                outRect.right = 32;
                outRect.top = 40;
                outRect.bottom = 0;
            }
        });

        //在初始化回调中 或 进入设置中心 时，提前进行预登录 这样可以提高一键登录的速度
        if (!GYManager.getInstance().isPreLoginResultValid()) {
            GYManager.getInstance().ePreLogin(5000, new GyCallBack() {
                @Override
                public void onSuccess(GYResponse gyResponse) {
                    Log.d(TAG, "activity中 提前预登录成功:" + gyResponse);
                    setPhoneNum(gyResponse);
                }

                @Override
                public void onFailed(GYResponse gyResponse) {
                    Log.d(TAG, "activity中 提前预登录失败:" + gyResponse);
                }
            });
        }

        ButterKnife.bind(this);
        GYManager.getInstance().setAuthPageListener(this);
    }

    private void initChooses() {
        {
            Choose one = new Choose("全屏式", "页面简洁沉浸视觉体验", R.drawable.ic_fullscreen);
            chooseList.add(one);
        }
        {
            Choose one = new Choose("浮窗式", "方便操作不影响别的窗口", R.drawable.ic_floatscreen);
            chooseList.add(one);
        }
        {
            Choose one = new Choose("弹窗式", "页面中心位置吸引用户注意", R.drawable.ic_popupwindow);
            chooseList.add(one);
        }
        {
            Choose one = new Choose("横屏式", "打游戏看电视的首选模式", R.drawable.ic_landscape);
            chooseList.add(one);
        }
//        {
//            Choose one = new Choose("SDK默认样式", "用于检查资源精简后是否正常", R.drawable.ic_fullscreen);
//            chooseList.add(one);
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    private long lastClickTime;
    private AtomicBoolean loginIng = new AtomicBoolean(false);

    @Override
    public void onItemClick(int position) {
        eLoginThemeConfig = null;
        isLandscape = false;
        isTranslucent = false;
        switch (position) {
            case 0:
                //设置自定义view
                setCustomConfig(490);
                setThirdPartLoginBtn(530);
                eLoginThemeConfig = ConfigUtils.getFullScreenConfig(this);
                break;
            case 1:
                isTranslucent = true;
                setCustomConfig(320);
                setThirdPartLoginBtn(360);
                eLoginThemeConfig =  ConfigUtils.getFloatConfig(this);
                break;
            case 2:
                isTranslucent = true;
                setCustomConfig(315);
                setThirdPartLoginBtn(355);
                eLoginThemeConfig = ConfigUtils.getDialogConfig(this);
                break;
            case 3:
                isLandscape = true;
                //设置自定义view
                setCustomConfig(235);
                setThirdPartLoginBtn(275);
                eLoginThemeConfig = ConfigUtils.getLandscapeConfig(this);
                break;
            case 4:
                //设置自定义view
//                setCustomConfig(490);
//                setThirdPartLoginBtn(530);
                eLoginThemeConfig = new ELoginThemeConfig.Builder().build();
                break;
            default:
                eLoginThemeConfig = null;
                return;
        }

        if (eLoginThemeConfig != null) {
            if (GYManager.getInstance().isPreLoginResultValid()) {
//                if (GYManager.getInstance().getSimCount(this)>1){
//                    showSimDialog(phoneNum);
//                }else {
                    eLogin(eLoginThemeConfig);
//                }
            } else {
                long now = System.currentTimeMillis();
                if (now - lastClickTime < 1000) {
                    Log.d(TAG, "点击太快，忽略～");
                    return;
                } else if (!loginIng.compareAndSet(false, true)) {
                    Log.d(TAG, "上次还未结束，忽略～");
                    return;
                }
                lastClickTime = now;

                GYManager.getInstance().ePreLogin(5000, new GyCallBack() {
                    @Override
                    public void onSuccess(GYResponse response) {
                        loginIng.set(false);

                        Log.d(TAG, "点击中 预登录成功:" + response);
//                        if (GYManager.getInstance().getSimCount(ChooseEloginActivity.this) > 1) {
//                            setPhoneNum(response);
//                            showSimDialog(phoneNum);
//                        } else {
                            eLogin(eLoginThemeConfig);
//                        }
                    }

                    //预登录失败 请切换到其他验证方式
                    @Override
                    public void onFailed(GYResponse response) {
                        loginIng.set(false);
                        Log.d(TAG, "点击中 预登录失败:" + response);
                        showToast("预登录失败:" + response);
                        hideLoadingDialog();
                    }
                });
            }
        }

    }


//    private void showSimDialog(String phoneNum) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle(R.string.sim_dialog_title)
//                .setMessage(String.format(getResources().getString(R.string.sim_dialog_content), phoneNum))
//                .setNegativeButton(R.string.sim_dialog_setting_btn, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        startActivityForResult(new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS), REQUEST_SETTING_CODE);
//                    }
//                })
//                .setPositiveButton(R.string.sim_dialog_entry_btn, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        eLogin(eLoginThemeConfig);
//                    }
//                })
//                .setCancelable(true)
//                .setOnCancelListener(new DialogInterface.OnCancelListener() {
//                    @Override
//                    public void onCancel(DialogInterface dialogInterface) {
//                        hideLoadingDialog();
//                    }
//                })
//                .show();
//    }


    /**
     * 预登录后，保存脱敏的手机号
     *
     * @param response
     */
    private void setPhoneNum(GYResponse response) {
        try {
            JSONObject jsonObject = new JSONObject(response.getMsg());
            phoneNum = jsonObject.getString("number");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void eLogin(ELoginThemeConfig config) {
        if (config == null) {
            return;
        }
        GYManager.getInstance().eAccountLogin(config, new GyCallBack() {
            @Override
            public void onSuccess(GYResponse response) {
                hideLoadingDialog();
                Log.d(TAG, "登录成功 response:" + response);
                showToast("登录成功");
                //关闭一键登录界面
                GYManager.getInstance().finishAuthActivity();

                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) {
                hideLoadingDialog();
                Log.d(TAG, "登录失败 response:" + response);
                showToast("一键登录失败:" + response);
                //关闭一键登录界面
                GYManager.getInstance().finishAuthActivity();
            }
        });
        // 过场动画
//        overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
    }


    private void setThirdPartLoginBtn(int marginTop) {

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GYManager.getInstance().finishAuthActivity();
            }
        };

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dip2px(this, 45), dip2px(this, 45));
        layoutParams.weight = 1;
        ImageView qqImageView = new ImageView(this);
        qqImageView.setImageResource(R.drawable.qq);
        qqImageView.setLayoutParams(layoutParams);

        qqImageView.setOnClickListener(onClickListener);


        ImageView wechatImg = new ImageView(this);
        wechatImg.setImageResource(R.drawable.wechat);
        wechatImg.setLayoutParams(layoutParams);

        wechatImg.setOnClickListener(onClickListener);

        ImageView weiboImg = new ImageView(this);
        weiboImg.setImageResource(R.drawable.weibo);
        weiboImg.setLayoutParams(layoutParams);
        weiboImg.setOnClickListener(onClickListener);

        LinearLayout thirdLogin = new LinearLayout(this);
        thirdLogin.setOrientation(HORIZONTAL);
        thirdLogin.addView(qqImageView);
        thirdLogin.addView(wechatImg);
        thirdLogin.addView(weiboImg);

        RelativeLayout.LayoutParams thirdLayoutParams = new RelativeLayout.LayoutParams(dip2px(this, 250), RelativeLayout.LayoutParams.WRAP_CONTENT);
        thirdLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        thirdLayoutParams.setMargins(0, dip2px(context, marginTop), 0, 0);
        thirdLogin.setLayoutParams(thirdLayoutParams);

        GYManager.getInstance().addRegisterViewConfig("third_button", new AuthRegisterViewConfig.Builder()
                .setView(thirdLogin)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .build()
        );
    }


    /**
     * 添加自定义view.
     */
    private void setCustomConfig(int marginTop) {

        Button mBtn = new Button(context);
        mBtn.setText("其他方式登录");
        mBtn.setTextColor(Color.parseColor("#3973FF"));
        mBtn.setBackgroundColor(Color.TRANSPARENT);
        mBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        RelativeLayout.LayoutParams mLayoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        mLayoutParams1.setMargins(0, dip2px(context, marginTop), 0, 0);
        mBtn.setLayoutParams(mLayoutParams1);

        GYManager.getInstance().addRegisterViewConfig("other_button", new AuthRegisterViewConfig.Builder()
                .setView(mBtn)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setCustomInterface(new CustomInterface() {
                    @Override
                    public void onClick(Context context) {
                        showToast("其他登录方式");
                    }
                })
                .build()
        );

    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case REQUEST_SETTING_CODE:
//                GYManager.getInstance().ePreLogin(5000, new GyCallBack() {
//                    @Override
//                    public void onSuccess(GYResponse response) {
//                        setPhoneNum(response);
//                        eLogin(eLoginThemeConfig);
//                    }
//
//                    //预登录失败 请切换到其他验证方式
//                    @Override
//                    public void onFailed(GYResponse response) {
//                        showToast("预登录失败:" + response);
//                        hideLoadingDialog();
//                    }
//                });
//                break;
//            default:
//                break;
//        }
//    }



    @Override
    public void onPrivacyClick(String s, String s1) {
        Log.d(TAG, "AuthPageListener 隐私条款点击回调:" + s + ":" + s1);
    }

    @Override
    public void onPrivacyCheckBoxClick(boolean b) {
        Log.d(TAG, "AuthPageListener 隐私条款复选框点击回调:" + b);
    }

    @Override
    public void onLoginButtonClick() {
        Log.d(TAG, "AuthPageListener 一键登录按钮点击回调");
    }

    @Override
    public void onAuthActivityCreate(final Activity activity) {
        Log.d(TAG, "AuthPageListener 授权页面启动回调 isTranslucent:" + isTranslucent + " isLandscape:" + isLandscape);
//        如果您的app需要同时支持透明和非透明，manifest必需设置成透明，然后再代码onAuthActivityCreate中动态修改非透明
        if (isTranslucent) {
            // 如果弹窗模式，希望背景透明
            activity.setTheme(R.style.AppThemeTranslucent);
        } else {
            activity.setTheme(R.style.AppTheme);
        }
//        如果您的app需要同时支持横竖屏，activity.setRequestedOrientation如果不起作用请在上一个activity中进行处理横竖屏，注意manifest相关activity记得配置configChanges
        if (isLandscape) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        // 如果弹窗模式，希望点击空白处自动关闭
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                activity.setFinishOnTouchOutside(true);
            }
        }, 1);
    }

    @Override
    public void onAuthWebActivityCreate(Activity activity) {
        Log.d(TAG, "AuthPageListener 隐私条款页面启动回调");
    }

}
