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.DecimalDigitsInputFilter;
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.Map;
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 onAmountChangeListener onAmountChangeListener;
    private String formatAmount;
    private InputFilter[] inputFilters;

    private int canEditColor;
    private int notEditableColor;

    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_not_in_storage_num, String.valueOf(Math.max(MoneyUtil.sub(item.getFoodQuantity(), item.getWarehousingQuantity()), 0)));
        //食品的收貨狀態
        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()));
        //食品數量
        EditText edFoodNum = viewHolder.getView(R.id.ed_food_num);
        edFoodNum.setFilters(inputFilters);
        //已入庫數量
        viewHolder.setText(R.id.tv_order_details_item_warehouse_warehousing_num, MoneyUtil.formatDouble(item.getWarehousingQuantity()));
        viewHolder.setText(R.id.tv_order_details_show_unit, item.getShowUnit().getDeputyUnit());
        //數量編輯框，已完成顯示已入庫數量，未完成顯示待入庫數量，已在之前處理過
        edFoodNum.setText(MoneyUtil.formatDouble(item.getShowUnit().getDeputyValue()));
        //實付
        setActualAmount(viewHolder, item.getShowUnit());
        //設置入庫總價,總價是由用戶輸入的單價*基本單位數
        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());
        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();
                //修改之前的數量
                double beforeNum = showUnit.getDeputyValue();
                if (TextUtil.isNotEmptyOrNullOrUndefined(s + "")) {
                    showUnit.setDeputyValue(Double.parseDouble(s.toString()));
                }
//                else {
//                    showUnit.setDeputyValue(0);
//                }
                //實付金額發生改變，需要通知頁面刷新總金額
                if (checkBox.isChecked()) {
                    //現在的數量減去之前的數量，再乘以單價，得到增加或減少了多少總價
                    onAmountChangeListener.onAmountChange(viewHolder.getAdapterPosition(), MoneyUtil.priceCalculation(MoneyUtil.sub(showUnit.getDeputyValue(), beforeNum), showUnit.getUnitPrice()));
                }
                //數量發生改變，需要修改實付金額
                setActualAmount(viewHolder, item.getShowUnit());
            }
        };
        edFoodNum.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                edFoodNum.addTextChangedListener(watcher);
                if("0".equals(edFoodNum.getText().toString())){
                    edFoodNum.setText("");
                }
            } else {
                if (TextUtil.isEmptyOrNullOrUndefined(edFoodNum)) {
                    DeputyUnitBean showUnit = getItem(viewHolder.getAdapterPosition()).getShowUnit();
                    showUnit.setDeputyValue(0);
                    edFoodNum.setText("0");
                }
                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();
                //之前的單價
                double beforePrice = showUnit.getUnitPrice();
                if (TextUtil.isNotEmptyOrNullOrUndefined(s + "")) {
                    showUnit.setUnitPrice(Double.parseDouble(s.toString()));
                }
//                else {
//                    showUnit.setUnitPrice(0);
//                }
                //當前食品已選中，實付金額發生改變，需要通知頁面刷新總金額
                if (checkBox.isChecked()) {
                    //現在的單價減去之前的單價，再乘以數量，得到增加或減少的金額
                    onAmountChangeListener.onAmountChange(viewHolder.getAdapterPosition(), MoneyUtil.priceCalculation(MoneyUtil.sub(showUnit.getUnitPrice(), beforePrice), showUnit.getDeputyValue()));
                }
                //單價發生改變，需要修改實付金額
                setActualAmount(viewHolder, item.getShowUnit());
            }
        };
        edUnitPrice.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                if (TextUtil.isNotEmptyOrNullOrUndefined(edUnitPrice)) {
                    double price = Double.parseDouble(edUnitPrice.getText().toString());
                    if(price == 0){
                        edUnitPrice.setText("");
                    }
                }
                edUnitPrice.addTextChangedListener(unitPriceWatcher);
            } else {
                if (TextUtil.isEmptyOrNullOrUndefined(edUnitPrice)) {
                    DeputyUnitBean showUnit = getItem(viewHolder.getAdapterPosition()).getShowUnit();
                    showUnit.setUnitPrice(0);
                    edUnitPrice.setText("0");
                }
                edUnitPrice.removeTextChangedListener(unitPriceWatcher);
            }
        });
    }

    /**
     * 修改實付金額
     */
    private void setActualAmount(BaseViewHolder viewHolder, DeputyUnitBean showUnit) {
        viewHolder.setText(R.id.tv_order_details_item_warehouse_actual_amount, String.format(formatAmount, MoneyUtil.priceCalculation(showUnit.getDeputyValue(), showUnit.getUnitPrice())));
    }

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

    public void setOnAmountChangeListener(OrderDetailsFoodAdapter.onAmountChangeListener onAmountChangeListener) {
        this.onAmountChangeListener = onAmountChangeListener;
    }
}
