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

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
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.DaggerWarehouseDetailsComponent;
import com.gingersoft.supply_chain.mvp.bean.ConsumeReasonBean;
import com.gingersoft.supply_chain.mvp.bean.WareHouseListBean;
import com.gingersoft.supply_chain.mvp.bean.WarehouseDetailsBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.gingersoft.supply_chain.mvp.contract.WarehouseDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.WarehouseDetailsPresenter;
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.InventoryConsumptionPopup;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.core.LoadSir;
import com.lxj.xpopup.XPopup;
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.OnRefreshListener;

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

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Description: 入庫詳情
 */
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;

    private WareHousingDetailsAdapter wareHousingDetailsAdapter;
    private PurchasePageAdapter adapter;
    private int foodId;
    private String foodNo;
    private String foodName;
    private String foodUnit;
    private int wareHousingNum;
    public final static String FOOD_NAME_KEY = "foodNameKey";
    public final static String FOOD_ID_KEY = "foodIdKey";
    public final static String FOOD_NO_KEY = "foodNoKey";
    public final static String FOOD_UNIT_KEY = "foodUnitKey";
    public final static String FOOD_NUM_KEY = "foodNumKey";
    public final static String FOOD_UNIT_PRICE_KEY = "foodUnitPriceKey";
    public final static String FOOD_TOTAL_AMOUNT_KEY = "foodTotalAmountKey";
    public final static String FOOD_IMAGE_KEY = "foodImageKey";
    /**
     * 入庫
     */
    public final static int WAREHOUSE_TYPE = 0;
    /**
     * 出庫
     */
    public final static int OUT_STOCK_TYPE = 1;

    public static WarehouseDetailsFragment newInstance(WareHouseListBean.WareHousingDataBean.PurchaseWarehousingOrderDetailsVOSBean purchaseWarehousingOrderDetailsVosBean) {
        WarehouseDetailsFragment fragment = new WarehouseDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putString(FOOD_NAME_KEY, purchaseWarehousingOrderDetailsVosBean.getName());
        bundle.putInt(FOOD_ID_KEY, purchaseWarehousingOrderDetailsVosBean.getId());
        bundle.putString(FOOD_UNIT_KEY, purchaseWarehousingOrderDetailsVosBean.getUnitName());
        bundle.putInt(FOOD_NUM_KEY, purchaseWarehousingOrderDetailsVosBean.getFoodNum());
        bundle.putDouble(FOOD_UNIT_PRICE_KEY, purchaseWarehousingOrderDetailsVosBean.getFoodPrice());
        bundle.putDouble(FOOD_TOTAL_AMOUNT_KEY, purchaseWarehousingOrderDetailsVosBean.getFoodAmount());
        bundle.putString(FOOD_NO_KEY, purchaseWarehousingOrderDetailsVosBean.getFoodNo());
        bundle.putString(FOOD_IMAGE_KEY, purchaseWarehousingOrderDetailsVosBean.getImages());
        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);
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> getPageInfo());
        if (arguments != null) {
            foodName = arguments.getString(FOOD_NAME_KEY);
            initTopBar(supplyTopBar, foodName);
            foodId = arguments.getInt(FOOD_ID_KEY);
            foodNo = arguments.getString(FOOD_NO_KEY);
            foodUnit = arguments.getString(FOOD_UNIT_KEY);
            wareHousingNum = arguments.getInt(FOOD_NUM_KEY);
            if (TextUtil.isNotEmptyOrNullOrUndefined(foodUnit)) {
                tvUnit.setText(foodUnit);
            }
            String foodImageUrl = arguments.getString(FOOD_IMAGE_KEY);
            if (TextUtil.isNotEmptyOrNullOrUndefined(foodImageUrl)) {
                GlideUtils.display(requireContext(), ivFoodImg, foodImageUrl);
            } else {
                ivFoodImg.setImageResource(R.drawable.img_small_default);
            }
            double unitPrice = arguments.getDouble(FOOD_UNIT_PRICE_KEY);
            double totalAmount = arguments.getDouble(FOOD_TOTAL_AMOUNT_KEY);
            tvWarehouseInventoryNumber.setText(String.valueOf(wareHousingNum));
            tvWarehouseUnitPrice.setText(String.format(getString(R.string.str_latest_unit_price_colon), unitPrice));
            tvWarehouseTotalAmount.setText(String.format(getString(R.string.str_total_amount_colon), totalAmount));
            tvWarehouseSpecifications.setText(foodUnit);
            getWarehouseDetails();
            if (wareHousingNum > 0) {
                //獲取庫存消耗的原因列表
                mPresenter.getWarehouseInventoryReason();
            }
            initViewPager();
        }
    }

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

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

    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(requireContext(), 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 -> {
            //庫存消耗
            InventoryConsumptionPopup inventoryConsumptionPopup = new InventoryConsumptionPopup(requireContext(), consumeReasonBeans, wareHousingNum);
            inventoryConsumptionPopup.setOnConfirmClickListener((consumptionNum, reasonIndex, remarks) -> {
                inventoryConsumptionPopup.dismiss();
                mPresenter.consumeWareHousing(foodNo, consumptionNum, consumeReasonBeans.get(reasonIndex).getId(), remarks);
                setFragmentResult(RESULT_OK, null);
            });
            inventoryConsumptionPopup.setTitleContent(getString(R.string.str_consumption_inventory), getString(R.string.str_remark_colon), getString(R.string.str_manual_input));
            new XPopup.Builder(requireContext())
                    .asCustom(inventoryConsumptionPopup).show();
        });
    }

    @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();
        }
    }
}
