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

import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerWarehousingOrderDetailsComponent;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodEncodeSn;
import com.gingersoft.supply_chain.mvp.contract.WarehousingOrderDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.WarehousingOrderDetailsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.ConsumptionReasonAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.WareHousingOrderFoodAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.BuyIngredientsFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodWarehousingFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.GoodsDetailsPopup;
import com.gingersoft.supply_chain.mvp.ui.widget.ScanSnPopup;
import com.gingersoft.supply_chain.mvp.ui.widget.WarehousingFoodDetailsPopup;
import com.jess.arms.di.component.AppComponent;
import com.lxj.xpopup.XPopup;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Description: 入庫單詳情
 *
 * @author admin
 */
public class WarehousingOrderDetailsFragment extends BaseSupplyChainFragment<WarehousingOrderDetailsPresenter> implements WarehousingOrderDetailsContract.View, View.OnClickListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.rv_warehousing_type)
    RecyclerView rvWarehousingType;
    @BindView(R2.id.rv_warehousing_food)
    RecyclerView rvWarehousingFood;
    @BindView(R2.id.switch_warehousing_is_print)
    SwitchCompat switchWarehousingIsPrint;
    @BindView(R2.id.tv_food_species)
    TextView tvFoodSpecies;
    @BindView(R2.id.tv_order_total_amount)
    TextView tvOrderTotalAmount;
    @BindView(R2.id.ed_remark)
    EditText edRemark;
    @BindView(R2.id.tv_order_confirm)
    QMUIAlphaTextView tvOrderConfirm;
    @BindView(R2.id.tv_order_cancel)
    QMUIAlphaTextView tvOrderCancel;
    @BindView(R2.id.layout_btn)
    LinearLayout layoutBtn;
    private boolean isLeave = false;

    private int warehousingOrderId;
    private String warehousingReason;

    public static final int ADD_FOOD_REQUEST_CODE = 1001;

    private static final String WAREHOUSING_ORDER_ID_KEY = "warehousingOrderIdKey";
    private static final String WAREHOUSING_ORDER_REASON_KEY = "warehousingReasonKey";

    public static WarehousingOrderDetailsFragment newInstance(int warehousingOrderId, String reason) {
        WarehousingOrderDetailsFragment fragment = new WarehousingOrderDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(WAREHOUSING_ORDER_ID_KEY, warehousingOrderId);
        bundle.putString(WAREHOUSING_ORDER_REASON_KEY, reason);
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar(supplyTopBar, getString(R.string.str_warehousing_order));
        Bundle arguments = getArguments();
        //入庫類型
        rvWarehousingType.setLayoutManager(new GridLayoutManager(requireContext(), 3));
        mPresenter.getWarehousingReason();
        if (arguments != null) {
            warehousingOrderId = arguments.getInt(WAREHOUSING_ORDER_ID_KEY, -1);
            warehousingReason = arguments.getString(WAREHOUSING_ORDER_REASON_KEY);
            if (warehousingOrderId != -1) {
                mPresenter.getWarehousingOrderDetails(warehousingOrderId);
                layoutBtn.setVisibility(View.GONE);
                return;
            }
        }
        initFoodInfo();
    }

    private void initFoodInfo() {
        mPresenter.initWarehousingFood();
        setOrderAllInfo();
    }

    @Override
    public void setOrderAllInfo() {
        //總價
        tvOrderTotalAmount.setText(String.format(getString(R.string.str_amount_tran_s), MoneyUtil.formatDouble(mPresenter.getFoodTotalAmount())));
        //種類
        tvFoodSpecies.setText(mPresenter.getFoodSize() + "");
    }


    private View getHeader() {
        View view = getLayoutInflater().inflate(R.layout.item_warehousing_order_details, rvWarehousingFood, false);
        TextView goodsName = view.findViewById(R.id.tv_goods_name);
        TextView goodsUnit = view.findViewById(R.id.tv_goods_unit);
        TextView goodsNumber = view.findViewById(R.id.tv_goods_quantity);
        TextView tvEdit = view.findViewById(R.id.tv_edit);
        goodsName.setTypeface(null, Typeface.BOLD);
        goodsUnit.setTypeface(null, Typeface.BOLD);
        goodsNumber.setTypeface(null, Typeface.BOLD);
        tvEdit.setTypeface(null, Typeface.BOLD);
        return view;
    }

    private View getFooter(View.OnClickListener onClickListener) {
        View view = getLayoutInflater().inflate(R.layout.footer_add, rvWarehousingFood, false);
        view.setOnClickListener(onClickListener);
        return view;
    }

    @Override
    public void initReason(ConsumptionReasonAdapter consumptionReasonAdapter) {
        rvWarehousingType.setAdapter(consumptionReasonAdapter);
        consumptionReasonAdapter.setOnItemChildClickListener((adapter, view, position) -> consumptionReasonAdapter.setSelectIndex(position));
        mPresenter.setSelectReason(warehousingReason);
    }

    @Override
    public void initFoodView(WareHousingOrderFoodAdapter wareHousingOrderFoodAdapter) {
        wareHousingOrderFoodAdapter.addHeaderView(getHeader());
        rvWarehousingFood.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(requireContext(), R.color.color_ccc), LinearLayout.LayoutParams.MATCH_PARENT, 1));
        if (warehousingOrderId == -1) {
            //加添加食材按鈕
            wareHousingOrderFoodAdapter.addFooterView(getFooter(v -> startForResult(FoodWarehousingFragment.newInstance(), ADD_FOOD_REQUEST_CODE)));
        } else {
            //加一條線
            wareHousingOrderFoodAdapter.addFooterView(getLayoutInflater().inflate(R.layout.include_horizontal_color_ccc_dividing_line, rvWarehousingFood, false));
            if (wareHousingOrderFoodAdapter.getItemCount() > 0) {
                edRemark.setText(String.format(getString(R.string.str_format_remark_colon), wareHousingOrderFoodAdapter.getItem(0).getRemarks()));
                edRemark.setFocusable(false);
                edRemark.setEnabled(false);
                edRemark.setBackground(null);
            }
        }
        rvWarehousingFood.setAdapter(wareHousingOrderFoodAdapter);
        wareHousingOrderFoodAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int viewId = view.getId();
            if (viewId == R.id.layout_unit_switch) {
                //切換單位

            } else if (viewId == R.id.tv_edit) {
                //查看
                PurchaseFoodBean item = wareHousingOrderFoodAdapter.getItem(position);
                if (wareHousingOrderFoodAdapter.getItem(position).getFoodMarkSn() == PurchaseFoodBean.HAS_SN) {
                    //SN食材，輸入SN碼
                    if (warehousingOrderId == -1) {
                        showScanPopup(position, wareHousingOrderFoodAdapter.getItem(position));
                    } else {
                        mPresenter.querySnCodes(item);
                    }
                } else {
                    //顯示詳情
                    new XPopup.Builder(requireContext())
                            .autoOpenSoftInput(false)
                            .autoFocusEditText(false)
                            .asCustom(new WarehousingFoodDetailsPopup(requireContext(), item))
                            .show();
                }
            }
        });
    }

    @Override
    public void addOrderSuccess() {
        isLeave = true;
        setFragmentResult(RESULT_OK, null);
        killMyself();
    }

    /**
     * 顯示掃碼popupwindow
     *
     * @param infoVosBean 食品信息
     */
    private void showScanPopup(int position, PurchaseFoodBean infoVosBean) {
        List<PurchaseFoodEncodeSn> foodEncodeSns = infoVosBean.getPurchaseFoodEncodeSn();
        ScanSnPopup scanSnPopup = new ScanSnPopup(this, infoVosBean.getName(), foodEncodeSns, true);
//                .setOnDeleteListener((snCode, snPosition) -> foodEncodeSns.remove(snCode));
        scanSnPopup.setOnScanResultListener((popup, scanResult) -> {
            //當前食材infoVosBean裡面有個sn碼集合，將scanResult添加進去
            infoVosBean.setPurchaseFoodEncodeSn(scanResult);
            infoVosBean.setFoodQuantity(scanResult.size());
            mPresenter.notifyAdapter(position);
            setOrderAllInfo();
            scanSnPopup.dismissOrHideSoftInput();
            if (!scanSnPopup.isDismiss()) {
                scanSnPopup.dismiss();
            }
        });
        new XPopup.Builder(
                requireContext())
                .asCustom(scanSnPopup)
                .show();
    }

    @Override
    public void showSnCodePopup(PurchaseFoodBean infoVosBean) {
        new XPopup.Builder(requireContext())
                .asCustom(new ScanSnPopup(this, infoVosBean.getName(), infoVosBean.getPurchaseFoodEncodeSn(), false))
                .show();
    }


    private void createWarehousingOrder() {
        mPresenter.createWarehousingOrder(edRemark.getText().toString());
    }

    @OnClick({R2.id.tv_order_cancel, R2.id.tv_order_confirm})
    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.tv_order_confirm) {
            //創建入庫單
            createWarehousingOrder();
        } else if (vId == R.id.tv_order_cancel) {
            killMyself();
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        if (warehousingOrderId == -1 && !isLeave && mPresenter.getFoodSize() > 0) {
            AppDialog.getInstance().showTipDialog(requireContext(), getString(R.string.str_info_not_save_about_to_leave), () -> {
                isLeave = true;
                killMyself();
            });
            return true;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == ADD_FOOD_REQUEST_CODE) {
            //刷新列表
            initFoodInfo();
        }
    }
}
