package com.wanyue.main.view.activity;

import android.app.Dialog;
import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wanyue.common.CommonAppConfig;
import com.wanyue.common.CommonAppContext;
import com.wanyue.common.HtmlConfig;
import com.wanyue.common.activity.BaseActivity;
import com.wanyue.common.activity.WebViewActivity;
import com.wanyue.common.bean.ConfigBean;
import com.wanyue.common.bean.UserBean;
import com.wanyue.common.custom.MyViewPager;
import com.wanyue.common.interfaces.OnItemClickListener;
import com.wanyue.common.mob.LoginData;
import com.wanyue.common.mob.MobBean;
import com.wanyue.common.mob.MobCallback;
import com.wanyue.common.mob.MobLoginUtil;
import com.wanyue.common.proxy.ViewProxyPageAdapter;
import com.wanyue.common.server.entity.Data;
import com.wanyue.common.server.observer.DialogObserver;
import com.wanyue.common.utils.DialogUitl;
import com.wanyue.common.utils.DpUtil;
import com.wanyue.common.utils.ListUtil;
import com.wanyue.common.utils.RouteUtil;
import com.wanyue.common.utils.StringUtil;
import com.wanyue.common.utils.ToastUtil;
import com.wanyue.main.R;
import com.wanyue.main.R2;
import com.wanyue.main.adapter.LoginTypeAdapter;
import com.wanyue.main.adapter.MainNavigatorAdapter;
import com.wanyue.main.api.MainAPI;
import com.wanyue.main.view.proxy.login.BaseLoginProxy;
import com.wanyue.main.view.proxy.login.PasswordLoginProxy;
import com.wanyue.main.view.proxy.login.VerifiCodeLoginProxy;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouteUtil.PATH_LOGIN)
public class LoginActivity extends BaseActivity implements OnItemClickListener<MobBean> {
    @BindView(R2.id.indicator)
    MagicIndicator mIndicator;
    @BindView(R2.id.btn_register)
    TextView mBtnRegister;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.btn_tip)
    TextView mBtnTip;
    @BindView(R2.id.tip_group)
    LinearLayout mTipGroup;
    @BindView(R2.id.viewPager)
    MyViewPager mViewPager;
    @BindView(R2.id.rootView)
    ViewGroup mRootView;

    private VerifiCodeLoginProxy mVerifiCodeLoginProxy;
    private PasswordLoginProxy mPasswordLoginProxy;

    private DialogObserver<Data<JSONObject>> mLoginSuccObserver;

    private MobLoginUtil mLoginUtil;

    public static void forward() {
        Intent intent = new Intent(CommonAppContext.sInstance, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        CommonAppContext.sInstance.startActivity(intent);
    }

    @Override
    public void init() {
        int statusHeight = CommonAppConfig.statuBarHeight();
        int defaultPaddingg = DpUtil.dp2px(20);
        mBtnTip.setText(getString(R.string.login_tip_2));
        mRootView.setPadding(defaultPaddingg, statusHeight, defaultPaddingg, 0);
        mViewPager.setCanScroll(false);
        initLoginPager();
        initThirdData();
    }



    /*初始化第三方登录的数据*/
    private void initThirdData() {
        ConfigBean configBean = CommonAppConfig.getConfig();
        if (configBean != null) {
            List<MobBean> list = MobBean.getLoginTypeList(configBean.getLoginType());
            if (ListUtil.haveData(list)) {
                mRecyclerView = findViewById(R.id.recyclerView);
                mRecyclerView.setHasFixedSize(true);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
                LoginTypeAdapter adapter = new LoginTypeAdapter(mContext, list);
                adapter.setOnItemClickListener(this);
                mRecyclerView.setAdapter(adapter);
                mLoginUtil = new MobLoginUtil();
            }
        }
    }


    private void initLoginPager() {
        String[] titles = {getString(R.string.code_login), getString(R.string.pwd_login)};
        CommonNavigator commonNavigator = new CommonNavigator(this);
        MainNavigatorAdapter adapter = new MainNavigatorAdapter(titles, this, mViewPager);
        commonNavigator.setAdapter(adapter);
        mIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mIndicator, mViewPager);
        mVerifiCodeLoginProxy = new VerifiCodeLoginProxy();
        mPasswordLoginProxy = new PasswordLoginProxy();
        mLoginSuccObserver = new DialogObserver<Data<JSONObject>>(this) {
            @Override
            public void onNextTo(Data<JSONObject> jsonObjectData) {
                loginingSucc(jsonObjectData);
            }
        };

        mVerifiCodeLoginProxy.setDataDefaultObserver(mLoginSuccObserver);
        mPasswordLoginProxy.setDataDefaultObserver(mLoginSuccObserver);

        List<? extends BaseLoginProxy> baseLoginProxiyArray = ListUtil.asList(mVerifiCodeLoginProxy,
                mPasswordLoginProxy);

        ViewProxyPageAdapter pageAdapter = new ViewProxyPageAdapter(getViewProxyMannger(), baseLoginProxiyArray);
        mViewPager.setAdapter(pageAdapter);
    }

    private void loginingSucc(Data<JSONObject> jsonObjectData) {
        ToastUtil.show(jsonObjectData.getMsg());
        JSONObject jsonObject = jsonObjectData.getInfo_0();
        UserBean userBean = JSON.toJavaObject(jsonObject, UserBean.class);
        String uid = userBean.getId();
        String token = jsonObject.getString("token");
        CommonAppConfig.setUserBean(userBean);
        CommonAppConfig.setLoginInfo(uid, token, true);

        String gradeId=jsonObject.getString("gradeid");
        String gradeName=jsonObject.getString("gradename");
        if(StringUtil.equals(gradeId,"0")){
          // startActivity(StudyStageActivity.class);
            CommonAppConfig.setGradeName(gradeName);
            CommonAppConfig.setGradeId(gradeId,false);
        }else{
           CommonAppConfig.setGradeName(gradeName);
           CommonAppConfig.setGradeId(gradeId);
        }
        finish();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    /*跳转到注册界面*/
    @OnClick(R2.id.btn_register)
    public void toRegister() {
        startActivity(RegisterActivity.class);
    }

    /*点击用户协议*/
    @OnClick(R2.id.btn_tip)
    public void clickTip() {
        WebViewActivity.forward(this, HtmlConfig.LOGIN_PRIVCAY,false);
    }

    @Override
    public void onItemClick(MobBean bean, int position) {
        if (mLoginUtil == null) {
            return;
        }
        final Dialog dialog = DialogUitl.loginAuthDialog(mContext);
        dialog.show();
        mLoginUtil.execute(bean.getType(), new MobCallback() {
            @Override
            public void onSuccess(Object data) {
               if (data != null) {
                   loginByThird((LoginData) data);
               }
            }
            @Override
            public void onError() {
                disMissLoadingDialog(dialog);

            }
            @Override
            public void onCancel() {
                disMissLoadingDialog(dialog);
            }
            @Override
            public void onFinish() {
               disMissLoadingDialog(dialog);
            }
        });
    }
    private void disMissLoadingDialog(Dialog dialog) {
        if (dialog != null&&dialog.isShowing()) {
            dialog.dismiss();
            dialog=null;
        }
    }


    /*第三方登录*/
    private void loginByThird(LoginData data) {
        if(mLoginSuccObserver!=null){
           mLoginSuccObserver.setContext(this);
        }
        MainAPI.loginByThird(data.getOpenID(), data.getNickName(), data.getAvatar(), data.getFlag()).
                compose(this.<Data<JSONObject>>bindUntilOnDestoryEvent())
                .subscribe(mLoginSuccObserver);
    }

}