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

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
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.RestaurantInfoUtils;
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.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
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();

        //側滑顯示或關閉時，修改背景圓角
        GradientDrawable drawable = new GradientDrawable();
        drawable.setColor(getResources().getColor(R.color.theme_bg_color));
        slideMenu.setOnOpenChangedListenter(isOpen -> {
            if (isOpen) {
                drawable.setCornerRadii(new float[]{0f, 0f, getResources().getDimension(R.dimen.main_page_radius), getResources().getDimension(R.dimen.main_page_radius), 0f, 0f, getResources().getDimension(R.dimen.main_page_radius), getResources().getDimension(R.dimen.main_page_radius)});
            } else {
                drawable.setCornerRadius(0);
            }
            refresh.setBackground(drawable);
        });
    }

    /**
     * 初始化側邊欄菜單項
     */
    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, 0));
        functions.add(new Function((long) 138, 150, 5, "餐臺模式", R.drawable.ic_dining_table_mode, 0));
        functions.add(new Function((long) 139, 150, 5, "外送模式", R.drawable.ic_delivery_mode_close, 1));
        functions.add(new Function((long) 140, 150, 5, "外賣模式", R.drawable.ic_outsourcing_model_close, 1));
        functions.add(new Function((long) 141, 150, 5, "預點餐模式", R.drawable.ic_pre_order_mode_close, 1));

        functions.add(new Function((long) 151, 0, 5, "管理", 0, 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, 0));
        functions.add(new Function((long) 142, 151, 5, "訂單管理", R.drawable.ic_meals_menu_management, 0));
        functions.add(new Function((long) 143, 151, 5, "餐臺管理", R.drawable.ic_dining_table_management_close, 1));
        functions.add(new Function((long) 144, 151, 5, "打印管理", R.drawable.ic_print_management, 0));
        functions.add(new Function((long) 145, 151, 5, "支付管理", R.drawable.ic_pay_management_close, 1));
        functions.add(new Function((long) 146, 151, 5, "折扣管理", R.drawable.ic_discount_management_close, 1));
        functions.add(new Function((long) 147, 151, 5, "沽清管理", R.drawable.ic_meals_menu_management, 0));

        functions.add(new Function((long) 152, 0, 5, "員工", 0, 0));
        functions.add(new Function((long) 147, 152, 5, "員工管理", R.drawable.ic_staff_management_close, 1));
        functions.add(new Function((long) 148, 152, 5, "權限管理", R.drawable.ic_authority_management_close, 1));
        functions.add(new Function((long) 149, 152, 5, "操作記錄", R.drawable.ic_operation_record_close, 1));
        //將功能列表數據分組
        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(), mOrderingMeals.get(position).getStatus()));
            rvOrdering.setAdapter(adapter);
        }
    }

    private void functionClick(String name, int status) {
        if (status != 0) {
            ToastUtils.show(mContext, "服務暫未開通，敬請期待");
            return;
        }
        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();
        } else if (name.equals("訂單管理")) {
            CC.obtainBuilder("Component.OtherOrder")
                    .setActionName("orderActivity")
                    .build()
                    .call();
        } else if (name.equals("沽清管理")) {
            CC.obtainBuilder("Component.Table")
                    .setActionName("showSoldoutCtrlActivity")
                    .build()
                    .call();
        }
    }

    private void setTitleInfo() {
        String restaurantName = GsaCloudApplication.getRestaurantName(this);
        String memberName = GsaCloudApplication.getMemberName(this);
        if (!TextUtils.isEmpty(restaurantName)) {
            if (RestaurantInfoUtils.getRestaurantSize(this) > 1) {
                //顯示下拉圖標
                Drawable drawable = getResources().getDrawable(R.drawable.ic_dropdown_white);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                tvRestaurantName.setCompoundDrawables(null, null, drawable, null);
            }
            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 = RestaurantInfoUtils.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")
                                    .addParam("fromPage", 2)
                                    .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);
    }


    @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) {
            //登出
            CommonTipDialog.showDoubtDialog(this, "退出登錄?", NewMainPresenter.class, mPresenter, "loginOut", null, null);
        } 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 (slideMenu.isOpen()) {
                slideMenu.closeMenu();
            } else {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    showMessage("再按一次退出應用");
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
