package com.gingersoft.supply_chain.mvp.ui.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.MoneyInputFilter;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author 宇航.
 * User: admin
 * Date: 2020/12/24
 * Time: 9:07
 * Use:
 */
public class OrderDetailsFoodAdapter extends BaseQuickAdapter<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean, BaseViewHolder> {

    private Context context;
    private OnValueChangeListener onValueChangeListener;

    public void setOnValueChangeListener(OnValueChangeListener onValueChangeListener) {
        this.onValueChangeListener = onValueChangeListener;
    }

    public OrderDetailsFoodAdapter(Context context, @Nullable List<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean> data) {
        super(R.layout.item_order_details_food, data);
        this.context = context;
    }

    @Override
    protected void convert(@NotNull BaseViewHolder viewHolder, PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean item) {
        viewHolder.setText(R.id.tv_order_no, item.getOrderNo() + "");
        viewHolder.setText(R.id.tv_order_details_item_food_name, item.getName());
        viewHolder.setText(R.id.tv_order_details_item_purchasing_unit, item.getUnit_content());
        viewHolder.setText(R.id.tv_order_details_item_purchasing_unit_price, "$" + item.getFoodPrice());
        viewHolder.setText(R.id.tv_order_details_item_num, String.valueOf(item.getFoodQuantity()));
        //食品的總價
        viewHolder.setText(R.id.tv_order_details_item_purchasing_total_amount, "$" + item.getTotalAmount());
        //拿到單價
//        double unitPrice = Integer.parseInt(item.getWareHouseBeans().get(0).getValue());
        //拿到數量
//        double foodQuantity = Integer.parseInt(item.getWareHouseBeans().get(1).getValue());
        //設置入庫總價,總價是由用戶輸入的單價*基本單位數
        viewHolder.setText(R.id.tv_order_details_item_warehouse_total_amount, String.format(context.getString(R.string.amount_string_s), MoneyUtil.formatDouble(item.getWarehousingAmount())));
        RecyclerView rvWarehouseUnit = viewHolder.getView(R.id.rv_warehouse_unit);
        if (item.getFoodUnits() != null) {
            rvWarehouseUnit.setVisibility(View.VISIBLE);
            rvWarehouseUnit.setLayoutManager(new GridLayoutManager(context, 3));
            WareHouseUnitAdapter wareHouseUnitAdapter = new WareHouseUnitAdapter(item.getFoodUnits(), viewHolder.getAdapterPosition(), (position, value) -> {
                PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean purchaseOrderDetailsInfoVosBean = getData().get(viewHolder.getAdapterPosition());
                //獲取入庫單位集合，用第0位（單價）乘以第一位（主單位數量），得到現在的入庫價格
                List<DeputyUnitBean> deputyUnitBeans = purchaseOrderDetailsInfoVosBean.getFoodUnits();
                if (deputyUnitBeans != null && deputyUnitBeans.size() > 1) {
                    double currentWareHouseAmount = MoneyUtil.priceCalculation(deputyUnitBeans.get(0).getDeputyValue(), deputyUnitBeans.get(1).getDeputyValue());
                    //現在的價格減去之前的價格，得到增加了多少
                    double changeAmount = MoneyUtil.sub(currentWareHouseAmount, purchaseOrderDetailsInfoVosBean.getWarehousingAmount());
                    if (purchaseOrderDetailsInfoVosBean.isChecked()) {
                        //调用接口，修改外部總金額
                        onValueChangeListener.onValueChange(position, changeAmount);
                    }
                    //保存最新的金額數據
                    purchaseOrderDetailsInfoVosBean.setWarehousingAmount(currentWareHouseAmount);
                    viewHolder.setText(R.id.tv_order_details_item_warehouse_total_amount, currentWareHouseAmount + "");
                }
            });
            rvWarehouseUnit.setAdapter(wareHouseUnitAdapter);
        } else {
            rvWarehouseUnit.setVisibility(View.GONE);
        }

        viewHolder.setBackgroundResource(R.id.iv_order_details_item_food_select, item.isChecked() ? R.drawable.ic_checkbox_checked : R.drawable.ic_checkbox_uncheck);
    }

    private static class WareHouseUnitAdapter extends BaseQuickAdapter<DeputyUnitBean, BaseViewHolder> {
        private int parentPosition;
        private OnValueChangeListener onValueChangeListener;
        private Disposable mDisposable;

        public WareHouseUnitAdapter(List<DeputyUnitBean> wareHouseBeans, int parentPosition, OnValueChangeListener onValueChangeListener) {
            super(R.layout.item_receiving_unit, wareHouseBeans);
            this.parentPosition = parentPosition;
            this.onValueChangeListener = onValueChangeListener;
        }

        @Override
        protected void convert(@NotNull BaseViewHolder viewHolder, DeputyUnitBean wareHouseBean) {
            viewHolder.setText(R.id.tv_receiving_unit_title, wareHouseBean.getDeputyUnit());
            EditText edWareHouseValue = viewHolder.getView(R.id.ed_receiving_unit_value);
            edWareHouseValue.setFilters(new InputFilter[]{new MoneyInputFilter()});
            edWareHouseValue.setText(MoneyUtil.formatDouble(wareHouseBean.getDeputyValue()));
            TextWatcher textWatcher = 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 editable) {
                    String s = editable + "";
                    if (TextUtil.isEmptyOrNullOrUndefined(s)) {
                        s = "0";
                    }
                    DeputyUnitBean item = getData().get(viewHolder.getLayoutPosition());
                    item.setDeputyValue(Double.parseDouble(s + ""));
                    if (viewHolder.getAdapterPosition() == 0 || viewHolder.getAdapterPosition() == 1) {
                        //如果修改的是單價，或者是主單位數量，就要刷新總價
                        if (mDisposable != null) {
                            mDisposable.dispose();
                        }
                        String finalS = s;
                        mDisposable = RxJavaUtils.delay(1, l -> onValueChangeListener.onValueChange(parentPosition, Double.parseDouble(finalS)));
                    }
                }
            };
            edWareHouseValue.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus) {
                    edWareHouseValue.addTextChangedListener(textWatcher);
                } else {
                    edWareHouseValue.removeTextChangedListener(textWatcher);
                }
            });
        }
    }

    public interface OnValueChangeListener {
        /**
         * 入庫價格發生變化回調接口
         *
         * @param position 入庫食品的下標
         * @param value    增加了多少價格，如果是減少，則改為負的
         */
        void onValueChange(int position, double value);
    }
}
