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.core.content.ContextCompat;
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.WareHouseListBean;
import com.gingersoft.supply_chain.mvp.contract.WarehousingInventoryContract;
import com.gingersoft.supply_chain.mvp.presenter.WarehousingInventoryPresenter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.zhy.autolayout.utils.ScreenUtils;

import org.w3c.dom.Text;

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 int foodNum;
    private String foodNo;

    private int pageIndex;

    public static WarehousingInventoryFragment newInstance(WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVOSBean purchaseWarehousingOrderDetailsVosBean) {
        WarehousingInventoryFragment fragment = new WarehousingInventoryFragment();
        Bundle bundle = new Bundle();
        bundle.putString(WarehouseDetailsFragment.FOOD_NAME_KEY, purchaseWarehousingOrderDetailsVosBean.getName());
        bundle.putInt(WarehouseDetailsFragment.FOOD_ID_KEY, purchaseWarehousingOrderDetailsVosBean.getId());
        bundle.putInt(WarehouseDetailsFragment.FOOD_NUM_KEY, purchaseWarehousingOrderDetailsVosBean.getFoodNum());
        bundle.putString(WarehouseDetailsFragment.FOOD_NO_KEY, purchaseWarehousingOrderDetailsVosBean.getFoodNo());
        bundle.putString(WarehouseDetailsFragment.FOOD_IMAGE_KEY, purchaseWarehousingOrderDetailsVosBean.getImages());
        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) {
            //獲取庫存盤點記錄
            getWarehousingRecord();
            int foodId = arguments.getInt(WarehouseDetailsFragment.FOOD_ID_KEY);
            //食品編號
            foodNo = arguments.getString(WarehouseDetailsFragment.FOOD_NO_KEY);
            //食品庫存總數
            foodNum = arguments.getInt(WarehouseDetailsFragment.FOOD_NUM_KEY);
            //加載食品圖片
            loadFoodImage(arguments);
            //初始化標題
            initTopBar(arguments);
            //初始化數量和編輯監聽
            initEdit();
        } else {
            showMessage("獲取食材信息失敗，請稍候重試");
            killMyself();
        }
    }

    private void getWarehousingRecord() {
        mPresenter.getWarehousingRecord(pageIndex);
    }

    private void initEdit() {
        //庫存數量
        tvWarehouseTotal.setText(String.valueOf(foodNum));
        //庫存差異
        tvWarehouseDifference.setText(String.valueOf(foodNum));
        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(foodNum - inventoryNum)));
                } else {
                    tvWarehouseDifference.setText(String.valueOf(foodNum));
                }
            }
        });
    }

    private void initTopBar(Bundle arguments) {
        String foodName = arguments.getString(WarehouseDetailsFragment.FOOD_NAME_KEY);
        //初始化標題
        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(Bundle arguments) {
        String foodImageUrl = arguments.getString(WarehouseDetailsFragment.FOOD_IMAGE_KEY);
        if (TextUtil.isNotEmptyOrNullOrUndefined(foodImageUrl)) {
            GlideUtils.display(requireContext(), ivWarehouseImg, foodImageUrl);
        } 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 = foodNum - inventoryNum;
                    mPresenter.consumeWareHousing(foodNo, remainingAmount);
                }
            }
        }
    };

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

    @Override
    public void loadRecord() {

    }
}
