package com.gingersoft.gsa.cloud.login.mvp.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
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.UserContext;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.login.R;
import com.gingersoft.gsa.cloud.login.R2;
import com.gingersoft.gsa.cloud.login.di.component.DaggerChooseRestaurantComponent;
import com.gingersoft.gsa.cloud.login.mvp.bean.LoginLimitBean;
import com.gingersoft.gsa.cloud.login.di.module.ChooseRestaurantModule;
import com.gingersoft.gsa.cloud.login.mvp.contract.ChooseRestaurantContract;
import com.gingersoft.gsa.cloud.login.mvp.presenter.ChooseRestaurantPresenter;
import com.gingersoft.gsa.cloud.login.mvp.ui.adapter.LoginLimitAdapter;
import com.gingersoft.gsa.cloud.ui.adapter.BasTextSectiontAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionHeader;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionRestaurantItem;
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ChooseRestaurantActivity extends BaseActivity<ChooseRestaurantPresenter> implements ChooseRestaurantContract.View {

    @Inject
    AppManager mAppManager;
    @BindView(R2.id.topbar)
    QMUITopBar mTopBar;
    @BindView(R2.id.section_layout)
    QMUIStickySectionLayout mSectionLayout;
    private String form;
    private List<QMUISection<SectionHeader, SectionRestaurantItem>> mQmuiSections;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerChooseRestaurantComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .chooseRestaurantModule(new ChooseRestaurantModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_choose_restaurant; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        form = getIntent().getStringExtra("form");
        //如果是登陸頁面或者啟動頁過來，才會判斷是否執行自動選擇餐廳
        mPresenter.getRestaurantList();
    }

    @Override
    public void initIntent() {

    }

    private List<QMUISection<SectionHeader, SectionRestaurantItem>> restaurantsTransformToSection(List<BrandsBean.BrandsData> mItems) {
        List<QMUISection<SectionHeader, SectionRestaurantItem>> qmuiSections = new ArrayList<>();
        for (int i = 0; i < mItems.size(); i++) {
            BrandsBean.BrandsData brandsBean = mItems.get(i);
            qmuiSections.add(createSection(brandsBean));
        }
        return qmuiSections;
    }

    private QMUISection<SectionHeader, SectionRestaurantItem> createSection(BrandsBean.BrandsData brandsBean) {
        SectionHeader header = new SectionHeader(brandsBean.getBrandName());
        ArrayList<SectionRestaurantItem> contents = new ArrayList<>();
        for (int i = 0; i < brandsBean.getRestaurants().size(); i++) {
            contents.add(new SectionRestaurantItem(Objects.requireNonNull(brandsBean.getRestaurants().get(i))));
        }
        return new QMUISection<>(header, contents, false);
    }

    @Override
    public void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> {
            if (TextUtil.isNotEmptyOrNullOrUndefined(form) && form.equals(WelcomeActivity.class.getName())) {
                launchActivity(new Intent(mContext, LoginActivity.class));
            } else {
                killMyself();
            }
        });
        mTopBar.setTitle("選擇餐廳");
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    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);

            RestaurantInfoManager.putBrandRestaurantInfos(JsonUtils.toJson(brands));
            brandsBeans.addAll(brands);

//            restaurantSize = RestaurantInfoUtils.getRestaurantSize(brands);
        }
//        boolean autoLogin = (boolean) SPUtils.get(mContext, UserConstans.AUTO_LOGIN, false);
//        if (autoLogin) {
//            int restaurantId = ResturantInfoManager.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);
//        }
    }

    protected void saveBrandAndRestaurantInfo(int brandId, String brandName, BrandsBean.BrandsData.RestaurantsBean restaurantsBean) {
        RestaurantInfoManager.newInstance().setBrandInfo(new BrandInfo(brandId, brandName));
        if (restaurantsBean != null) {
            RestaurantInfoManager.newInstance().setResturantInfo(new RestaurantInfo(restaurantsBean.getRestaurantId(), restaurantsBean.getRestaurantName()
                    , restaurantsBean.getGsPosShopId()));
        }
    }

    private void showChooseRestaurantDialog(List<BrandsBean.BrandsData> brandsBean, List<BrandsBean.BrandsData> brands) {
        mSectionLayout.setLayoutManager(new LinearLayoutManager(mContext) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });
        BasTextSectiontAdapter mAdapter = new BasTextSectiontAdapter();
        mAdapter.setCallback(new QMUIStickySectionAdapter.Callback<SectionHeader, SectionRestaurantItem>() {

            @Override
            public void loadMore(QMUISection<SectionHeader, SectionRestaurantItem> section, boolean loadMoreBefore) {

            }

            @Override
            public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                if (holder instanceof BasTextSectiontAdapter.ViewHolder) {
                    BasTextSectiontAdapter.ViewHolder viewHolder = (BasTextSectiontAdapter.ViewHolder) holder;
                    if (viewHolder.getTvName().getText() != null) {
                        SectionRestaurantItem item = viewHolder.getSectionRestaurantItem(position);
                        ChooseRestaurantItemClick(brands, item.getRestaurantsBean());
                    }
                } else {
                    //點擊的頭部，折疊
                }
            }

            @Override
            public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                return false;
            }
        });

        mSectionLayout.setAdapter(mAdapter, true);

        mQmuiSections = restaurantsTransformToSection(brandsBean);
        mAdapter.setData(mQmuiSections);
    }

    protected void ChooseRestaurantItemClick(List<BrandsBean.BrandsData> brands, BrandsBean.BrandsData.RestaurantsBean item) {
        //切換餐廳，發送關閉接單的廣播，並清除心跳
        sendBroadcast(new Intent(AppConstans.CLEAR_ORDER_RECEIVING_HEART));
        //关闭Prj打印服務
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .setActionName("stopPrintService")
                .build()
                .call();
        BrandsBean.BrandsData brandsBean = RestaurantInfoUtils.getBrandByRestaurantId(brands, item.getRestaurantId());
        if (brandsBean != null) {
            LoganManager.w_login(TAG, LoganManager.EVENT_SELECTED, "品牌=" + brandsBean.getBrandName() + " 餐廳=" + item.getRestaurantName());
            saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), item);
            mPresenter.getLoginLimit(item.getRestaurantId(), true);
        }
//        jumpDownloadActivity();
    }

    @Override
    protected void onStop() {
        super.onStop();
        killMyself();
    }

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

    private void killBeforeActivity() {
        List<Activity> activities = mAppManager.getActivityList();
        for (int i = activities.size(); i >= 0; i--) {
            if (i < activities.size()) {
                Activity activity = activities.get(i);
                if (!activity.getClass().getName().equals(getClass().getName())) {
                    LogUtil.d(TAG, "killBeforeActivty: " + i + " - " + activity.getClass().getSimpleName());
                    mAppManager.killActivity(activity.getClass());
                    mAppManager.removeActivity(activity);
                }
            }
        }
    }

    @Override
    public void jumpActivity(Class activity) {
        startActivity(new Intent(this, activity));
    }

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

    @Override
    public void killMyself() {
        finish();
    }

    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));
//                GsaCloudApplication.logOut();

                UserContext.newInstance().logOut();

            }).setGravity(Gravity.BOTTOM).show();
        } else {
            showMessage("獲取登陸人數失敗");
            UserContext.newInstance().logOut();
        }
    }

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

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