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

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
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.time.TimeUtils;
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.DaggerHomeComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.HomeContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.HomeTurnoverBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.HomePresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.HomeFunctionAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionHeader;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionNormalItem;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/10/2020 15:02
 * <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 HomeFragment extends BaseFragment<HomePresenter> implements HomeContract.View, View.OnClickListener {

    @BindView(R2.id.main_home_bar)
    QMUITopBarLayout mTopBar;

    @BindView(R2.id.tv_main_home_today_turnover)
    TextView tvTurnover;
    @BindView(R2.id.tv_main_home_cutoff_time)
    TextView tvCutoff;
    @BindView(R2.id.tv_main_home_total_amount_project)
    TextView tvProjectTotalAmount;
    @BindView(R2.id.tv_main_home_consumers_number)
    TextView tvConsumersNum;
    @BindView(R2.id.tv_main_home_bill_number)
    TextView tvBillNum;

    @BindView(R2.id.section_layout)
    QMUIStickySectionLayout mSectionLayout;

    private RecyclerView.LayoutManager mLayoutManager;
    private HomeFunctionAdapter mAdapter;
    private String[] title = new String[]{"點餐", "管理", "員工"};

    private Map<String, String[]> function = new HashMap<>();
    private ArrayList<QMUISection<SectionHeader, SectionNormalItem>> list;

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.main_fragment_home, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.getRestaurantReport(GsaCloudApplication.getRestaurantId() + "");
//        mPresenter.getRestaurantFunList("26");
        initTopBar();
        initStickyLayout();
        tvCutoff.setText(TimeUtils.getCurrentTimeInString(new SimpleDateFormat("MM.dd HH：mm")));
    }

    private void initTopBar() {
        View refreshView = View.inflate(mContext, R.layout.main_home_title_img, null);
        refreshView.setOnClickListener(this);
        ImageView refresh = refreshView.findViewById(R.id.main_home_title_iv);
        refresh.setImageResource(R.drawable.ic_main_home_refresh);
        mTopBar.addLeftView(refreshView, R.id.main_home_refresh);

        mTopBar.setTitle("店鋪名稱");

        View msgView = View.inflate(mContext, R.layout.main_home_title_img, null);
        msgView.setOnClickListener(this);
        ImageView msg = msgView.findViewById(R.id.main_home_title_iv);
        msg.setImageResource(R.drawable.selector_msg);
        mTopBar.addRightView(msgView, R.id.main_home_msg);
//        mTopBar.addRightImageButton(R.drawable.selector_msg, R.id.main_home_msg).setOnClickListener(this);
    }

    /**
     * 初始化功能列表
     */
    private void initStickyLayout() {
        mLayoutManager = createLayoutManager();
        mSectionLayout.setLayoutManager(mLayoutManager);
        mAdapter = new HomeFunctionAdapter();
        mAdapter.setCallback(new QMUIStickySectionAdapter.Callback<SectionHeader, SectionNormalItem>() {
            @Override
            public void loadMore(QMUISection<SectionHeader, SectionNormalItem> section, boolean loadMoreBefore) {

            }

            @Override
            public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                if (holder instanceof HomeFunctionAdapter.ViewHolder) {
                    HomeFunctionAdapter.ViewHolder viewHolder = (HomeFunctionAdapter.ViewHolder) holder;
                    if (viewHolder.getTvFun().getText() != null) {
                        switch (viewHolder.getTvFun().getText().toString()) {
                            case "餐檯模式":
                                CC.obtainBuilder("Component.Table")
                                        .setActionName("showTableActivity")
                                        .build()
                                        .call();
                                break;
                            case "打印管理":
                                CC.obtainBuilder("Component.Print")
                                        .setActionName("showPrintActivity")
                                        .build()
                                        .call();
                                break;
                        }
                    }
                } else {
                    //點擊的頭部，折疊
                }
            }

            @Override
            public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                return false;
            }
        });
        function.put(title[0], new String[]{"餐檯模式", "外送模式", "外賣模式", "預點餐模式", "快速收款"});
        function.put(title[1], new String[]{"餐牌管理", "選項管理", "餐桌管理", "打印管理", "時段管理", "支付管理", "折扣管理", "員工管理"});
        function.put(title[2], new String[]{"權限管理", "操作記錄"});

        mSectionLayout.setAdapter(mAdapter, true);
        list = new ArrayList<>();

        for (int i = 0; i < function.size(); i++) {
            list.add(createSection(title[i]));
        }
        mAdapter.setData(list);
    }

    private QMUISection<SectionHeader, SectionNormalItem> createSection(String title) {
        SectionHeader header = new SectionHeader(title);
        ArrayList<SectionNormalItem> contents = new ArrayList<>();
        for (int i = 0; i < Objects.requireNonNull(function.get(title)).length; i++) {
            contents.add(new SectionNormalItem(R.drawable.ic_dining_table, Objects.requireNonNull(function.get(title))[i]));
        }
//        QMUISection<SectionHeader, SectionNormalItem> section = new QMUISection<>(header, contents, false);
        // if test load more, you can open the code
//        section.setExistAfterDataToLoad(true);
//        section.setExistBeforeDataToLoad(true);
        return new QMUISection<>(header, contents, false);
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                return mAdapter.getItemIndex(i) < 0 ? layoutManager.getSpanCount() : 1;
            }
        });
        return layoutManager;
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @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() {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.main_home_refresh) {
            //刷新
            v.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.rotate_center));
        } else if (v.getId() == R.id.main_home_msg) {
            //消息

        }
    }

    @Override
    public void loadBusinessInfo(Map<String, HomeTurnoverBean.DataBean> data) {
        HomeTurnoverBean.DataBean bean = data.get(TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE));//TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE)
        if (bean != null) {
            tvTurnover.setText(bean.getBusiness_amount());
            tvProjectTotalAmount.setText(bean.getSales());
            tvConsumersNum.setText(bean.getPeople());
            tvBillNum.setText(bean.getNumber_bill());
        }
    }
}
