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.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
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.InputFilterUtils;
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;
    private String formatAmount;
    private InputFilter[] inputFilters;

    private int canEditColor;
    private int notEditableColor;

    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);
        addChildClickViewIds(R.id.layout_order_details_unit);
        this.context = context;
        formatAmount = context.getString(R.string.amount_string);
        inputFilters = new InputFilter[]{new MoneyInputFilter()};
        canEditColor = ContextCompat.getColor(context, R.color.color_3c);
        notEditableColor = ContextCompat.getColor(context, R.color.color_aaa);

    }

    @Override
    protected void convert(@NotNull BaseViewHolder viewHolder, PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean item) {
        //食品編號
//        viewHolder.setText(R.id.tv_order_no, item.getOrderNo() + "");
        //食品名稱
        viewHolder.setText(R.id.iv_order_details_item_food_select, item.getName());
        //食品單位
        viewHolder.setText(R.id.tv_order_details_item_purchasing_unit, item.getUnit_content());
        //已入庫數量
        viewHolder.setText(R.id.tv_order_details_item_warehouse_warehousing_num, String.valueOf(item.getWarehousingQuantity()));
        //食品的收貨狀態
        TextView tvFoodState = viewHolder.getView(R.id.tv_order_details_state);
        tvFoodState.setText(PurchaseOrderDetailsBean.getStringByOrderState(item.getStatus()));
        tvFoodState.setTextColor(ContextCompat.getColor(context, PurchaseOrderDetailsBean.getColorByOrderState(item.getStatus())));
        //單位的操作
        RelativeLayout layoutUnit = viewHolder.getView(R.id.layout_order_details_unit);
        TextView tvUnit = viewHolder.getView(R.id.tv_order_details_show_unit);
        ImageView ivSwitchUnit = viewHolder.getView(R.id.iv_switch_unit);
        if (item.getStatus() == PurchaseOrderDetailsBean.WAIT_RECEIVED) {
            //待收貨
            if (item.getFoodUnits() != null && item.getFoodUnits().size() > 1) {
                //有其他單位
                layoutUnit.setEnabled(true);
                tvUnit.setTextColor(canEditColor);
                ivSwitchUnit.setVisibility(View.VISIBLE);
            } else {
                //沒有其他單位
                layoutUnit.setEnabled(false);
                tvUnit.setTextColor(notEditableColor);
                ivSwitchUnit.setVisibility(View.GONE);
            }
        } else {
            //部分收貨或已收貨其他狀態，收貨單位不可切換
            layoutUnit.setEnabled(false);
            tvUnit.setTextColor(notEditableColor);
            ivSwitchUnit.setVisibility(View.GONE);
        }
        //訂單食品數量
        viewHolder.setText(R.id.tv_order_details_item_warehouse_num, String.valueOf(item.getFoodQuantity()));
        //食品的總價
        viewHolder.setText(R.id.tv_order_details_item_warehouse_total_amount, String.format(formatAmount, item.getTotalAmount()));
        //實付
        viewHolder.setText(R.id.tv_order_details_item_warehouse_actual_amount, String.format(formatAmount, item.getTotalAmount()));
        if (item.getShowUnit() != null) {
            viewHolder.setText(R.id.tv_order_details_show_unit, item.getShowUnit().getDeputyUnit());
        } else {
            viewHolder.setText(R.id.tv_order_details_show_unit, "");
        }
        //食品數量
        EditText edFoodNum = viewHolder.getView(R.id.ed_food_num);
        edFoodNum.setFilters(inputFilters);
        edFoodNum.setText(String.valueOf(item.getShowUnit().getDeputyValue()));
        TextWatcher watcher = 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) {
                DeputyUnitBean showUnit = getItem(viewHolder.getAdapterPosition()).getShowUnit();
                if (TextUtil.isNotEmptyOrNullOrUndefined(s + "")) {
                    showUnit.setDeputyValue(Double.parseDouble(s.toString()));
                } else {
                    showUnit.setDeputyValue(0);
                }
            }
        };
        edFoodNum.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                edFoodNum.addTextChangedListener(watcher);
            } else {
                edFoodNum.removeTextChangedListener(watcher);
            }
        });
        //食品單價
        EditText edUnitPrice = viewHolder.getView(R.id.ed_food_unit_price);
        edUnitPrice.setFilters(inputFilters);
        edUnitPrice.setText(String.valueOf(item.getShowUnit().getUnitPrice()));
        TextWatcher unitPriceWatcher = 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) {
                DeputyUnitBean showUnit = getItem(viewHolder.getAdapterPosition()).getShowUnit();
                if (TextUtil.isNotEmptyOrNullOrUndefined(s + "")) {
                    showUnit.setUnitPrice(Double.parseDouble(s.toString()));
                } else {
                    showUnit.setUnitPrice(0);
                }
            }
        };
        edUnitPrice.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                edUnitPrice.addTextChangedListener(unitPriceWatcher);
            } else {
                edUnitPrice.removeTextChangedListener(unitPriceWatcher);
            }
        });

        //設置入庫總價,總價是由用戶輸入的單價*基本單位數
        viewHolder.setText(R.id.tv_order_details_item_warehouse_total_amount, String.format(context.getString(R.string.amount_string_s), MoneyUtil.formatDouble(item.getWarehousingAmount())));
        CheckBox checkBox = viewHolder.getView(R.id.iv_order_details_item_food_select);
        checkBox.setChecked(item.isChecked());
    }

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