package com.gingersoft.supply_chain.mvp.ui.fragment.order;

import android.os.Bundle;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerPurchaseListComponent;
import com.gingersoft.supply_chain.mvp.bean.ConfirmOrderBean;
import com.gingersoft.supply_chain.mvp.bean.OrderBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.PurchaseListContract;
import com.gingersoft.supply_chain.mvp.presenter.PurchaseListPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.PurchaseOrderAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.PurchasePageAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.ScreenView;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.tab.QMUIBasicTabSegment;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment2;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment.ADD_ORDER;


/**
 * Description:採購單列表
 */
public class PurchaseListFragment extends BaseSupplyChainFragment<PurchaseListPresenter> implements PurchaseListContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_purchase_list)
    QMUITopBar mTopBar;
    @BindView(R2.id.purchase_list_tabSegment)
    QMUITabSegment2 mTabSegment;
    @BindView(R2.id.contentViewPager)
    ViewPager2 contentViewPager;
    @BindView(R2.id.btn_save)
    QMUIAlphaButton btnNewOrder;
    @BindView(R2.id.screen_view)
    ScreenView screenView;
    @BindView(R2.id.view_load_bg)
    View loadBg;
    @BindView(R2.id.ed_food_ingredients_search)
    EditText edSearch;
    @BindView(R2.id.srl_purchase_list)
    SmartRefreshLayout refreshPurchaseList;

    private PurchaseOrderAdapter purchaseOrderAdapter;

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

    private final int[] orderState = new int[]{PurchaseOrderDetailsBean.WAIT_RECEIVED, PurchaseOrderDetailsBean.COMPLETE_RECEIVED};
    private int pageIndex = 0;
    /**
     * 當前訂單列表類型的下標
     */
    private int orderStateIndex = 0;

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerPurchaseListComponent //如找不到该类,请编译一下项目
                .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.fragment_purchase_list, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        btnNewOrder.setText("+新增訂單");
        edSearch.setFilters(new InputFilter[]{InputFilterUtils.getChAndEnAndNumInputFilter(mContext), InputFilterUtils.getLengthFilter(mContext, 20)});
        btnNewOrder.setOnClickListener(v -> {
            //跳轉到下單頁面
            start(FoodIngredientsFragment.newInstance(ADD_ORDER));
        });
        loadService = LoadSir.getDefault().register(loadBg, (Callback.OnReloadListener) v -> getOrderList());
        refreshPurchaseList.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            getOrderList();
        });
        refreshPurchaseList.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            getOrderList();
        });
        initTopBar();
        initTabAndData();
        getOrderList();
    }

    private void getOrderList() {
        mPresenter.getOrderList(edSearch.getText() + "", orderState[orderStateIndex], pageIndex);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (tvCartGoodsNum != null) {
            tvCartGoodsNum.setText(String.valueOf(SupplyShoppingCart.getInstance().getCartFoods().size()));
        }
    }

    private TextView tvCartGoodsNum;

    private void initTopBar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> killMyself());
        mTopBar.setTitle("採購列表");
        View view = View.inflate(mContext, R.layout.layout_shopping_cart, null);
        tvCartGoodsNum = view.findViewById(R.id.tv_purchase_cart_size);
        tvCartGoodsNum.setText(String.valueOf(SupplyShoppingCart.getInstance().getCartFoods().size()));

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mTopBar.addRightView(view, R.id.qmui_shopping_cart, layoutParams);
        view.setOnClickListener(v -> start(ShoppingCatFragment.newInstance()));
    }

    private void initTabAndData() {
        QMUITabBuilder builder = mTabSegment.tabBuilder()
                .setNormalColor(ContextCompat.getColor(mContext, R.color.color_86))
                .setSelectColor(ContextCompat.getColor(mContext, R.color.theme_color));

        purchaseOrderAdapter = new PurchaseOrderAdapter(null);
        purchaseOrderAdapter.setOnItemClickListener((adapter, view, position) -> start(OrderDetailsFragment.newInstance(purchaseOrderAdapter.getData().get(position).getId())));
        purchaseOrderAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int viewId = view.getId();
            if (viewId == R.id.iv_supplier_delete) {
                //刪除採購單
                AppDialog.getInstance().showWaringDialog(mContext, "是否刪除採購單?", (view1, dialog) -> {
                    List<OrderBean> data = purchaseOrderAdapter.getData();
                    mPresenter.deleteOrder(position, data.get(position));
                    dialog.dismiss();
                });
            } else if (viewId == R.id.btn_purchase_send) {
                //發送採購單
                List<OrderBean> data = purchaseOrderAdapter.getData();
                OrderBean orderBean = data.get(position);

                ConfirmOrderBean.PurchaseOrder purchaseOrder = new ConfirmOrderBean.PurchaseOrder();
                purchaseOrder.setId(orderBean.getId());
                purchaseOrder.setSupplierId(orderBean.getSupplierId());
                purchaseOrder.setSupplierName(orderBean.getSupplierName());
                start(SendMsgFragment.newInstance(Collections.singletonList(purchaseOrder)));
            }
        });
        PurchasePageAdapter adapter = new PurchasePageAdapter(purchaseOrderAdapter, 4);
        contentViewPager.setAdapter(adapter);
        mTabSegment.setupWithViewPager(contentViewPager);
        mTabSegment.setIndicator(new QMUITabIndicator(
                QMUIDisplayHelper.dp2px(getContext(), 2), false, false));
        mTabSegment.addTab(builder.setText("未完成").build(getContext()));
        mTabSegment.addTab(builder.setText("已完成").build(getContext()));
//        mTabSegment.addTab(builder.setText("部分收貨").build(getContext()));
//        mTabSegment.addTab(builder.setText("全部收貨").build(getContext()));
        mTabSegment.notifyDataChanged();
        mTabSegment.setMode(QMUITabSegment.MODE_FIXED);
        mTabSegment.addOnTabSelectedListener(new QMUIBasicTabSegment.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int index) {
                orderStateIndex = index;
                getOrderList();
            }

            @Override
            public void onTabUnselected(int index) {

            }

            @Override
            public void onTabReselected(int index) {

            }

            @Override
            public void onDoubleTap(int index) {
                mTabSegment.clearSignCountView(index);
            }
        });
    }

    @OnClick({R2.id.layout_purchase_list_screen, R2.id.iv_purchase_list_search})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.layout_purchase_list_screen) {
            //篩選
            screenView.setVisibility(screenView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        } else if (viewId == R.id.iv_purchase_list_search) {
            getOrderList();
        }
    }

    @Override
    public void loadOrderList(List<OrderBean> list) {
        refreshPurchaseList.finishRefresh();
        refreshPurchaseList.finishLoadMore();
        loadService.showCallback(SuccessCallback.class);
        purchaseOrderAdapter.setList(list);
    }

    @Override
    public void loadFail() {
        purchaseOrderAdapter.setList(null);
        loadService.showCallback(EmptyCallback.class);
    }

    @Override
    public void loadError() {
        purchaseOrderAdapter.setList(null);
        loadService.showCallback(ErrorCallback.class);
    }

    @Override
    public void deleteOrder(int position) {
        purchaseOrderAdapter.removeAt(position);
    }
}
