package com.cooleshow.base.utils;

import android.app.Activity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.common.AppManager;
import com.cooleshow.base.data.net.ApiException;
import com.cooleshow.base.router.RouterPath;

/**
 * Author by pq, Date on 2022/5/9.
 */
public class ErrorParse {
    private static volatile ErrorParse mErrorParse;
    public static int TOKEN_INVALID_ERROR_CODE = 403;//token异常

    private ErrorParse() {
    }

    public static ErrorParse getInstance() {
        if (mErrorParse == null) {
            synchronized (ErrorParse.class) {
                if (mErrorParse == null) {
                    mErrorParse = new ErrorParse();
                }
            }
        }
        return mErrorParse;
    }

    public void parseError(Throwable throwable) {
        if (throwable instanceof ApiException) {
            ApiException apiException = (ApiException) throwable;
            if (apiException.getErrcode() == TOKEN_INVALID_ERROR_CODE) {
                ToastUtil.getInstance().showShort("登录状态异常,请重新登录");
                logOut();
                return;
            } else {
                ToastUtil.getInstance().showShort(apiException.getErrmsg());
            }
        } else {
            throwable.printStackTrace();
            ToastUtil.getInstance().showShort("网络或服务错误，请重试");
        }
    }

    private void logOut() {
        String LOGIN_ADDRESS = "com.cooleshow.usercenter.ui.activity.VerifyCodeLoginActivity";
        Activity activity = AppManager.Companion.getInstance().currentActivity();
        if (activity != null && LOGIN_ADDRESS.equals(activity.getComponentName().getClassName())) {
            return;
        }
        ARouter.getInstance().build(RouterPath.UserCenter.PATH_VERIFY_LOGIN)
                .navigation();
       /* UserHelper.saveUserToken("");
        ARouter.getInstance().build(RouterPath.UserCenter.PATH_VERIFY_LOGIN)
                .withString(UserConstants.PHONE_NUM_KEY, UserHelper.getUserPhone())
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation();*/
    }
}
