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

import android.app.Dialog;
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.PurchaseListMorePopup;
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.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
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;

    private final static int REQUEST_ORDER_DETAILS_CODE = 1001;

    @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) {
        refreshPurchaseList.setPrimaryColorsId(R.color.trans, R.color.black);
        btnNewOrder.setText("+新增訂單");
//        edSearch.setFilters(new InputFilter[]{InputFilterUtils.getChAndEnAndNumInputFilter(mContext), InputFilterUtils.getLengthFilter(mContext, 20)});
        btnNewOrder.setOnClickListener(v -> {
            //跳轉到下單頁面
            startForResult(FoodIngredientsFragment.newInstance(ADD_ORDER), REQUEST_ORDER_DETAILS_CODE);
        });
        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("", 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 -> {
            //需要先判斷是否有食品
            if (SupplyShoppingCart.getInstance().getCartFoods().size() > 0) {
                start(ShoppingCatFragment.newInstance());
            } else {
                //跳轉到下單頁面
                showMessage("請先選擇食品");
                startForResult(FoodIngredientsFragment.newInstance(ADD_ORDER), REQUEST_ORDER_DETAILS_CODE);
            }
        });
    }

    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) ->
                startForResult(OrderDetailsFragment.newInstance(purchaseOrderAdapter.getData().get(position).getId(), orderState[orderStateIndex]), REQUEST_ORDER_DETAILS_CODE)
        );
        purchaseOrderAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int viewId = view.getId();
            if (viewId == R.id.iv_purchase_order_more) {
                //更多：刪除。發送。再次購買
                new XPopup.Builder(mContext)
                        .atView(view)
                        .hasShadowBg(false)
                        .popupPosition(PopupPosition.Left)
                        .asCustom(new PurchaseListMorePopup(mContext)
                                //, "再次购买"  , R.drawable.ic_purchase_buy_again
                                .setStringData(new String[]{"删除", "发送"}, new int[]{R.drawable.ic_purchase_delete, R.drawable.ic_purchase_send})
                                .setOnSelectListener((popupPosition, text) -> {
                                    if (popupPosition == 0) {
                                        //刪除
                                        AppDialog.getInstance().showWaringDialog(mContext, "是否刪除訂單", (view1, dialog) -> {
                                            mPresenter.deleteOrder(position, purchaseOrderAdapter.getData().get(position).getId());
                                        });
                                    } else if (popupPosition == 1) {
                                        //發送採購單
                                        sendPurchase(position);
                                    }
                                }))
                        .show();
            }
        });
        PurchasePageAdapter adapter = new PurchasePageAdapter(purchaseOrderAdapter, 2);
        contentViewPager.setAdapter(adapter);
        mTabSegment.setupWithViewPager(contentViewPager);
        QMUITabIndicator qmuiTabIndicator = new QMUITabIndicator(
                ContextCompat.getDrawable(mContext, R.drawable.ic_open_close), false, false, ContextCompat.getColor(mContext, R.color.color_3c));
        mTabSegment.setIndicator(qmuiTabIndicator);
        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);
            }
        });
    }

    private void sendPurchase(int position) {
        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)));
    }

    @OnClick({R2.id.iv_purchase_list_screen, R2.id.iv_purchase_list_search})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.iv_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) {
        closeLoading();
        if (list == null) {
            loadService.showCallback(EmptyCallback.class);
        } else if (list.size() == 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showCallback(SuccessCallback.class);
        }
        purchaseOrderAdapter.setList(list);
    }

    private void closeLoading() {
        refreshPurchaseList.finishRefresh();
        refreshPurchaseList.finishLoadMore();
    }

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

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

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

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ORDER_DETAILS_CODE) {
//            //用戶對訂單進行了操作，需要對列表進行刷新
            getOrderList();
        }
    }
}
