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

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

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.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.SectionItem;
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.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 java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
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_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;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        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) {
        initShadow();
        initFuncationData();
        setTitleInfo();
    }

    private void initShadow() {
    }

    private void initFuncationData() {
        List<SectionItem> data = new ArrayList<>();
        data.add(new SectionItem(R.drawable.ic_dining_table_mode, "餐檯模式"));
        data.add(new SectionItem(R.drawable.ic_delivery_mode, "外送模式"));
        data.add(new SectionItem(R.drawable.ic_outsourcing_model, "外賣模式"));
        data.add(new SectionItem(R.drawable.ic_pre_order_mode, "預點餐模式"));
        MainOrderingAdapter adapter = new MainOrderingAdapter(R.layout.main_home_funcation_item, data);
        rvOrdering.setLayoutManager(new GridLayoutManager(mContext, 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (data.get(position).getText().equals("餐檯模式")) {
                CC.obtainBuilder("Component.Table")
                        .setActionName("showTableActivity")
                        .build()
                        .call();
            }
        });
        rvOrdering.setAdapter(adapter);

        List<SectionItem> managementData = new ArrayList<>();
        managementData.add(new SectionItem(R.drawable.ic_meals_menu_management, "餐牌管理"));
        managementData.add(new SectionItem(R.drawable.ic_dining_table_management, "餐檯管理"));
        managementData.add(new SectionItem(R.drawable.ic_print_management, "打印管理"));
        managementData.add(new SectionItem(R.drawable.ic_pay_management, "支付管理"));
        managementData.add(new SectionItem(R.drawable.ic_discount_management, "折扣管理"));

        MainOrderingAdapter managementAdapter = new MainOrderingAdapter(R.layout.main_home_management_funcation_item, managementData);
        rvManagement.setLayoutManager(new GridLayoutManager(mContext, 5) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rvManagement.setAdapter(managementAdapter);

        managementAdapter.setOnItemClickListener((adapter12, view, position) -> {
            if (managementData.get(position).getText().equals("打印管理")) {
                CC.obtainBuilder("Component.Print")
                        .setActionName("showPrintActivity")
                        .build()
                        .call();
            }
        });

        List<SectionItem> staffData = new ArrayList<>();
        staffData.add(new SectionItem(R.drawable.ic_staff_management, "員工管理"));
        staffData.add(new SectionItem(R.drawable.ic_authority_management, "權限管理"));
        staffData.add(new SectionItem(R.drawable.ic_operation_record, "操作記錄"));

        MainOrderingAdapter staffAdapter = new MainOrderingAdapter(R.layout.main_home_management_funcation_item, staffData);
        rvStaffManagement.setLayoutManager(new GridLayoutManager(mContext, 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rvStaffManagement.setAdapter(staffAdapter);
    }

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

    public View.OnClickListener mSlidingMenuOnclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            slideMenu.toggle();
        }
    };

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

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