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

import android.content.Context;
import android.text.Editable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;

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.threadPool.ThreadPoolManager;
import com.gingersoft.gsa.cloud.ui.view.imageview.mask.PorterShapeImageView;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
import com.gingersoft.supply_chain.mvp.ui.adapter.BuyIngredientsAdapter;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.util.KeyboardUtils;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView;

import org.w3c.dom.Text;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/4/15
 * Time: 10:07
 * Use:
 */
public class GoodsDetailsPopup extends CenterPopupView {

    @BindView(R2.id.iv_goods_details)
    PorterShapeImageView ivGoodsDetails;
    @BindView(R2.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R2.id.tv_supplier_name)
    TextView tvSupplierName;
    @BindView(R2.id.tv_goods_no)
    TextView tvGoodsNo;
    @BindView(R2.id.tv_goods_price)
    QMUISpanTouchFixTextView tvGoodsPrice;
    @BindView(R2.id.tv_goods_specification)
    TextView tvGoodsSpecification;
    @BindView(R2.id.tv_goods_stock)
    TextView tvGoodsStock;

    @BindView(R2.id.btn_food_operation_sub)
    QMUIButton btnFoodOperationSub;
    @BindView(R2.id.ed_food_ingredient_number)
    AppCompatEditText edFoodIngredientNumber;
    @BindView(R2.id.btn_food_operation_add)
    QMUIButton btnFoodOperationAdd;
    @BindView(R2.id.layout_operation_food_num)
    LinearLayout layoutOperationFoodNum;
    @BindView(R2.id.iv_popup_close)
    ImageView ivPopupClose;
    private PurchaseFoodBean purchaseFoodBean;
    private BuyIngredientsAdapter.OnFoodNumberChangeListener onFoodNumberChangeListener;
    /**
     * 是否可以編輯數量
     */
    private boolean isEditNumber = true;

    public GoodsDetailsPopup(@NonNull Context context, PurchaseFoodBean purchaseFoodBean) {
        super(context);
        this.purchaseFoodBean = purchaseFoodBean;
    }


    @Override
    protected int getImplLayoutId() {
        return R.layout.layout_goods_details_popup;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        ButterKnife.bind(this);
        popupInfo.autoOpenSoftInput = false;
        if (purchaseFoodBean.getImages() == null) {
            ivGoodsDetails.setImageResource(R.drawable.img_small_default);
        } else {
            GlideUtils.display(getContext(), ivGoodsDetails, purchaseFoodBean.getImages(), R.drawable.img_small_default);
        }
        tvGoodsName.setText(purchaseFoodBean.getName());
        tvSupplierName.setText(purchaseFoodBean.getSupplierName());
        tvGoodsNo.setText(purchaseFoodBean.getFoodNo());

        String price = String.format(getContext().getString(R.string.str_unit_price_colon_s), MoneyUtil.formatDouble(purchaseFoodBean.getUnitPrice()));
        tvGoodsPrice.setText(TextUtil.getBoldSpannableString(price, ContextCompat.getColor(getContext(), R.color.required_color), 3, price.length()));

        if (TextUtil.isNotEmptyOrNullOrUndefined(purchaseFoodBean.getPackingDescription())) {
            tvGoodsSpecification.setText(purchaseFoodBean.getPackingDescription());
        } else {
            tvGoodsSpecification.setText(purchaseFoodBean.getBasicUnitName());
        }
        ivPopupClose.setOnClickListener(this::onClick);

        if (!isEditNumber) {
            layoutOperationFoodNum.setVisibility(GONE);
            tvGoodsStock.setVisibility(GONE);
            return;
        }
        edFoodIngredientNumber.setText(purchaseFoodBean.getFoodQuantity() + "");
        btnFoodOperationSub.setOnClickListener(v -> {
            //减
            if (purchaseFoodBean.getFoodQuantity() > 0) {
                foodNumberChange(-1);
            }
        });
        btnFoodOperationSub.setOnTouchListener(onBtnTouchListener);
        btnFoodOperationSub.setOnLongClickListener(v -> {
            //長按減號
            setLongClick(false);
            return true;
        });

        btnFoodOperationAdd.setOnTouchListener(onBtnTouchListener);
        btnFoodOperationAdd.setOnLongClickListener(v -> {
            //長按加號
            setLongClick(true);
            return true;
        });

        btnFoodOperationAdd.setOnClickListener(v -> {
            //加
            if (purchaseFoodBean.getFoodQuantity() < PurchaseConstant.PURCHASE_FOOD_MAX) {
                foodNumberChange(1);
            }
        });
        edFoodIngredientNumber.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                //失去焦點時調用
                Editable text = edFoodIngredientNumber.getText();
                if (TextUtil.isNotEmptyOrNullOrUndefined(text)) {
                    int foodQuantity = Integer.parseInt(text.toString());
                    foodNumberChange(foodQuantity - hasFocusNum);
                } else {
                    foodNumberChange(-purchaseFoodBean.getFoodQuantity());
                }
            } else {
                hasFocusNum = purchaseFoodBean.getFoodQuantity();
            }
        });
    }

    private int hasFocusNum;

    public GoodsDetailsPopup setEditNumber(boolean editNumber) {
        isEditNumber = editNumber;
        return this;
    }

    /**
     * + - 按鈕觸摸事件
     */
    private View.OnTouchListener onBtnTouchListener = (v, event) -> {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            longClick = true;
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            longClick = false;
        }
        return false;
    };

    private int delayTime = PurchaseConstant.LONG_CLICK_INIT_TIME;
    private boolean longClick = false;

    /**
     * 按鈕長按事件
     *
     * @param addOrSub 是+ or -
     */
    public void setLongClick(boolean addOrSub) {
        //開啟線程
        ThreadPoolManager.getInstence().putExecutableTasks(() -> {
            int number = purchaseFoodBean.getFoodQuantity();
            delayTime = PurchaseConstant.LONG_CLICK_INIT_TIME;
            if (addOrSub) {
                //+
                while (longClick) {
                    if (number < PurchaseConstant.PURCHASE_FOOD_MAX) {
                        try {
                            Thread.sleep(delayTime);
                            number++;
                            if (delayTime > PurchaseConstant.LONG_CLICK_DECREASE_TIME) {
                                delayTime -= PurchaseConstant.LONG_CLICK_DECREASE_TIME;
                            }
                            edFoodIngredientNumber.post(() -> foodNumberChange(1));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        longClick = false;
                    }
                }
            } else {
                //-
                while (longClick) {
                    if (number > 0) {
                        try {
                            Thread.sleep(delayTime);
                            number--;
                            if (delayTime > PurchaseConstant.LONG_CLICK_DECREASE_TIME) {
                                delayTime -= PurchaseConstant.LONG_CLICK_DECREASE_TIME;
                            }
                            edFoodIngredientNumber.post(() -> foodNumberChange(-1));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        longClick = false;
                    }
                }
            }
        });
    }

    private void foodNumberChange(int changeNum) {
        if (changeNum == 0) {
            return;
        }
        purchaseFoodBean.setFoodQuantity(purchaseFoodBean.getFoodQuantity() + changeNum);
        edFoodIngredientNumber.setText(String.valueOf(purchaseFoodBean.getFoodQuantity()));
        if (onFoodNumberChangeListener != null) {
            onFoodNumberChangeListener.onChange(purchaseFoodBean, 0, 0, purchaseFoodBean.getFoodQuantity() - changeNum, purchaseFoodBean.getFoodQuantity());
        }
    }


    public GoodsDetailsPopup setOnFoodNumberChangeListener(BuyIngredientsAdapter.OnFoodNumberChangeListener onFoodNumberChangeListener) {
        this.onFoodNumberChangeListener = onFoodNumberChangeListener;
        return this;
    }

    private void onClick(View v) {
        dismiss();
    }
}
