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

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerWareHouseListComponent;
import com.gingersoft.supply_chain.mvp.bean.WareHouseListBean;
import com.gingersoft.supply_chain.mvp.contract.WareHouseListContract;
import com.gingersoft.supply_chain.mvp.presenter.WareHouseListPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.WarehousingQueryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
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.qmuiteam.qmui.widget.QMUITopBar;
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.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 庫存查詢列表
 */
public class WareHouseListFragment extends BaseSupplyChainFragment<WareHouseListPresenter> implements WareHouseListContract.View {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.iv_warehouse_list_search)
    ImageView ivWarehouseListSearch;
    @BindView(R2.id.ed_warehouse_list_search)
    EditText edWarehouseListSearch;
    @BindView(R2.id.tv_overdue_food_num)
    TextView tvOverdueFoodNum;
    @BindView(R2.id.tv_expiring_soon_food_num)
    TextView tvExpiringSoonFoodNum;
    @BindView(R2.id.tv_low_inventory_food_num)
    TextView tvLowInventoryFoodNum;
    @BindView(R2.id.tv_ingredients_cost_inventory)
    TextView tvIngredientsCostInventory;
    @BindView(R2.id.rv_warehouse_list)
    RecyclerView rvWarehouseList;
    @BindView(R2.id.sl_warehousing_list)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R2.id.hs_warehousing_list)
    HorizontalScrollView hsWarehousingList;
    @BindView(R2.id.tv_warehouse_item_unit_price)
    TextView tvUnitPrice;
    @BindView(R2.id.tv_warehouse_item_inventory_quantity)
    TextView tvWarehousingQuantity;
    @BindView(R2.id.tv_warehouse_item_total_amount)
    TextView tvTotalAmount;
    private int SORT_TYPE = 0;
    /**
     * 升序或降序
     */
    private boolean isAscending = false;
    private int pageIndex = 0;
    /**
     * 調整到其他頁面，用於回來是否刷新數據
     */
    private final int UPDATE_KEY = 1001;
    private WarehousingQueryAdapter warehousingQueryAdapter;

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        smartRefreshLayout.setPrimaryColorsId(R.color.trans, R.color.black);
        initTopBar(supplyTopBar, "庫存查詢");
        loadService = LoadSir.getDefault().register(rvWarehouseList);
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            getWarehousing();
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            getWarehousing();
        });
        getWarehousing();
    }

    private void getWarehousing() {
        mPresenter.getWarehousing(pageIndex, edWarehouseListSearch.getText() + "");
    }


    @OnClick({R2.id.iv_warehouse_list_search, R2.id.tv_warehouse_item_unit_price, R2.id.tv_warehouse_item_inventory_quantity, R2.id.tv_warehouse_item_total_amount})
    public void OnClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_warehouse_list_search) {
            pageIndex = 0;
            getWarehousing();
        } else if (id == R.id.tv_warehouse_item_unit_price) {
            //切換按單價排序
            sort(mPresenter.SORT_UNIT_PRICE);
        } else if (id == R.id.tv_warehouse_item_inventory_quantity) {
            //按庫存數量排序
            sort(mPresenter.SORT_WAREHOUSING_NUM);
        } else if (id == R.id.tv_warehouse_item_total_amount) {
            //按總價排序
            sort(mPresenter.SORT_TOTAL_AMOUNT);
        }
    }

    private void sort(int sortType) {
        if (SORT_TYPE == sortType) {
            isAscending = !isAscending;
        } else {
            SORT_TYPE = sortType;
        }
        mPresenter.sortByType(SORT_TYPE, isAscending);
    }

    @Override
    public void loadWarehousingInfo(WareHouseListBean.WareHousingDataBean data) {
        WareHouseListBean.WareHousingDataBean.TotalBean total = data.getTotal();
        tvOverdueFoodNum.setText(total.getOverdue() + "");
        tvExpiringSoonFoodNum.setText(total.getAboutExpire() + "");
        tvLowInventoryFoodNum.setText(total.getOutStock() + "");
        tvIngredientsCostInventory.setText(String.format(getString(R.string.amount_string), total.getCost()));
        loadListInfo(data.getPurchaseWarehousingOrderDetailsVOS());
    }

    @Override
    public void finishLoad() {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
    }

    @Override
    public void loadFail() {
        finishLoad();
        loadService.showCallback(ErrorCallback.class);
    }

    @Override
    public void loadListInfo(List<WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVOSBean> purchaseWarehousingOrderDetailsVos) {
        if (purchaseWarehousingOrderDetailsVos == null || purchaseWarehousingOrderDetailsVos.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
            return;
        } else {
            loadService.showSuccess();
        }
        if (warehousingQueryAdapter == null) {
            warehousingQueryAdapter = new WarehousingQueryAdapter(mContext, purchaseWarehousingOrderDetailsVos);
            rvWarehouseList.setLayoutManager(new LinearLayoutManager(mContext));
            rvWarehouseList.setAdapter(warehousingQueryAdapter);

            warehousingQueryAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if(view.getId() == R.id.tv_warehouse_item_inventory_quantity){
                    //點擊庫存數量，進入庫存盤點
                    startForResult(WarehousingInventoryFragment.newInstance(warehousingQueryAdapter.getItem(position)), UPDATE_KEY);
                }
            });
            warehousingQueryAdapter.setOnItemClickListener((adapter, view, position) -> {
                //進入庫存詳情
                startForResult(WarehouseDetailsFragment.newInstance(warehousingQueryAdapter.getItem(position)), UPDATE_KEY);
            });
        } else {
            warehousingQueryAdapter.setList(purchaseWarehousingOrderDetailsVos);
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if(requestCode == UPDATE_KEY && resultCode == RESULT_OK){
            getWarehousing();
        }
    }
}
