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

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
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.toast.ToastUtils;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.main.BuildConfig;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerNewMainComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.NewMainContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.MainSideMenuBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.NewMainPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.MainOrderingAdapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.MainSideMenuAdapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.fragment.MainTopFragment;
import com.gingersoft.gsa.cloud.main.mvp.ui.view.SlidingMenu;
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 com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

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

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/18/2020 17:14
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class NewMainActivity extends BaseActivity<NewMainPresenter> implements NewMainContract.View, View.OnClickListener {
    @BindView(R2.id.rv_side_menu)
    RecyclerView mRvSideMenu;
    @BindView(R2.id.rv_ordering_meals)
    RecyclerView rvOrdering;//點餐
    @BindView(R2.id.rv_management)
    RecyclerView rvManagement;//管理
    @BindView(R2.id.rv_staff_management)
    RecyclerView rvStaffManagement;//管理

    //    @BindView(R2.id.drawer_layout)
//    DrawerLayout drawerLayout;
    @BindView(R2.id.slideMenu)
    SlidingMenu slideMenu;

    //    @BindView(R2.id.layout_ordering_meals)
//    LinearLayout orderingMeals;
//    @BindView(R2.id.layout_management)
//    LinearLayout layoutManagement;
    @BindView(R2.id.tv_restaurant_name)
    TextView tvRestaurantName;
    @BindView(R2.id.tv_username)
    TextView tvUserName;
    @BindView(R2.id.tv_store_name)
    TextView tvStoreName;

    @BindView(R2.id.qm_refresh)
    SmartRefreshLayout refresh;

    private MainTopFragment mainTopFragment;
    @BindViews({R2.id.tv_function_name1, R2.id.tv_function_name2, R2.id.tv_function_name3})
    TextView[] mTvFunctionNames;

    private RxPermissions mRxPermissions;

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        mPresenter.requestExternalStoragePermission();
        //初始化側邊欄菜單項
        initSideMenu();

        FragmentManager fragmentManager = getSupportFragmentManager();
        mainTopFragment = (MainTopFragment) fragmentManager.findFragmentById(R.id.main_top_fragment);

        tvStoreName.setText(GsaCloudApplication.getRestaurantName(mContext));
        refresh.setOnRefreshListener(refreshLayout -> {
            if (mainTopFragment != null) {
                Message msg = new Message();
                msg.what = 0;
                mainTopFragment.setData(msg);
            }
        });
        refresh.setEnableLoadMore(false);
        initFuncationData();
        setTitleInfo();
    }

    /**
     * 初始化側邊欄菜單項
     */
    private void initSideMenu() {
        mRvSideMenu.setLayoutManager(new LinearLayoutManager(mContext));
        List<MainSideMenuBean> mainSideMenuBeans = new ArrayList<>();
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_mall_center, "商城中心"));
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_about_us, "關於我們"));
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_password, "修改密碼"));
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_setting, "清機"));
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_setting, "設置"));
        if (BuildConfig.DEBUG) {
            mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_setting, "切換環境"));
        }
        MainSideMenuAdapter adapter = new MainSideMenuAdapter(mainSideMenuBeans);
        mRvSideMenu.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            switch (mainSideMenuBeans.get(position).getFunctionName()) {
                case "切換環境":
                    //切換環境
                    CC.obtainBuilder("User.Component.Login")
                            .setActionName("switchServer")
                            .build()
                            .call();
                    finish();
                    break;
                case "清機":
                    launchActivity(new Intent(mContext, SettlementActivity.class));
                    break;
            }
        });
    }

    public void onFinishRefresh() {
        refresh.finishRefresh();
    }

    private void initFuncationData() {
        //拿到功能列表數據
//        FunctionDaoUtils functionDao = new FunctionDaoUtils(mContext);
//        List<Function> functions = functionDao.queryAllFunction();
//        if (functions == null) {
//            return;
//        }
        List<Function> functions = new ArrayList<>();
        functions.add(new Function((long) 150, 0, 5, "點餐", 0));
        functions.add(new Function((long) 138, 150, 5, "餐臺模式", R.drawable.ic_dining_table_mode));
        functions.add(new Function((long) 139, 150, 5, "外送模式", R.drawable.ic_delivery_mode));
        functions.add(new Function((long) 140, 150, 5, "外賣模式", R.drawable.ic_outsourcing_model));
        functions.add(new Function((long) 141, 150, 5, "預點餐模式", R.drawable.ic_pre_order_mode));

        functions.add(new Function((long) 151, 0, 5, "管理", 0));
//        functions.add(new Function((long) 142, 151, 5, "餐牌管理", R.drawable.ic_meals_menu_management));
        functions.add(new Function((long) 142, 151, 5, "賬單管理", R.drawable.ic_meals_menu_management));
        functions.add(new Function((long) 143, 151, 5, "餐臺管理", R.drawable.ic_dining_table_management));
        functions.add(new Function((long) 144, 151, 5, "打印管理", R.drawable.ic_print_management));
        functions.add(new Function((long) 145, 151, 5, "支付管理", R.drawable.ic_pay_management));
        functions.add(new Function((long) 146, 151, 5, "折扣管理", R.drawable.ic_discount_management));

        functions.add(new Function((long) 152, 0, 5, "員工", 0));
        functions.add(new Function((long) 147, 152, 5, "員工管理", R.drawable.ic_staff_management));
        functions.add(new Function((long) 148, 152, 5, "權限管理", R.drawable.ic_authority_management));
        functions.add(new Function((long) 149, 152, 5, "操作記錄", R.drawable.ic_operation_record));
        //將功能列表數據分組
        SparseArray<String> parents = new SparseArray<>();
        SparseArray<List<Function>> funMap = new SparseArray<>();
        for (Function function : functions) {
            if (function.getParentId() == 0) {
                //父模塊
                parents.put(function.getId().intValue(), function.getResName());
            } else {
                if (funMap.get(function.getParentId()) == null) {
                    List<Function> functionList = new ArrayList<>();
                    functionList.add(function);
                    funMap.put(function.getParentId(), functionList);
                } else {
                    funMap.get(function.getParentId()).add(function);
                }
            }
        }
        initAdapter(parents, funMap, 0, R.layout.main_home_funcation_item, rvOrdering, 4);
        initAdapter(parents, funMap, 1, R.layout.main_home_management_funcation_item, rvManagement, 5);
        initAdapter(parents, funMap, 2, R.layout.main_home_management_funcation_item, rvStaffManagement, 4);
    }

    private void initAdapter(SparseArray<String> parents, SparseArray<List<Function>> funMap, int i, int p, RecyclerView rvOrdering, int i2) {
        if (funMap.size() > i && parents.size() > i) {
            mTvFunctionNames[i].setText(parents.get(parents.keyAt(i)));
            List<Function> mOrderingMeals = funMap.get(parents.keyAt(i));
            MainOrderingAdapter adapter = new MainOrderingAdapter(p, mOrderingMeals);
            rvOrdering.setLayoutManager(new GridLayoutManager(mContext, i2) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            adapter.setOnItemClickListener((adapter1, view, position) -> functionClick(mOrderingMeals.get(position).getResName()));
            rvOrdering.setAdapter(adapter);
        }
    }

    private void functionClick(String name) {
        if (name.equals("餐臺模式")) {
            CC.obtainBuilder("Component.Table")
                    .setActionName("showTableActivity")
                    .build()
                    .call();
        } else if (name.equals("打印管理")) {
            CC.obtainBuilder("Component.Print")
                    .setActionName("showPrintActivity")
                    .build()
                    .call();
        } else if (name.equals("賬單管理")) {
            CC.obtainBuilder("Component.Table")
                    .setActionName("showOrderCenterActivity")
                    .build()
                    .call();
        }
    }

    private void setTitleInfo() {
        String restaurantName = GsaCloudApplication.getRestaurantName(this);
        String memberName = GsaCloudApplication.getMemberName(this);
        if (!TextUtils.isEmpty(restaurantName)) {
            tvRestaurantName.setText(restaurantName);
        }
        if (!TextUtils.isEmpty(memberName)) {
            tvUserName.setText(memberName);
        }
    }

    private void showChooseRestaurantDialog() {
        String brandRestaurantInfos = GsaCloudApplication.getBrandRestaurantInfos(this);
        if (!TextUtils.isEmpty(brandRestaurantInfos)) {
            List<LoginBean.DataBean.UserBean.BrandsBean> brandsBeans = JsonUtils.parseArray(brandRestaurantInfos, LoginBean.DataBean.UserBean.BrandsBean.class);
            if (brandsBeans != null && brandsBeans.size() > 0) {
                new ChooseRestaurantDialog.BottomListSheetBuilder(this)
                        .addBrandItems(brandsBeans)
                        .setOnItemClickListener((dialog, item, position) -> {

                            LoginBean.DataBean.UserBean.BrandsBean brandsBean = getBrandByRestaurantId(brandsBeans, item.getId());

                            if (brandsBean != null) {
                                saveBrandAndRestaurantInfo(brandsBean.getBrandId(), brandsBean.getBrandName(), item.getId(), item.getText());
                            }

                            GsaCloudApplication.setRestaurantId(NewMainActivity.this, item.getId());
                            GsaCloudApplication.setRestaurantName(NewMainActivity.this, item.getText());

                            setTitleInfo();
                            CC.obtainBuilder("Component.Download")
                                    .setActionName("showDownloadActivity")
                                    .build()
                                    .call();
                            dialog.dismiss();
                        })
                        .build()
                        .show();
            }
        }
    }

    private void saveBrandAndRestaurantInfo(int brandId, String brandName, int restaurantId, String restaurantName) {
        GsaCloudApplication.setBrandId(this, brandId);
        GsaCloudApplication.setBrandName(this, brandName);
        GsaCloudApplication.setRestaurantId(this, restaurantId);
        GsaCloudApplication.setRestaurantName(this, restaurantName);
    }

    private LoginBean.DataBean.UserBean.BrandsBean getBrandByRestaurantId(List<LoginBean.DataBean.UserBean.BrandsBean> brands, int restaurantId) {
        for (int i = 0; i < brands.size(); i++) {
            if (brands.get(i).getRestaurants() != null) {
                for (int j = 0; j < brands.get(i).getRestaurants().size(); j++) {
                    if (brands.get(i).getRestaurants().get(j).getRestaurantId() == restaurantId) {
                        return brands.get(i);
                    }
                }
            }
        }
        return null;
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
//        ArmsUtils.snackbarText(message);
        ToastUtils.show(mContext, message);
    }

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

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

    @OnClick({R2.id.layout_login_out, R2.id.iv_personal_center, R2.id.tv_restaurant_name})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.layout_login_out) {
            //登出
            mPresenter.loginOut();
        } else if (v.getId() == R.id.iv_personal_center) {
            slideMenu.toggle();
        } else if (v.getId() == R.id.tv_restaurant_name) {
            showChooseRestaurantDialog();
        }
    }

    @Override
    public void loginOut() {
        GsaCloudApplication.isLogin = false;
        CC.obtainBuilder("User.Component.Login")
                .setActionName("showActivityA")
                .build()
                .call();
        finish();
    }

    @Override
    public RxPermissions getRxPermissions() {
        return mRxPermissions;
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                showMessage("再按一次退出應用");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
