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.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.encryption.Aes;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.constans.AppConstans;
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.BrandsBean;
import com.gingersoft.gsa.cloud.ui.widget.dialog.ChooseRestaurantDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
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.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)
//    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.tv_version_name)
    TextView tv_version_name;

    @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);
        mPresenter.checkAppVersion();
    }

    @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();
        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();
        if (((int) SPUtils.get(mContext, "isFormal", 0)) != 0) {
            tv_version_name.setText("v_" + DeviceUtils.getVersionName(this) + "\u1500Beta");
        } else {
            tv_version_name.setText("v_" + DeviceUtils.getVersionName(this));
        }
        //開啟Prj打印服務
        CC.obtainBuilder("Component.Print")
                .setActionName("openPrintService")
                .build()
                .call();
    }

    /**
     * 初始化側邊欄菜單項
     */
    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("User.Component.Login")
                            .setActionName("switchServer")
                            .build()
                            .call();
//                    finish();
                    break;
                case "複製Token":
                    String token;
                    int memberId = GsaCloudApplication.getMemberId(GsaCloudApplication.getAppContext());
                    String loginToken = GsaCloudApplication.getLoginToken(GsaCloudApplication.getAppContext());
                    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() {
        //拿到功能列表數據
//        FunctionDaoUtils functionDao = new FunctionDaoUtils(mContext);
//        List<Function> functions = functionDao.queryAllFunction();
//        if (functions == null) {
//            return;
//        }
        List<Function> functions = new ArrayList<>();

//        if (!BuildConfig.DEBUG) {
        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, 0));
        functions.add(new Function((long) 140, 150, 5, "外賣模式", R.drawable.ic_outsourcing_model_close, 0));
        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, 0));
        functions.add(new Function((long) 142, 151, 5, "外賣接單", R.drawable.ic_takeaway_orders, 0));
        functions.add(new Function((long) 143, 151, 5, "餐檯管理", R.drawable.ic_dining_table_management, 0));
        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_sell_off_manger, 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));
//        } else {
//            functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.order, "order"));
//            functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.manager, "manager"));
//            functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.employee, "employee"));
//        }

        //將功能列表數據分組
        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) {
//        switch (status){
//            case STATUS_NONACTIVATED:
//                ToastUtils.show(mContext, "服務暫未開通,請前往開通");
//                return;
//            case STATUS_TIME_LIMIT:
//                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();
        } else if (name.equals("餐檯管理")) {
            CC.obtainBuilder("Component.Manager")
                    .setActionName("showTableManageActivity")
                    .build()
                    .call();
        }
    }

    private void updateTitleInfo() {
        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);
        }
        tvStoreName.setText(restaurantName);
        if (!TextUtils.isEmpty(memberName)) {
            tvUserName.setText(memberName);
        }
    }

    private void showChooseRestaurantDialog() {
        String brandRestaurantInfos = GsaCloudApplication.getBrandRestaurantInfos(this);
        if (!TextUtils.isEmpty(brandRestaurantInfos)) {
            List<BrandsBean.BrandsData> brandsBeans = JsonUtils.parseArray(brandRestaurantInfos, BrandsBean.BrandsData.class);
            if (brandsBeans != null && brandsBeans.size() > 0) {
                new ChooseRestaurantDialog.BottomListSheetBuilder(this)
                        .addBrandItems(brandsBeans)
                        .setOnItemClickListener((dialog, item, position) -> {
                            //切換餐廳，發送關閉接單的廣播，並清除心跳
                            sendBroadcast(new Intent(AppConstans.CLEAR_ORDER_RECEIVING_HEART));

                            //关闭Prj打印服務
                            CC.obtainBuilder("Component.Print")
                                    .setActionName("stopPrintService")
                                    .build()
                                    .call();

                            BrandsBean.BrandsData 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());

                            updateTitleInfo();

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

}
