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

import android.animation.LayoutTransition;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.print.PrintHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.glide.GlideUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.utils.view.LayoutToBitmapUtils;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerWarehouseDetailsComponent;
import com.gingersoft.supply_chain.mvp.bean.ConsumeReasonBean;
import com.gingersoft.supply_chain.mvp.bean.OutboundOrderBean;
import com.gingersoft.supply_chain.mvp.bean.WareHouseListBean;
import com.gingersoft.supply_chain.mvp.bean.WarehouseDetailsBean;
import com.gingersoft.supply_chain.mvp.contract.WarehouseDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.WarehouseDetailsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OutboundOrderAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.PurchasePageAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.WareHousingDetailsAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.InventoryConsumptionView;
import com.gingersoft.supply_chain.mvp.ui.widget.ScanSnView;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Description: 入庫詳情
 *
 * @author admin
 */
public class WarehouseDetailsFragment extends BaseSupplyChainFragment<WarehouseDetailsPresenter> implements WarehouseDetailsContract.View, View.OnClickListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.iv_warehouse_img)
    ImageView ivFoodImg;
    @BindView(R2.id.tv_warehouse_inventory_number)
    TextView tvWarehouseInventoryNumber;
    @BindView(R2.id.tv_warehouse_specifications)
    TextView tvWarehouseSpecifications;
    @BindView(R2.id.tv_warehouse_unit_price)
    TextView tvWarehouseUnitPrice;
    @BindView(R2.id.tv_warehouse_total_amount)
    TextView tvWarehouseTotalAmount;
    @BindView(R2.id.tv_warehousing_record)
    TextView tvWarehousingRecord;
    @BindView(R2.id.tv_outbound_record)
    TextView tvOutboundRecord;
    @BindView(R2.id.vp_warehouse_viewpager)
    ViewPager2 vpWarehouseViewpager;
    @BindView(R2.id.srl_warehouse_details_list)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R2.id.tv_food_unit)
    TextView tvUnit;
    @BindView(R2.id.layout_warehousing_root)
    LinearLayout layoutRoot;

    @BindView(R2.id.layout_warehousing_title)
    LinearLayout layoutTitle;
    /**
     * 庫存消耗view
     */
    private InventoryConsumptionView inventoryConsumptionView;
    /**
     * 掃碼sn碼view
     */
    private ScanSnView scanSnView;
    private WareHousingDetailsAdapter wareHousingDetailsAdapter;
    private PurchasePageAdapter adapter;

    public final static String FOOD_INFO_KEY = "purchaseWarehousingBean";
    private WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVO;
    /**
     * 入庫
     */
    public final static int WAREHOUSE_TYPE = 0;
    /**
     * 出庫
     */
    public final static int OUT_STOCK_TYPE = 1;

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        smartRefreshLayout.setPrimaryColorsId(R.color.trans, R.color.black);
        loadService = LoadSir.getDefault().register(smartRefreshLayout);
//        smartRefreshLayout.setEnableHeaderTranslationContent(false).
//                setEnableFooterTranslationContent(false);
        LayoutTransition layoutTransition = new LayoutTransition();
        layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
        layoutRoot.setLayoutTransition(layoutTransition);
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> getPageInfo());
        if (arguments != null) {
            purchaseWarehousingOrderDetailsVO = (WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVO) arguments.getSerializable(FOOD_INFO_KEY);
            if (purchaseWarehousingOrderDetailsVO == null) {
                killMyself();
                showMessage("食材信息獲取失敗，請稍候重試");
            }
            initTopBar(supplyTopBar, purchaseWarehousingOrderDetailsVO.getName());

            tvUnit.setText(purchaseWarehousingOrderDetailsVO.getUnitName());
            String foodImageUrl = arguments.getString(purchaseWarehousingOrderDetailsVO.getImages());
            if (TextUtil.isNotEmptyOrNullOrUndefined(foodImageUrl)) {
                GlideUtils.display(requireContext(), ivFoodImg, foodImageUrl);
            } else {
                ivFoodImg.setImageResource(R.drawable.img_small_default);
            }
            tvWarehouseInventoryNumber.setText(String.valueOf(purchaseWarehousingOrderDetailsVO.getFoodNum()));
            tvWarehouseUnitPrice.setText(String.format(getString(R.string.str_latest_unit_price_colon), purchaseWarehousingOrderDetailsVO.getFoodPrice()));
            tvWarehouseTotalAmount.setText(String.format(getString(R.string.str_total_amount_colon), purchaseWarehousingOrderDetailsVO.getFoodAmount()));
            tvWarehouseSpecifications.setText(purchaseWarehousingOrderDetailsVO.getUnitName());
            getWarehouseDetails();
            if (purchaseWarehousingOrderDetailsVO.getFoodNum() > 0) {
                //獲取庫存消耗的原因列表
                mPresenter.getWarehouseInventoryReason();
            }
            initViewPager();
        }
    }

    /**
     * 獲取入庫詳情
     */
    private void getWarehouseDetails() {
        mPresenter.getWarehousingOrderDetails(purchaseWarehousingOrderDetailsVO.getFoodNo());
    }

    /**
     * 獲取出庫詳情
     */
    private void getOutStockDetails() {
        mPresenter.getOutStockDetails(purchaseWarehousingOrderDetailsVO.getFoodNo());
    }

    private void initViewPager() {
        vpWarehouseViewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                setBtnSelectState(position);
                if (position == WAREHOUSE_TYPE) {
                    //查詢入庫
                    getWarehouseDetails();
                } else {
                    //查詢出庫
                    getOutStockDetails();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    private void setBtnSelectState(int position) {
        if (wareHousingDetailsAdapter != null) {
            wareHousingDetailsAdapter.setList(new ArrayList<>());
        }
        if (position == WAREHOUSE_TYPE) {
            tvWarehousingRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
            tvWarehousingRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_left_themecolor_radius_btn));
            tvOutboundRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_3c));
            tvOutboundRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_right_white_radius_btn));
        } else {
            tvOutboundRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
            tvOutboundRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_right_themecolor_radius_btn));
            tvWarehousingRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_3c));
            tvWarehousingRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_left_white_radius_btn));
        }
    }


    @Override
    public void loadAdapter(List<WarehouseDetailsBean> warehouseDetailsBeans) {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
        if (warehouseDetailsBeans.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
            if (wareHousingDetailsAdapter == null) {
                wareHousingDetailsAdapter = new WareHousingDetailsAdapter(warehouseDetailsBeans, vpWarehouseViewpager.getCurrentItem());
                if (adapter == null) {
                    adapter = new PurchasePageAdapter(wareHousingDetailsAdapter, 2);
                    vpWarehouseViewpager.setAdapter(adapter);
                }
            } else {
                wareHousingDetailsAdapter.setType(vpWarehouseViewpager.getCurrentItem());
                wareHousingDetailsAdapter.setList(warehouseDetailsBeans);
            }
        }
    }

    @Override
    public void loadConsumeReason(List<ConsumeReasonBean> consumeReasonBeans) {
        Button button = supplyTopBar.addRightTextButton(R.string.str_inventory_consumption, R.id.id_inventory_consumption);
        button.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
        button.setOnClickListener(v -> showInventory(consumeReasonBeans));
    }

    /**
     * 顯示庫存消耗
     *
     * @param consumeReasonBeans 庫存消耗原因
     */
    private void showInventory(List<ConsumeReasonBean> consumeReasonBeans) {
        if (smartRefreshLayout.getVisibility() == View.VISIBLE) {
            //隱藏庫存消耗記錄列表
            showList(View.GONE);
            //移除掉
            if (inventoryConsumptionView != null) {
                layoutRoot.removeView(inventoryConsumptionView);
                layoutRoot.removeView(scanSnView);
            }
            //初始化消耗view
            inventoryConsumptionView = new InventoryConsumptionView(requireContext(), consumeReasonBeans, purchaseWarehousingOrderDetailsVO.getFoodNum());
            layoutRoot.addView(inventoryConsumptionView);
            //如果不是sn食材
            if (!purchaseWarehousingOrderDetailsVO.isSnFood()) {
                inventoryConsumptionView.setShowBtn();
                inventoryConsumptionView.setOnConfirmClickListener((consumptionNum, reasonIndex, remarks) -> inventory(consumeReasonBeans))
                        .setOnCancelListener(() -> showList(View.VISIBLE));
                return;
            }
            //初始化掃碼view
            scanSnView = new ScanSnView(this, null, scanResult -> inventory(consumeReasonBeans)).setOnCancelListener(() -> {
                //取消
                showList(View.VISIBLE);
            });
            //設置LayoutParam
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            int dimensionPixelOffset = requireContext().getResources().getDimensionPixelOffset(R.dimen.dp_10);
            layoutParams.leftMargin = dimensionPixelOffset;
            layoutParams.rightMargin = dimensionPixelOffset;
            layoutParams.bottomMargin = dimensionPixelOffset;
            scanSnView.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_white_eight_corners_bg));
            layoutRoot.addView(scanSnView, layoutParams);
        } else {
            showList(View.VISIBLE);
        }
    }

    private void inventory(List<ConsumeReasonBean> consumeReasonBeans) {
        //掃完碼，點擊確認
        showList(View.VISIBLE);
        //獲取用戶輸入的消耗數量
        int consumptionNum = inventoryConsumptionView.getConsumptionNum();
        if (consumptionNum == -1) {
            return;
        }
        //調用消耗接口
        mPresenter.consumeWareHousing(purchaseWarehousingOrderDetailsVO.getFoodNo(), consumptionNum, consumeReasonBeans.get(inventoryConsumptionView.getReasonIndex()).getId(), inventoryConsumptionView.getRemark());
        setFragmentResult(RESULT_OK, null);

        if (inventoryConsumptionView.getIsPrint()) {
            //打印
            onPrintPdf(consumeReasonBeans.get(inventoryConsumptionView.getReasonIndex()).getDescription(), inventoryConsumptionView.getRemark(), consumptionNum);
        }
    }

    private void onPrintPdf(String consumptionReason, String remarks, int foodNum) {
        PrintHelper printHelper = new PrintHelper(requireContext());
        boolean b = PrintHelper.systemSupportsPrint();
        if (b) {
            //設置縮放模式
            printHelper.setScaleMode(PrintHelper.SCALE_MODE_FIT);
            //設置打印方向
            //橫向 PrintHelper.ORIENTATION_LANDSCAPE
            //縱向 PrintHelper.ORIENTATION_PORTRAIT
            printHelper.setOrientation(PrintHelper.ORIENTATION_LANDSCAPE);
            //設置打印顏色
            printHelper.setColorMode(PrintHelper.COLOR_MODE_MONOCHROME);
            printHelper.printBitmap(String.format(getString(R.string.str_restaurant_outbound_order), purchaseWarehousingOrderDetailsVO.getName()), generatePrintBitmap(consumptionReason, remarks, foodNum), () -> {
                //打印完成回調
            });
        } else {
            //不支持打印
            showMessage(getString(R.string.str_device_not_print));
        }
    }

    private Bitmap generatePrintBitmap(String consumptionReason, String remarks, int foodNum) {
        View view = LayoutInflater.from(requireContext()).inflate(R.layout.layout_print_consume, null);
        TextView restaurantName = view.findViewById(R.id.tv_print_consume_restaurant_name);
        TextView tvDate = view.findViewById(R.id.tv_print_consume_date);
        TextView tvFoodNo = view.findViewById(R.id.tv_print_consume_no);
        RecyclerView rvInfo = view.findViewById(R.id.rv_print_consume_info);
        TextView tvUserName = view.findViewById(R.id.tv_print_consume_user_name);

        restaurantName.setText(String.format(getString(R.string.str_restaurant_outbound_order), RestaurantInfoManager.newInstance().getRestaurantName()));
        tvDate.setText(TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        tvFoodNo.setText(String.format(getString(R.string.str_no), purchaseWarehousingOrderDetailsVO.getFoodNo()));
        tvUserName.setText(String.format(getString(R.string.str_prepared), UserContext.newInstance().getMemberName()));
        List<OutboundOrderBean> outboundOrderBeans = new ArrayList<>();
        outboundOrderBeans.add(new OutboundOrderBean("品名", purchaseWarehousingOrderDetailsVO.getName()));
        outboundOrderBeans.add(new OutboundOrderBean("單位", purchaseWarehousingOrderDetailsVO.getUnitName()));
        outboundOrderBeans.add(new OutboundOrderBean("數量", String.valueOf(foodNum)));
        outboundOrderBeans.add(new OutboundOrderBean("單價", String.valueOf(purchaseWarehousingOrderDetailsVO.getFoodPrice())));
        outboundOrderBeans.add(new OutboundOrderBean("金額", String.valueOf(MoneyUtil.priceCalculation(purchaseWarehousingOrderDetailsVO.getFoodPrice(), foodNum))));
        outboundOrderBeans.add(new OutboundOrderBean("消耗原因", consumptionReason));
        outboundOrderBeans.add(new OutboundOrderBean("備註", remarks));

        OutboundOrderAdapter outboundOrderAdapter = new OutboundOrderAdapter(outboundOrderBeans);
        rvInfo.setAdapter(outboundOrderAdapter);
        return LayoutToBitmapUtils.getBitmapByView(requireContext(), view);
    }

    /**
     * 顯示消耗列表
     *
     * @param visible 是否顯示
     */
    private void showList(int visible) {
        smartRefreshLayout.setVisibility(visible);
        layoutTitle.setVisibility(visible);
        loadService.getLoadLayout().setVisibility(visible);
    }

    @Override
    public void getPageInfo() {
        if (vpWarehouseViewpager.getCurrentItem() == WAREHOUSE_TYPE) {
            //獲取入庫流水
            getWarehouseDetails();
        } else {
            //獲取出庫流水
            getOutStockDetails();
        }
    }

    @Override
    public void setWarehousingNum(int num) {
        tvWarehouseInventoryNumber.setText(String.valueOf(num));
    }

    @OnClick({R2.id.tv_warehousing_record, R2.id.tv_outbound_record})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_warehousing_record) {
            //入庫流水
            vpWarehouseViewpager.setCurrentItem(WAREHOUSE_TYPE);
            //查詢入庫
            getWarehouseDetails();
        } else if (v.getId() == R.id.tv_outbound_record) {
            //出庫流水
            vpWarehouseViewpager.setCurrentItem(OUT_STOCK_TYPE);
            //查詢出庫
            getOutStockDetails();
        }
    }
}
