package com.gingersoft.gsa.cloud.login.mvp.contract;

import android.app.Dialog;
import android.content.Intent;
import android.view.Gravity;
import android.widget.LinearLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.core.login.LoginBean;
import com.gingersoft.gsa.cloud.common.core.restaurant.BrandInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.restaurant.bean.BrandsBean;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantInfoUtils;
import com.gingersoft.gsa.cloud.common.core.user.UserConstans;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.core.user.info.UserInfo;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.login.R;
import com.gingersoft.gsa.cloud.login.mvp.bean.LoginLimitBean;
import com.gingersoft.gsa.cloud.login.mvp.presenter.BaseLoginPresenter;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.ChooseRestaurantActivity;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.LoginActivity;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.SwitchServerActivity;
import com.gingersoft.gsa.cloud.login.mvp.ui.adapter.LoginLimitAdapter;
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils;
import com.gingersoft.gsa.cloud.ui.widget.dialog.ChooseRestaurantDialog;
import com.jess.arms.base.BaseActivity;
import java.util.ArrayList;
import java.util.List;

public abstract class LoginInterfaceImpl<P extends BaseLoginPresenter> extends BaseActivity<P> implements BaseLoginContract.View {

    @Override
    public void loginSuccess(LoginBean info) {
        saveLoginInfo(info);
    }

    @Override
    public void saveRestaurantListInfo(List<BrandsBean.BrandsData> brands) {
        int restaurantSize = 0;
        List<BrandsBean.BrandsData> brandsBeans = new ArrayList<>();
        if (brands != null) {
            RestaurantInfoManager.putBrandRestaurantInfos(JsonUtils.toJson(brands));
            restaurantSize = RestaurantInfoUtils.getRestaurantSize(brands);
            brandsBeans.addAll(brands);
        }
        boolean autoLogin = (boolean) SPUtils.get(UserConstans.AUTO_LOGIN, false);

        if (autoLogin && UserContext.newInstance().isLogin()) {
            int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
            if (restaurantId != 0) {
                //上一次進入app有選擇餐廳，通過餐廳ID獲取允許的最大登陸數
                mPresenter.getLoginLimit(restaurantId, false);
//                jumpMainActivity();
                return;
            }
        }

        if (restaurantSize == 1) {
            //只有一個品牌是直接進下載頁面
            BrandsBean.BrandsData brandsBean = RestaurantInfoUtils.getOnlyBrand(brands);
            BrandsBean.BrandsData.RestaurantsBean restaurantsBean = RestaurantInfoUtils.getOnlyRestaurant(brands);
            if (brandsBean != null) {
                saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), restaurantsBean);
                //通過餐廳ID獲取允許的最大登陸數
                mPresenter.getLoginLimit(restaurantsBean.getRestaurantId(), true);
            }
//            jumpDownloadActivity();
        } else {

//            showChooseRestaurantDialog(brandsBeans, brands);
        }
    }

    @Override
    public void startToSwitchServer() {
        startActivity(new Intent(mContext, SwitchServerActivity.class));
    }

    private void saveLoginInfo(LoginBean loginBean) {
        if (loginBean != null) {
//            GsaCloudApplication.setLoginToken(mContext, loginBean.getData().getToken());
            if (loginBean.getUser() != null) {
//                GsaCloudApplication.setMemberId(mContext, loginBean.getData().getUser().getId());
//                GsaCloudApplication.setMemberName(mContext, loginBean.getData().getUser().getUserName());

                LoginBean.UserBean info = loginBean.getUser();

                UserInfo userInfo = new UserInfo();
                userInfo.setToken(loginBean.getToken());
                userInfo.setUserId(info.getId());
                userInfo.setUserName(info.getUserName());
                userInfo.setMobile(info.getMobile());
                userInfo.setStatus(info.getStatus());
                userInfo.setEmail(info.getEmail());
                userInfo.setMerchantsId(info.getMerchantsId());
                userInfo.setParentId(info.getParentId());

                UserContext.newInstance().setUserInfo(userInfo);
                //獲取餐廳
//                mPresenter.getRestaurantList();
                boolean autoLogin = (boolean) SPUtils.get(UserConstans.AUTO_LOGIN, false);
                if (autoLogin) {
                    int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
                    if (restaurantId != 0) {
                        //上一次進入app有選擇餐廳，通過餐廳ID獲取允許的最大登陸數
//                mPresenter.getLoginLimit(restaurantId, false);
//                        jumpMainActivity();
                        jumpDownloadActivity();
                        return;
                    }
                }
                Intent intent = new Intent(mContext, ChooseRestaurantActivity.class);
                Class clazz = getClass();
                intent.putExtra("form", clazz.getName());
                launchActivity(intent);
            }
        }
    }

    protected void ChooseRestaurantItemClick(List<BrandsBean.BrandsData> brands, ChooseRestaurantDialog dialog, BrandsBean.BrandsData.RestaurantsBean item) {
        BrandsBean.BrandsData brandsBean = RestaurantInfoUtils.getBrandByRestaurantId(brands, item.getRestaurantId());
        if (brandsBean != null) {
            saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), item);
            mPresenter.getLoginLimit(item.getRestaurantId(), true);
        }
        dialog.dismiss();
//        jumpDownloadActivity();
    }

    protected void saveBrandAndRestaurantInfo(int brandId, String brandName, BrandsBean.BrandsData.RestaurantsBean restaurantsBean) {

        RestaurantInfoManager.newInstance().setBrandInfo(new BrandInfo(brandId, brandName));

//        GsaCloudApplication.setBrandId(mContext, brandId);
//        GsaCloudApplication.setBrandName(mContext, brandName);
        if (restaurantsBean != null) {
            RestaurantInfoManager.newInstance().setResturantInfo(new RestaurantInfo(restaurantsBean.getRestaurantId(),restaurantsBean.getRestaurantName()
                    ,restaurantsBean.getGsPosShopId()));
//            GsaCloudApplication.setRestaurantId(mContext, restaurantsBean.getRestaurantId());
//            GsaCloudApplication.setRestaurantName(mContext, restaurantsBean.getRestaurantName());
//            GsaCloudApplication.setGsPosShopId(mContext, restaurantsBean.getGsPosShopId());
        }
    }

    @Override
    public void jumpDownloadActivity() {
        CC.obtainBuilder(ComponentName.COMPONENT_DOWNLOAD)
                .setActionName("showDownloadActivity")
                .addParam("fromPage", 1)
                .build()
                .call();
        killMyself();
    }

    @Override
    public void jumpMainActivity() {
        CC.obtainBuilder(ComponentName.COMPONENT_MAIN)
                .setActionName("showMainActivity")
                .build()
                .call();
        killMyself();
    }

    private DialogUtils dialogUtils;
    private int loginNum = 0;

    @Override
    public void showLoginLimit(List<LoginLimitBean> loginLimitBeans) {
        if (loginLimitBeans != null) {
            dialogUtils = new DialogUtils(mContext, R.layout.login_limit_dialog_layout) {
                @Override
                public void initLayout(ViewHepler hepler, Dialog dialog) {
                    hepler.setOnClickListenter(R.id.iv_login_limit_back, v -> {
                        dialog.dismiss();
                    });
                    RecyclerView loginLimit = hepler.getView(R.id.rv_login_limit);
                    loginLimit.setLayoutManager(new LinearLayoutManager(mContext));
                    LoginLimitAdapter loginLimitAdapter = new LoginLimitAdapter(loginLimitBeans);
                    loginLimitAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                        if (position < loginLimitBeans.size()) {
                            mPresenter.loginOut(loginLimitBeans.get(position).getUserId());
                            loginLimitBeans.remove(position);
                            loginNum = loginLimitBeans.size();
                            loginLimitAdapter.notifyDataSetChanged();
                        }
                    });
                    loginLimit.setAdapter(loginLimitAdapter);
                }
            }.setWidth(LinearLayout.LayoutParams.MATCH_PARENT).setOnDismissListener(dialog -> {
                //不管有沒有踢出人，彈窗消失回到登陸頁面
                startActivity(new Intent(mContext, LoginActivity.class));
            }).setGravity(Gravity.BOTTOM).show();
        } else {
            showMessage("獲取登陸人數失敗");
            launchActivity(new Intent(mContext, LoginActivity.class));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (dialogUtils != null) {
            dialogUtils.dismiss();
        }
    }

    @Override
    public void kickOut() {
        if (loginNum == 0) {
            if (dialogUtils != null) {
                dialogUtils.dismiss();
            }
        }
    }

}
