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

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
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.LinearLayout;
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.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.constans.ResultConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
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.function.FunctionManager;
import com.gingersoft.gsa.cloud.common.function.jump.ActivityJumpBean;
import com.gingersoft.gsa.cloud.common.function.jump.ActivityJumpStrategy;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.encryption.Aes;
import com.gingersoft.gsa.cloud.common.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.main.BuildConfig;
import com.gingersoft.gsa.cloud.main.ComponentMain;
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.activity.menu.FoodMenuManageActivity;
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.widget.dialog.CommonTipDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.lihang.ShadowLayout;
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 BaseFragmentActivity<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)
    ShadowLayout sl_order;
    @BindView(R2.id.ll_management)
    LinearLayout ll_management;
    @BindView(R2.id.ll_staff_management)
    LinearLayout ll_staff_management;

    @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.tv_version_name)
    TextView tv_version_name;
    @BindView(R2.id.qm_refresh)
    SmartRefreshLayout refresh;
    @BindViews({R2.id.tv_function_name1, R2.id.tv_function_name2, R2.id.tv_function_name3})
    TextView[] mTvFunctionNames;

//    @XFunctionViews(value = FunctionMain.ORDER_GROUP, filterParent = false)
//    private List<Function> mOrderingMeals = new ArrayList<>();
//    @XFunctionViews(value = FunctionMain.MANAGER_GROUP, filterParent = false)
//    private List<Function> mManagement = new ArrayList<>();
//    @XFunctionViews(value = FunctionMain.EMPLOYEE_GROUP, filterParent = false)
//    private List<Function> mStaffManagement = new ArrayList<>();

//    private Map<Function, ActivityJumpStrategy> mActivityJumpStrategy = new HashMap<>();

    private MainTopFragment mainTopFragment;
    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) {
//        XFunctionManager.inJect(this, FunctionMain.class);
        super.onCreate(savedInstanceState);
        mPresenter.checkAppVersion();
        mPresenter.syncRestaurantExtendedConfiguration();
    }

    @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();
        ImmersionBar.with(this).titleBar(R.id.cl_title_layout).init();
        ImmersionBar.with(this).titleBar(R.id.side_layout).navigationBarAlpha(1).init();
        //初始化側邊欄菜單項
        initSideMenu();

        FragmentManager fragmentManager = getSupportFragmentManager();
        mainTopFragment = (MainTopFragment) fragmentManager.findFragmentById(R.id.main_top_fragment);
        tvStoreName.setText(ResturantInfoManager.newInstance().getRestaurantName());
        refresh.setOnRefreshListener(refreshLayout -> {
            if (mainTopFragment != null) {
                Message msg = new Message();
                msg.what = 0;
                mainTopFragment.setData(msg);
            }
        });
        refresh.setEnableLoadMore(false);
//        initFuncationData();
        updateTitleInfo();

        //側滑顯示或關閉時，修改背景圓角
        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);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initFuncationData();
        if (((int) SPUtils.get("isFormal", 0)) != 0) {
            tv_version_name.setText("v_" + DeviceUtils.getVersionName(this) + "\u1500Beta");
        } else {
            tv_version_name.setText("v_" + DeviceUtils.getVersionName(this));
        }
        //開啟Prj打印服務
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .setActionName("openPrintService")
                .build()
                .call();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String restaurantName = ResturantInfoManager.newInstance().getRestaurantName();
        tvStoreName.setText(restaurantName);
        tvRestaurantName.setText(restaurantName);
    }

    /**
     * 初始化側邊欄菜單項
     */
    private void initSideMenu() {
        mRvSideMenu.setLayoutManager(new LinearLayoutManager(mContext));
        List<MainSideMenuBean> mainSideMenuBeans = new ArrayList<>();

        if (BuildConfig.DEBUG) {
            mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_setting, "複製Token"));
            mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_setting, "查看日誌"));
            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, "查看日誌"));
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_settlement_report, "清機"));
        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(ComponentName.COMPONENT_LOGIN)
                            .setActionName("switchServer")
                            .build()
                            .call();
//                    finish();
                    break;
                case "複製Token":
                    String token;
                    int memberId = UserContext.newInstance().getMemberId();
                    String loginToken = UserContext.newInstance().getLoginToken();
                    token = Aes.aesEncrypt("9_" + memberId + "_" + System.currentTimeMillis() + "_" + loginToken);
                    token = token.replaceAll("\r|\n", "");

                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData label = ClipData.newPlainText("Label", token);
                    cm.setPrimaryClip(label);
                    ToastUtils.show(mContext, "已複製");
                    break;
                case "清機":
                    launchActivity(new Intent(mContext, SettlementActivity.class));
                    break;
                case "查看日誌":
                    launchActivity(new Intent(mContext, LookLogActivity.class));
                    break;
            }
        });
    }

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

    private void initFuncationData() {
        List<Function> functions = new ArrayList<>();
        List<Function> orderFunctions = FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.order, "order");
        if (orderFunctions.size() > 0) {
            functions.addAll(orderFunctions);
            sl_order.setVisibility(View.VISIBLE);
        } else {
            sl_order.setVisibility(View.INVISIBLE);
        }

        List<Function> managerFuncations = FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.manager, "manager");

        managerFuncations.add(new Function(171, 163, 5, "二維碼", R.drawable.ic_qr_code, 0));
        managerFuncations.add(new Function(171, 163, 5, "配置列表", R.drawable.ic_expand_list, 0));
        managerFuncations.add(new Function(171, 163, 5, "廚房打印查詢", R.drawable.ic_kitchen_print_query, 0));
        managerFuncations.add(new Function(171, 163, 5, "餐牌管理", R.drawable.ic_food_menu_manger, 0));
        managerFuncations.add(new Function(171, 163, 5, "採購", R.drawable.ic_purchase, 0));

        if (managerFuncations.size() > 0) {
            functions.addAll(managerFuncations);
            ll_management.setVisibility(View.VISIBLE);
        } else {
            ll_management.setVisibility(View.GONE);
        }

        List<Function> employeeFuncations = FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.employee, "employee");
        if (employeeFuncations.size() > 0) {
            functions.addAll(employeeFuncations);
            ll_staff_management.setVisibility(View.VISIBLE);
        } else {
            ll_staff_management.setVisibility(View.GONE);
        }
//        }

        //將功能列表數據分組
        SparseArray<String> parents = new SparseArray<>();
        SparseArray<List<Function>> funMap = new SparseArray<>();
        for (Function function : functions) {
            if (function.getParentId() == 0) {
                //父模塊
                parents.put(function.getId(), 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);
                }
            }
        }
        if (orderFunctions.size() > 0) {
            initAdapter(parents, funMap, 0, R.layout.main_home_funcation_item, rvOrdering, 4);
        }
        if (managerFuncations.size() > 0) {
            initAdapter(parents, funMap, 1, R.layout.main_home_management_funcation_item, rvManagement, 5);
        }
        if (employeeFuncations.size() > 0) {
            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) -> {
//                clickFunction(mActivityJumpStrategy.get(mOrderingMeals.get(position)), );
                functionClick(mOrderingMeals.get(position).getResName(), mOrderingMeals.get(position).getStatus());
            });
            rvOrdering.setAdapter(adapter);

//            for (int j = 0; j < funMap.size(); j++) {
//                List<Function> functionGroups = funMap.get(funMap.keyAt(j));
//                for (Function function : functionGroups) {
//                    mActivityJumpStrategy.put(function, new IntentJumpStrategy());
//                }
//            }

        }
    }

    private void clickFunction(ActivityJumpStrategy jumpStrategy, ActivityJumpBean jumpBean) {
        jumpStrategy.actionToJumpPage(this, jumpBean);
    }

    private void functionClick(String name, int status) {
        switch (name) {
            case "餐檯模式":
                CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                        .setActionName("showTableActivity")
                        .build()
                        .call();
                break;
            case "打印管理":

                CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                        .setActionName("showPrintActivity")
                        .build()
                        .call();
                break;
            case "賬單管理":
                CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                        .setActionName("showOrderCenterActivity")
                        .build()
                        .call();
                break;
            case "外送/自取":
                CC.obtainBuilder(ComponentName.COMPONENT_DELIVERYPICK)
                        .setActionName("orderActivity")
                        .build()
                        .call();
                break;
            case "沽清管理":
                CC.obtainBuilder(ComponentName.COMPONENT_TABLE)
                        .setActionName("showSoldoutCtrlActivity")
                        .build()
                        .call();
                break;
            case "餐檯管理":
                CC.obtainBuilder(ComponentName.COMPONENT_MANAGER)
                        .setActionName("showTableManageActivity")
                        .build()
                        .call();
                break;
            case "冷鏈接單":
            case "凍鏈接單":
                CC.obtainBuilder("Component.ColdChain")
                        .setActionName("Component.ColdChain")
                        .build()
                        .call();
                break;
            case "二維碼":
                launchActivity(new Intent(mContext, RestaurantQrCodeActivity.class));
                break;
            case "配置列表":
                launchActivity(new Intent(mContext, ExpandListActivity.class));
                break;
            case "廚房打印查詢":
                CC.obtainBuilder(ComponentName.COMPONENT_DELIVERYPICK)
                        .setActionName("PrjQueryActivity")
                        .build()
                        .call();
                break;
            case "餐牌管理":
                launchActivity(new Intent(mContext, FoodMenuManageActivity.class));
                break;
            case "採購":
                CC.obtainBuilder(ComponentName.COMPONENT_SUPPLYCHAIN)
                        .setActionName(AppConstans.SUPPLY_CHAIN_MAIN_ACTION)
                        .build()
                        .call();
                break;
            default:
                break;
        }
    }

    private void updateTitleInfo() {
        String restaurantName = ResturantInfoManager.newInstance().getRestaurantName();
        String memberName = UserContext.newInstance().getMemberName();
        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);
        }
        tvStoreName.setText(restaurantName);
        if (!TextUtils.isEmpty(memberName)) {
            tvUserName.setText(memberName);
        }
    }

    private void showChooseRestaurantDialog() {
        String brandRestaurantInfos = ResturantInfoManager.getBrandRestaurantInfos();
        if (!TextUtils.isEmpty(brandRestaurantInfos)) {
            List<BrandsBean.BrandsData> brandsBeans = JsonUtils.parseArray(brandRestaurantInfos, BrandsBean.BrandsData.class);
            if (brandsBeans != null && brandsBeans.size() > 0) {
                CC.obtainBuilder(ComponentName.COMPONENT_LOGIN)
                        .setActionName("ChooseRestaurant")
                        .build()
                        .call();
            }
        }
    }

    @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) {
//        if (message != null)
//            LoadingDialog.showDialogForLoading(mContext, message, true);
//        else
//            LoadingDialog.showDialogForLoading(mContext);
    }

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

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(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() {
        UserContext.newInstance().logOut();
        finish();
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ResultConstans.DOWNLOAD_PAGE_BACK) {
            initFuncationData();
        }
    }

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