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.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.RestaurantInfoUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.widget.DialogUtils;
import com.gingersoft.gsa.cloud.constans.UserConstans;
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.mvp.ui.activity.ChooseRestaurantActivity;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.mvp.ui.activity.LoginActivity;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.mvp.ui.activity.SwitchServerActivity;
import com.gingersoft.gsa.cloud.login.mvp.ui.adapter.LoginLimitAdapter;
import com.gingersoft.gsa.cloud.ui.bean.mode.BrandsBean;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
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);
    }

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

        if (autoLogin && GsaCloudApplication.isLogin) {
            int restaurantId = GsaCloudApplication.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) {
//        GsaCloudApplication.setBrandRestaurantInfos(mContext, "");
        if (loginBean.getData() != null) {
            GsaCloudApplication.setLoginToken(mContext, loginBean.getData().getToken());
            if (loginBean.getData().getUser() != null) {
                GsaCloudApplication.setMemberId(mContext, loginBean.getData().getUser().getId());
                GsaCloudApplication.setMemberName(mContext, loginBean.getData().getUser().getUserName());
                //獲取餐廳
//                mPresenter.getRestaurantList();
                boolean autoLogin = (boolean) SPUtils.get(mContext, UserConstans.AUTO_LOGIN, false);
                if (autoLogin) {
                    int restaurantId = GsaCloudApplication.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) {
        GsaCloudApplication.setBrandId(mContext, brandId);
        GsaCloudApplication.setBrandName(mContext, brandName);
        if (restaurantsBean != null) {
            GsaCloudApplication.setRestaurantId(mContext, restaurantsBean.getRestaurantId());
            GsaCloudApplication.setRestaurantName(mContext, restaurantsBean.getRestaurantName());
            GsaCloudApplication.setGsPosShopId(mContext, restaurantsBean.getGsPosShopId());
        }
    }

    public void jumpDownloadActivity() {
        CC.obtainBuilder("Component.Download")
                .setActionName("showDownloadActivity")
                .addParam("fromPage", 1)
                .build()
                .call();
        killMyself();
    }

    public void jumpMainActivity() {
        CC.obtainBuilder("Component.Main")
                .setActionName("showMainActivity")
                .build()
                .call();
        killMyself();
    }

    private DialogUtils dialogUtils;
    private int loginNum = 0;

    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();
        }
    }

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

}
