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

import android.os.Bundle;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

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.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.animator.CustomAnimation1;
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.PurchaseWarehousingOrderDetailsVO;
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.gingersoft.supply_chain.mvp.ui.widget.TableView;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


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

    @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.table_ware_housing_list)
    TableView mTableView;

    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() {
        return new WareHouseListFragment();
    }

    @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) {
        initTopBar(supplyTopBar, "庫存查詢");
        loadService = LoadSir.getDefault().register(mTableView);
        getWarehousing();
        edWarehouseListSearch.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 16), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(mContext)});
        edWarehouseListSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                //響應回車按鈕
                //隐藏软键盘
                hideSoftInput();
                pageIndex = 0;
                getWarehousing();
            }
            return false;
        });
    }

    private void getWarehousing() {
        if (pageIndex == 0 && warehousingQueryAdapter != null) {
            warehousingQueryAdapter.setList(null);
        }
        mPresenter.getWarehousing(pageIndex, TextUtil.getNotNullStrAndTrim(edWarehouseListSearch.getText().toString()));
    }

    //R2.id.tv_warehouse_item_unit_price, R2.id.tv_warehouse_item_inventory_quantity, R2.id.tv_warehouse_item_total_amount
    @OnClick({R2.id.iv_warehouse_list_search, R2.id.bt_warehouse_list_search})
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_warehouse_list_search || id == R.id.bt_warehouse_list_search) {
            pageIndex = 0;
            getWarehousing();
        } else if (id == R.id.layout_unit_price) {
            //切換按單價排序`
            sort(mPresenter.SORT_UNIT_PRICE);
        } else if (id == R.id.layout_inventory_quantity) {
            //按庫存數量排序
            sort(mPresenter.SORT_WAREHOUSING_NUM);
        } else if (id == R.id.layout_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, warehousingQueryAdapter.getData());
    }

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

    @Override
    public void finishLoadNoMoreData() {
        mTableView.freshAndLoadSuccess();
        mTableView.loadMoreSuccessWithNoMoreData();
        if (warehousingQueryAdapter == null || warehousingQueryAdapter.getItemCount() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
        }
    }

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

    @Override
    public void loadSortData(List<PurchaseWarehousingOrderDetailsVO> purchaseWarehousingOrderDetailsVos) {
        warehousingQueryAdapter.setList(purchaseWarehousingOrderDetailsVos);
    }

    @Override
    public void loadListInfo(List<PurchaseWarehousingOrderDetailsVO> purchaseWarehousingOrderDetailsVos) {
        if (purchaseWarehousingOrderDetailsVos == null || purchaseWarehousingOrderDetailsVos.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
            return;
        } else {
            loadService.showSuccess();
        }

        if (warehousingQueryAdapter == null) {
            mTableView.getHeadView().findViewById(R.id.layout_unit_price).setOnClickListener(this);
            mTableView.getHeadView().findViewById(R.id.layout_inventory_quantity).setOnClickListener(this);
            mTableView.getHeadView().findViewById(R.id.layout_total_amount).setOnClickListener(this);

            warehousingQueryAdapter = new WarehousingQueryAdapter(mContext, purchaseWarehousingOrderDetailsVos);
            warehousingQueryAdapter.setAdapterAnimation(new CustomAnimation1());
            mTableView.setOnTableRefreshAndLoadMoreListener(new TableView.OnTableRefreshAndLoadMoreListener() {
                @Override
                public void onTableRefresh() {
                    pageIndex = 0;
                    getWarehousing();
                }

                @Override
                public void onTableLoadMore() {
                    pageIndex++;
                    getWarehousing();
                }
            })
                    .setContentAdapter(warehousingQueryAdapter);
//            rvWarehouseList.setLayoutManager(new LinearLayoutManager(requireContext()));
//            rvWarehouseList.setAdapter(warehousingQueryAdapter);
            warehousingQueryAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.layout_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.addData(purchaseWarehousingOrderDetailsVos);
        }
    }

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