package com.bonait.bnframework.modules.home.fragment.from;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.model.mode.CloudGood;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ScreenUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.mode.QDListSectionAdapter;
import com.bonait.bnframework.modules.home.fragment.mode.SectionHeader;
import com.bonait.bnframework.modules.home.fragment.mode.SectionItem;
import com.bonait.bnframework.modules.home.fragment.mode.fragment_plc;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CpActivity extends BaseActivity {

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.qmuisection_layout)
    QMUIStickySectionLayout mSectionLayout;
    private RecyclerView.LayoutManager mLayoutManager;
    protected static QMUIStickySectionAdapter<SectionHeader, SectionItem, QMUIStickySectionAdapter.ViewHolder> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cp);
        //属性绑定
        ButterKnife.bind(this);
        context=this;
        initTopBar();
        initAdapter();
        initAdapterLogicalOperation();
        NBClick();
    }

    // QDListSectionAdapter
    private void initAdapter() {
        mLayoutManager = createLayoutManager();
        mSectionLayout.setLayoutManager(mLayoutManager);
        mAdapter = createAdapter();
        //mSectionLayout.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.aword_fade_enter));
    }

    private void initAdapterLogicalOperation() {
        mAdapter.setCallback(new QMUIStickySectionAdapter.Callback<SectionHeader, SectionItem>() {
            @Override
            public void loadMore(final QMUISection<SectionHeader, SectionItem> section, final boolean loadMoreBefore) {

            }

            //点击事件
            @Override
            public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                if (holder.getItemViewType() != 1) {
                    int pos = holder.isForStickyHeader ? position : holder.getAdapterPosition();
                    mAdapter.toggleFold(pos, false);
                }
            }

            //长按事件
            @Override
            public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                int FirstPos = mAdapter.getSectionIndex(position);
                int SecondPos = mAdapter.getItemIndex(position);
                //ItemPopupWindow.show(getContext(), holder.itemView, holder.getItemViewType(), FirstPos, SecondPos);
                ToastUtils.info("一级条目" + FirstPos + "二级" + SecondPos);
                return true;
            }
        });
        mSectionLayout.setAdapter(mAdapter, true);
        ConfigData.getInstance().GetGevGood(this, mHandler);
        mAdapter.setData(getList());
    }
    Context context;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj.toString() == "MSG_REFRESH") {
                mAdapter.setData(getList());
            }
        }
    };

    public void NBClick() {
        /**
         * 删除菜品
         */
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.DeleteGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    SectionItem item = (SectionItem) msg;
                    QueryDB.DeleteGoodsid(item.getAccount());
                    QueryDB.DeleteGoodsSrecipeList(item.getAccount());
                    mAdapter.setDataWithoutDiff(getList(), true);
                }
            }
        });

        /**
         * 刷新菜品
         */
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.ScGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    mAdapter.setData(new ArrayList<QMUISection<SectionHeader, SectionItem>>());
                    mAdapter.setData(getList());
                }
            }
        });

        /**
         * 点击菜品
         */
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.ClickGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    SectionItem item = (SectionItem) msg;
                    String goodid = item.getAccount();//商品id
                    Intent intent = new Intent(getContext(), DiyUpdateActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("id", goodid);
                    startActivity(intent);
                }
            }
        });
    }

    protected QMUIStickySectionAdapter<SectionHeader, SectionItem, QMUIStickySectionAdapter.ViewHolder> createAdapter() {
        return new QDListSectionAdapter();
    }

    protected RecyclerView.LayoutManager createLayoutManager() {
//        return new LinearLayoutManager(getContext()) {
//            @Override
//            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
//                return new RecyclerView.LayoutParams(
//                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            }
//        };

        final GridLayoutManager layoutManager;
        if(ConfigName.getInstance().IsPortraitScreen)//竖屏
        {
             layoutManager = new GridLayoutManager(getContext(), 3);
        }else
        {
            layoutManager = new GridLayoutManager(getContext(), 5);
        }
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                return mAdapter.getItemIndex(i) < 0 ? layoutManager.getSpanCount() : 1;
            }
        });

        return layoutManager;
    }

    /**
     * 获取数据
     *
     * @return
     */
    private static ArrayList<QMUISection<SectionHeader, SectionItem>> getList() {
        ArrayList<QMUISection<SectionHeader, SectionItem>> list = new ArrayList<>();
        ArrayList<BPA_GOODS> good = QueryDB.GetGoodsALL();
        List<String> Bendi_id = new ArrayList<>();

        SectionHeader header_bdcp = new SectionHeader("本地菜谱", "", "");
        ArrayList<SectionItem> contents_bdcp = new ArrayList<>();

        SectionHeader header_sccp = new SectionHeader("收藏菜谱", "", "");
        ArrayList<SectionItem> contents_sccp = new ArrayList<>();

        SectionHeader header_ydcp = new SectionHeader("云端菜谱", "", "");
        ArrayList<SectionItem> contents_ydcp = new ArrayList<>();

        for (BPA_GOODS item : good) {
            if (item.url == null) {
                item.url = "未知";
            }
            contents_bdcp.add(new SectionItem(item.name, String.valueOf(item.maketime), item.id, item.url, item.issc == 1, false, true));
            if (item.issc == 1) {
                contents_sccp.add(new SectionItem(item.name, String.valueOf(item.maketime), item.id, item.url, item.issc == 1, false, true));
            }
            Bendi_id.add(item.id);
        }

        for (CloudGood item : ConfigName.getInstance().cloudGoods) {
            contents_ydcp.add(new SectionItem(item.goods_Name, "180", item.id, item.goods_ImgUrl, false, true, Bendi_id.contains(item.id) ? true : false));
        }
        list.add(new QMUISection<>(header_bdcp, contents_bdcp, false));
        list.add(new QMUISection<>(header_sccp, contents_sccp, true));
        list.add(new QMUISection<>(header_ydcp, contents_ydcp, true));
        return list;
    }

    private void initTopBar() {
        mTopBar.setTitle("菜谱管理");
        /**
         * 返回按钮
         */
        mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        /**
         * 下载云端菜谱
         */
        mTopBar.addRightImageButton(R.mipmap.clouddownload,R.id.cLeftImageViewId).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = "同步云端菜谱操作提示！";
                String message = "请问客官确定要同步菜谱吗?此操作将完全复刻云端菜谱,本地菜谱将清除！请确认本地菜谱已上传云端！！！！";
                AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {

                        if(ConfigName.getInstance().cloudGoods!=null && ConfigName.getInstance().cloudGoods.size()>0)
                        {
                            ArrayList<BPA_GOODS> goods= QueryDB.GetGoodsALL();
                            ArrayList<BPA_GOODSRECIPE> rec= QueryDB.GetGoodsSrecipeALL();
                            for (BPA_GOODS good:goods)
                            {
                                QueryDB.DeleteGoods(good);
                            }
                            for (BPA_GOODSRECIPE pf:rec)
                            {
                                QueryDB.DeleteGoodsSrecipe(pf);
                            }

                            for (CloudGood item : ConfigName.getInstance().cloudGoods) {
                                ConfigData.getInstance().GetGoodProcess(context,item.id,false);
                            }
                        }
                        dialog.dismiss();
                    }
                });
            }
        });

        /**
         * 新建商品
         */
        mTopBar.addRightTextButton("新建商品",R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                skipToActivity(DiyActivity.class);
            }
        });


    }

    /**
     * 跳转界面
     */
    private void skipToActivity(Class da) {
        // 跳转到登录页面
        Intent intent = new Intent(context, da);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected boolean canDragBack() {
        return false;
    }
}