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

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.gingersoft.gsa.cloud.common.utils.glide.GlideUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerWarehousingInventoryComponent;
import com.gingersoft.supply_chain.mvp.bean.InventoryRecordBean;
import com.gingersoft.supply_chain.mvp.bean.WareHouseListBean;
import com.gingersoft.supply_chain.mvp.contract.WarehousingInventoryContract;
import com.gingersoft.supply_chain.mvp.presenter.WarehousingInventoryPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.InventoryRecordAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
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;


/**
 * Description: 庫存盤點
 */
public class WarehousingInventoryFragment extends BaseSupplyChainFragment<WarehousingInventoryPresenter> implements WarehousingInventoryContract.View {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.iv_warehouse_img)
    ImageView ivWarehouseImg;
    @BindView(R2.id.tv_warehouse_total)
    TextView tvWarehouseTotal;
    @BindView(R2.id.tv_warehouse_difference)
    TextView tvWarehouseDifference;
    @BindView(R2.id.ed_warehouse_loss)
    EditText edWarehouseLoss;
    @BindView(R2.id.rv_warehouse_inventory_record)
    RecyclerView rvRecord;
    private InventoryRecordAdapter adapter;
    @BindView(R2.id.smart_inventory_record)
    SmartRefreshLayout smartRefreshLayout;
    private int pageIndex;

    private WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVo;

    public static WarehousingInventoryFragment newInstance(WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVo) {
        WarehousingInventoryFragment fragment = new WarehousingInventoryFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(WarehouseDetailsFragment.FOOD_INFO_KEY, purchaseWarehousingOrderDetailsVo);
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            purchaseWarehousingOrderDetailsVo = (WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVO) arguments.getSerializable(WarehouseDetailsFragment.FOOD_INFO_KEY);
            //獲取庫存盤點記錄
            getWarehousingRecord();
            //加載食品圖片
            loadFoodImage();
            //初始化標題
            initTopBar(purchaseWarehousingOrderDetailsVo.getName());
            //初始化數量和編輯監聽
            initEdit();
        } else {
            showMessage("獲取食材信息失敗，請稍候重試");
            killMyself();
        }
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            getWarehousingRecord();
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            getWarehousingRecord();
        });
    }

    private void getWarehousingRecord() {
        mPresenter.getWarehousingRecord(purchaseWarehousingOrderDetailsVo.getFoodNo(), pageIndex);
    }

    private void initEdit() {
        //庫存數量
        tvWarehouseTotal.setText(String.valueOf(purchaseWarehousingOrderDetailsVo.getFoodNum()));
        //庫存差異
        tvWarehouseDifference.setText(String.valueOf(purchaseWarehousingOrderDetailsVo.getFoodNum()));
        edWarehouseLoss.setOnFocusChangeListener((v, hasFocus) -> {
            //當輸入框獲得焦點時，數量為0，去掉0
            if (hasFocus && edWarehouseLoss.getText().toString().equals("0")) {
                edWarehouseLoss.setText("");
            }
        });
        edWarehouseLoss.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtil.isNotEmptyOrNullOrUndefined(s + "")) {
                    //用戶輸入的盤點數量
                    int inventoryNum = Integer.parseInt(s + "");
//                        if (inventoryNum > foodNum) {
//                            inventoryNum = foodNum;
//                            showMessage("不能大於庫存數");
//                            edWarehouseLoss.setText(String.valueOf(foodNum));
//                            edWarehouseLoss.setSelection(edWarehouseLoss.getText().length());
//                        }
                    tvWarehouseDifference.setText(String.valueOf(Math.abs(purchaseWarehousingOrderDetailsVo.getFoodNum() - inventoryNum)));
                } else {
                    tvWarehouseDifference.setText(String.valueOf(purchaseWarehousingOrderDetailsVo.getFoodNum()));
                }
            }
        });
    }

    private void initTopBar(String foodName) {
        //初始化標題
        initTopBar(supplyTopBar, foodName);
        //添加保存按鈕
        Button btnSave = supplyTopBar.addRightTextButton(R.string.str_save, R.id.id_save);
        btnSave.setTextColor(getColor(R.color.white));
        btnSave.setOnClickListener(mOnClickListener);
    }

    private void loadFoodImage() {
        if (TextUtil.isNotEmptyOrNullOrUndefined(purchaseWarehousingOrderDetailsVo.getImages())) {
            GlideUtils.display(requireContext(), ivWarehouseImg, purchaseWarehousingOrderDetailsVo.getImages());
        } else {
            ivWarehouseImg.setImageResource(R.drawable.img_small_default);
        }
    }

    private View.OnClickListener mOnClickListener = v -> {
        if (v.getId() == R.id.id_save) {
            //保存，調用庫存損耗
            if (TextUtil.isEmptyOrNullOrUndefined(edWarehouseLoss)) {
                showMessage("請輸入盤點庫存數量");
                edWarehouseLoss.requestFocus();
            } else {
                //盤點數量
                int inventoryNum = Integer.parseInt(edWarehouseLoss.getText().toString());
                if (inventoryNum <= 0) {
                    showMessage("請輸入盤點庫存數量");
                    edWarehouseLoss.requestFocus();
                } else {
                    int remainingAmount = purchaseWarehousingOrderDetailsVo.getFoodNum() - inventoryNum;
                    mPresenter.consumeWareHousing(purchaseWarehousingOrderDetailsVo.getFoodNo(), remainingAmount);
                }
            }
        }
    };

    @Override
    public void updateSuccess() {
        setFragmentResult(RESULT_OK, null);
    }

    @Override
    public void loadRecord(List<InventoryRecordBean> inventoryRecordBeans) {
        smartRefreshLayout.finishLoadMore();
        smartRefreshLayout.finishRefresh();
        //加載盤點記錄
        if (adapter == null) {
            adapter = new InventoryRecordAdapter(inventoryRecordBeans);
            rvRecord.setAdapter(adapter);
        } else {
            adapter.setList(inventoryRecordBeans);
        }
    }
}
