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

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.chad.library.adapter.base.BaseQuickAdapter;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.ui.animator.CustomAnimation1;
import com.gingersoft.gsa.cloud.ui.animator.CustomAnimation3;
import com.gingersoft.gsa.cloud.ui.animator.CustomAnimation4;
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.BuyIngredientsFragment;
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.LoadSir;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
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 java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 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() {
        return new PurchaseListFragment();
    }

    /**
     * 待收貨，已完成
     */
    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)});
        loadService = LoadSir.getDefault().register(loadBg, (Callback.OnReloadListener) v -> getOrderList());
        refreshPurchaseList.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            getOrderList();
        });
        refreshPurchaseList.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            getOrderList();
        });
        initTopBar();
        initTabAndData();
    }

    private void getOrderList() {
        if (pageIndex == 0 && purchaseOrderAdapter != null) {
            purchaseOrderAdapter.setNewInstance(null);
        }
        mPresenter.getOrderList("", orderState[orderStateIndex], pageIndex);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setGoodsSize();
    }

    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);
        setGoodsSize();
        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 {
                //跳轉到下單頁面
                toCreateOrder();
            }
        });
    }

    /**
     * 修改商品數量
     */
    private void setGoodsSize() {
        if (tvCartGoodsNum != null) {
            int shoppingGoodsSize = SupplyShoppingCart.getInstance().getCartFoods().size();
            if (shoppingGoodsSize > 0) {
                tvCartGoodsNum.setVisibility(View.VISIBLE);
                tvCartGoodsNum.setText(String.valueOf(shoppingGoodsSize));
            } else {
                tvCartGoodsNum.setVisibility(View.GONE);
            }
        }
    }

    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.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);
        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) {
                                        //刪除
                                        if (purchaseOrderAdapter.getItem(position).getStatus() == PurchaseOrderDetailsBean.WAIT_RECEIVED) {
                                            //只有待收貨可以刪除
                                            AppDialog.getInstance().showWaringDialog(mContext, "是否刪除訂單", () -> mPresenter.deleteOrder(position, purchaseOrderAdapter.getData().get(position).getId()));
                                        } else {
                                            showMessage("該訂單已有入庫食品，不可刪除！");
                                        }
                                    } 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) {
                Log.e("eee", "onTabSelected" + index);
                orderStateIndex = index;
                pageIndex = 0;
                getOrderList();
            }

            @Override
            public void onTabUnselected(int index) {

            }

            @Override
            public void onTabReselected(int index) {
                Log.e("eee", "onTabReselected" + 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, R2.id.btn_save})
    @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) {
            pageIndex = 0;
            getOrderList();
        } else if (viewId == R.id.btn_save) {
            //跳轉到下單頁面
            toCreateOrder();
        }
    }

    private void toCreateOrder() {
        startForResult(BuyIngredientsFragment.newInstance(), REQUEST_ORDER_DETAILS_CODE);
    }

    @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.addData(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);
        showMessage(getString(R.string.str_order_del_contact_supplier));
    }

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