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.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
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.PurchaseWarehousingOrderDetailsVO;
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.gingersoft.supply_chain.mvp.ui.widget.ScanSnView;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import butterknife.BindView;

import static com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean.HAS_SN;


/**
 * Description: 庫存盤點
 */
public class WarehousingInventoryFragment extends BaseSupplyChainFragment<WarehousingInventoryPresenter> implements
        View.OnClickListener,
        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;
    @BindView(R2.id.layout_inventory_record)
    LinearLayout layoutInventoryTitle;
    @BindView(R2.id.layout_inventory_content)
    LinearLayout layoutContent;
    //    @BindView(R2.id.iv_inventory_scan_sn)
//    ImageView ivScanSn;
    @BindView(R2.id.layout_inventory_sn)
    FrameLayout layoutSnView;
    private int pageIndex;

    private ScanSnView scanSnView;

    private PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVo;

    public static WarehousingInventoryFragment newInstance(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 = (PurchaseWarehousingOrderDetailsVO) arguments.getSerializable(WarehouseDetailsFragment.FOOD_INFO_KEY);
            //獲取庫存盤點記錄
            getWarehousingRecord();
            //加載食品圖片
            loadFoodImage();
            //初始化標題
            initTopBar(purchaseWarehousingOrderDetailsVo.getName());
            //初始化數量和編輯監聽
            initEdit();

//            ivScanSn.setVisibility(purchaseWarehousingOrderDetailsVo.getFoodMarkSn() == HAS_SN ? View.VISIBLE : View.GONE);
            loadService = LoadSir.getDefault().register(smartRefreshLayout, (Callback.OnReloadListener) v -> {
                pageIndex = 0;
                getWarehousingRecord();
            });
        } 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);
        //添加保存按鈕
        if (purchaseWarehousingOrderDetailsVo.getFoodMarkSn() != HAS_SN) {
            addTopRightBtn(R.string.str_save, R.id.id_inventory_consumption);
            edWarehouseLoss.setEnabled(true);
        } else {
            addTopRightBtn(R.string.str_inventory, R.id.id_inventory);
            edWarehouseLoss.setEnabled(false);
        }
    }

    private void addTopRightBtn(int stringId, int btnId) {
        Button btnSave = supplyTopBar.addRightTextButton(stringId, btnId);
        btnSave.setTextColor(getColor(R.color.white));
        btnSave.setOnClickListener(this);
    }


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

    @Override
    public void updateSuccess(int consumeQuantity) {
        setFragmentResult(RESULT_OK, null);
        edWarehouseLoss.setText("0");
        purchaseWarehousingOrderDetailsVo.setFoodNum(purchaseWarehousingOrderDetailsVo.getFoodNum() - consumeQuantity);
        tvWarehouseTotal.setText(purchaseWarehousingOrderDetailsVo.getFoodNum() + "");
        tvWarehouseDifference.setText(purchaseWarehousingOrderDetailsVo.getFoodNum() + "");
        showList();

    }

    private void showList() {
        if (scanSnView != null) {
            layoutSnView.removeView(scanSnView);
            scanSnView = null;
            smartRefreshLayout.setVisibility(View.VISIBLE);
            layoutInventoryTitle.setVisibility(View.VISIBLE);
        }
        pageIndex = 0;
        getWarehousingRecord();
    }

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

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.id_inventory_consumption) {
            //保存，調用庫存損耗
            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(),purchaseWarehousingOrderDetailsVo.getId(), remainingAmount);
                }
            }
        } else if (v.getId() == R.id.id_inventory) {
            if (scanSnView == null) {
                loadService.showSuccess();
                smartRefreshLayout.setVisibility(View.GONE);
                layoutInventoryTitle.setVisibility(View.GONE);
                scanSnView = new ScanSnView(this).setOnScanResultListener((popup, scanResult) -> {
                    //確認
                    if (CollectionUtils.isNullOrEmpty(scanResult)) {
                        showMessage("請掃碼盤點Sn碼");
                        return;
                    }
                    mPresenter.consumeWareHousing(purchaseWarehousingOrderDetailsVo.getFoodNo(),purchaseWarehousingOrderDetailsVo.getId(), purchaseWarehousingOrderDetailsVo.getFoodNum() - scanResult.size(), scanResult);
                }).setOnSingerResultListener((isAdd, snCode, currentSnCodeNumber) -> {
                    //單個掃碼回調
                    edWarehouseLoss.setText(String.valueOf(currentSnCodeNumber));
                }).setOnDeleteSnCodeListener((snCode, position) -> {
                    //刪除某個sncode
                    if (TextUtil.isNotEmptyOrNullOrUndefined(edWarehouseLoss)) {
                        int snCodeSize = Integer.parseInt(edWarehouseLoss.getText().toString());
                        snCodeSize -= 1;
                        edWarehouseLoss.setText(String.valueOf(snCodeSize));
                    }

                }).setOnCancelListener(this::showList).init();
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                layoutParams.topMargin = QMUIDisplayHelper.dp2px(requireContext(), 10);
                layoutSnView.addView(scanSnView, layoutParams);
            } else {
                showList();
            }
            //掃碼sn
//            XPermissionUtils.launchCamera(this, (allGranted, grantedList, deniedList) -> {
//                if (allGranted) {
//                    CC.obtainBuilder(ComponentName.COMPONENT_SCAN)
//                            .setActionName("openScanActivity")
//                            .addParam("scanMode", BarcodeType.ONE_DIMENSION)
//                            .build()
//                            .callAsyncCallbackOnMainThread((cc, result) -> {
//                                Object qrCodeResult = result.getDataItem("qrCodeResult");
//                                if (scanSnView == null) {
//                                    loadService.showSuccess();
//                                    smartRefreshLayout.setVisibility(View.GONE);
//                                    layoutInventoryTitle.setVisibility(View.GONE);
//                                    scanSnView = new ScanSnView(this).setOnScanResultListener((popup, scanResult) -> {
//                                        //確認
//                                        if (CollectionUtils.isNullOrEmpty(scanResult)) {
//                                            showMessage("請掃碼盤點Sn碼");
//                                            return;
//                                        }
//                                        mPresenter.consumeWareHousing(purchaseWarehousingOrderDetailsVo.getFoodNo(), purchaseWarehousingOrderDetailsVo.getFoodNum() - scanResult.size(), scanResult);
//                                    }).setOnSingerResultListener((isAdd, snCode, currentSnCodeNumber) -> {
//                                        //單個掃碼回調
//                                        edWarehouseLoss.setText(String.valueOf(currentSnCodeNumber));
//                                    }).setOnDeleteSnCodeListener((snCode, position) -> {
//                                        //刪除某個sncode
//                                        if (TextUtil.isNotEmptyOrNullOrUndefined(edWarehouseLoss)) {
//                                            int snCodeSize = Integer.parseInt(edWarehouseLoss.getText().toString());
//                                            snCodeSize -= 1;
//                                            edWarehouseLoss.setText(String.valueOf(snCodeSize));
//                                        }
//                                    }).setOnCancelListener(this::showList).setShowScan(false).init();
//                                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//                                    layoutParams.topMargin = QMUIDisplayHelper.dp2px(requireContext(), 10);
//                                    layoutSnView.addView(scanSnView, layoutParams);
//                                }
//                                scanSnView.addCode(qrCodeResult.toString());
//                            });
//                }
//            });
        }
    }
}
