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.core.content.ContextCompat;
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.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.constans.ResultConstans;
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.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.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.service.IServiceManager;
import com.gingersoft.gsa.cloud.common.utils.AppDevices;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.StytemUtils;
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 configImmersionBar(ImmersionBar immersionBar) {
        immersionBar.titleBar(R.id.cl_title_layout).init();
        immersionBar.titleBar(R.id.side_layout).navigationBarAlpha(1).init();
    }

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

        FragmentManager fragmentManager = getSupportFragmentManager();
        mainTopFragment = (MainTopFragment) fragmentManager.findFragmentById(R.id.main_top_fragment);
        tvStoreName.setText(RestaurantInfoManager.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(ContextCompat.getColor(mContext, 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();
        initService();
        initFuncationData();
        if (((int) SPUtils.get("isFormal", 0)) != 0) {
            tv_version_name.setText("v_" + DeviceUtils.getVersionName(this) + "\u3000Beta");
        } else {
            tv_version_name.setText("v_" + DeviceUtils.getVersionName(this));
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        updateTitleInfo();
    }

    private void initService() {
        IServiceManager.startICommandService(GsaCloudApplication.getAppContext());
        IServiceManager.startPrjService(GsaCloudApplication.getAppContext());
    }

    /**
     * 初始化側邊欄菜單項
     */
    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_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_setting, "切換環境"));
        }
//        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_setting, "上傳日誌"));
        mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_settlement_report, "清機"));
        if (AppDevices.isHywebPos()) {
            mainSideMenuBeans.add(new MainSideMenuBean(R.drawable.ic_settlement_report, "N5清機"));
        }
        MainSideMenuAdapter adapter = new MainSideMenuAdapter(mainSideMenuBeans);
        mRvSideMenu.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> {

            String functionName = mainSideMenuBeans.get(position).getFunctionName();

            LoganManager.w_home(TAG, LoganManager.EVENT_CLICK + functionName);

            switch (functionName) {
                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 "清機": {
                    Intent intent = new Intent(this, SettlementActivity.class);
                    intent.putExtra(SettlementActivity.SETTLEMENT_TYPE_TAG, SettlementActivity.SETTLEMENT_TYPE_NOMAL);
                    startActivity(intent);
                }
                break;
                case "N5清機": {
                    Intent intent = new Intent(this, SettlementActivity.class);
                    intent.putExtra(SettlementActivity.SETTLEMENT_TYPE_TAG, SettlementActivity.SETTLEMENT_TYPE_HYWEB_POS);
                    startActivity(intent);
                }
                break;
                case "查看日誌":
                    launchActivity(new Intent(mContext, LookLogActivity.class));
                    break;
                case "上傳日誌":
                    LoganManager.uploadLog(mContext, true);
                    break;
                case "廚房單原圖":

                    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_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<>(3);
        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) {

        LoganManager.w_home(TAG, LoganManager.EVENT_CLICK + name);

        switch (name.trim()) {
            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 "廚房打印查詢":
            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 = RestaurantInfoManager.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 = RestaurantInfoManager.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 {
                    ArmsUtils.exitApp();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
