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

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerShoppingCatComponent;
import com.gingersoft.supply_chain.mvp.bean.ConfirmOrderBean;
import com.gingersoft.supply_chain.mvp.bean.ShoppingCartBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.ShoppingCatContract;
import com.gingersoft.supply_chain.mvp.presenter.ShoppingCatPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.ShoppingCartAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment.ADD_ORDER;


/**
 * ================================================
 * Description: 購物車
 * 本次下單所有食品展示頁
 */
public class ShoppingCatFragment extends BaseSupplyChainFragment<ShoppingCatPresenter> implements ShoppingCatContract.View, View.OnClickListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar topBar;
    @BindView(R2.id.rv_order_content)
    RecyclerView rvOrderContent;
    @BindView(R2.id.cb_order_content_all_select)
    CheckBox cbOrderContentAllSelect;
    @BindView(R2.id.tv_order_content_food_type_total)
    TextView tvOrderContentFoodTypeTotal;
    @BindView(R2.id.tv_order_content_total_amount)
    TextView tvOrderContentTotalAmount;
    @BindView(R2.id.ed_order_content_remark)
    EditText edOrderContentRemark;
    @BindView(R2.id.tv_order_content_complete)
    TextView tvConfirm;

    private ShoppingCartAdapter shoppingCartAdapter;
    /**
     * 食材種類
     */
    private int totalSpecies = 0;
    /**
     * 總金額
     */
    private double totalAmount = 0;
    /**
     * 是否可以創建訂單按鈕的背景
     */
    private Drawable canClick;
    private Drawable notCanClick;


    public static ShoppingCatFragment newInstance() {
        ShoppingCatFragment fragment = new ShoppingCatFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerShoppingCatComponent//如找不到该类,请编译一下项目
                .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_order_content, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        canClick = ContextCompat.getDrawable(requireContext(), R.drawable.shape_app_btn);
        notCanClick = ContextCompat.getDrawable(requireContext(), R.drawable.shape_btn_unclick);
        initTopBar(topBar, "採購單");
        mPresenter.organizeShopCartData();

        cbOrderContentAllSelect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //全選
            if (buttonView.isPressed()) {
                if (shoppingCartAdapter != null) {
                    mPresenter.calculateTotalPrice(isChecked, shoppingCartAdapter.getData());
                }
            }
        });
    }

    @OnClick({R2.id.btn_order_content_order_template, R2.id.btn_order_content_add_food, R2.id.tv_order_content_complete, R2.id.tv_order_content_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_order_content_complete) {
            //完成，篩選出選擇的食品
            if (mPresenter.filterData(shoppingCartAdapter.getData())) {
                AppDialog.getInstance().showWaringDialog(requireContext(), "確認創建訂單？", (view, dialog) -> {
                    mPresenter.createOrder(shoppingCartAdapter.getData());
                });
            }
        } else if (viewId == R.id.btn_order_content_order_template) {
            //訂單模板

        } else if (viewId == R.id.btn_order_content_add_food) {
            //添加食材
            startWithPop(FoodIngredientsFragment.newInstance(ADD_ORDER));
        } else if (viewId == R.id.tv_order_content_cancel) {
            //取消
            killMyself();
        }
    }

    @Override
    public void loadAdapter(List<ShoppingCartBean> shoppingCartBeans) {
        shoppingCartAdapter = new ShoppingCartAdapter(mContext, shoppingCartBeans);
        shoppingCartAdapter.setOnFoodDeleteListener((supplierIndex, foodListVosBean) -> {
            //從購物車元數據移除掉這個食材
            SupplyShoppingCart.getInstance().getCartFoods().remove(foodListVosBean);
            List<ShoppingCartBean> shoppingCartAdapterData = shoppingCartAdapter.getData();
            //購物車adapter移除這個供應商
            if (shoppingCartAdapterData.get(supplierIndex).getFoodList().size() <= 0) {
                shoppingCartAdapter.removeAt(supplierIndex);
                if (foodListVosBean.isChecked()) {
                    totalSpecies = MoneyUtil.sub(totalSpecies, 1);
                    totalAmount = MoneyUtil.sub(totalAmount, MoneyUtil.priceCalculation(foodListVosBean.getUnitPrice(), foodListVosBean.getFoodQuantity()));
                    setTotalInfo(totalSpecies, totalAmount);
                }
            }
            setAllSelect(shoppingCartAdapterData);
            mPresenter.verificationMixAmount(shoppingCartAdapter.getData());
        });
        rvOrderContent.setAdapter(shoppingCartAdapter);
        setAllSelect(shoppingCartBeans);
        //當供應商裡面選中食品數量或價格有變化時回調，計算總價
        shoppingCartAdapter.setOnInfoChangeListener((double changeAmount, int changeSpecies) -> {
            totalAmount = MoneyUtil.sum(totalAmount, changeAmount);
            totalSpecies += changeSpecies;
            setTotalInfo(totalSpecies, totalAmount);
            //這裡應該可以再加一個回調接口，用來專門處理食材的選中狀態切換
            setAllSelect(shoppingCartAdapter.getData());
            mPresenter.verificationMixAmount(shoppingCartAdapter.getData());
        });
    }

    /**
     * 設置是否全選
     */
    public void setAllSelect(List<ShoppingCartBean> shoppingCartAdapterData) {
        boolean checked = true;
        for (ShoppingCartBean shoppingCartAdapterDatum : shoppingCartAdapterData) {
            if (!shoppingCartAdapterDatum.isAllSelect()) {
                checked = false;
                break;
            }
        }
        cbOrderContentAllSelect.setChecked(checked);
    }

    @Override
    public void setTotalInfo(int typeTotal, double totalPrice) {
        totalSpecies = typeTotal;
        totalAmount = totalPrice;
        tvOrderContentFoodTypeTotal.setText(String.valueOf(typeTotal));
        tvOrderContentTotalAmount.setText("$" + totalPrice);
    }

    @Override
    public void addOrderSuccess(List<ConfirmOrderBean.PurchaseOrder> purchaseOrders) {
        ShoppingCatFragment childFragment = findChildFragment(ShoppingCatFragment.class);
        if (childFragment != null) {
            childFragment.killMyself();
        }
        startWithPop(SendMsgFragment.newInstance(purchaseOrders));
    }

    @Override
    public void notifyAdapter(int position) {
        if (position == -1) {
            shoppingCartAdapter.notifyDataSetChanged();
        } else {
            shoppingCartAdapter.notifyItemChanged(position);
            rvOrderContent.scrollToPosition(position);
        }
    }

    @Override
    public void setCreateBtnState(boolean checkable) {
        tvConfirm.setBackground(checkable ? canClick : notCanClick);
        tvConfirm.setClickable(checkable);
    }
}
