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

import android.app.Dialog;
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.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.PurchaseFoodBean;
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;

    private ShoppingCartAdapter shoppingCartAdapter;

    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) {
        initTopBar(topBar, "採購單");
        mPresenter.organizeShopCartData();
        cbOrderContentAllSelect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //全選
            if (buttonView.isPressed()) {
                if (shoppingCartAdapter != null) {
                    double totalAmount = 0;
                    int totalTypeFood = 0;
                    for (List<PurchaseFoodBean> datum : shoppingCartAdapter.getData()) {
                        for (PurchaseFoodBean purchaseFoodBean : datum) {
                            purchaseFoodBean.setChecked(isChecked);
                            if (isChecked) {
                                totalTypeFood++;
                                totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
                            }
                        }
                    }
                    shoppingCartAdapter.addChecked(shoppingCartAdapter.getData());
                    setTotalInfo(totalTypeFood, totalAmount);
                    shoppingCartAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @OnClick({R2.id.btn_order_content_order_template, R2.id.btn_order_content_add_food, R2.id.tv_order_content_complete})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_order_content_complete) {
            //完成
            List<PurchaseFoodBean> purchaseFoodBeans = shoppingCartAdapter.getPurchaseFoodListVosBeans();
            //去到訂單確認頁面
            boolean isHasChecked = false;
            for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
                if (purchaseFoodBean.isChecked()) {
                    isHasChecked = true;
                    break;
                }
            }
            if (isHasChecked) {
                //關閉選擇食材的頁面
                AppDialog.getInstance().showWaringDialog(mContext, "確認創建採購單？", (view, dialog) -> {
                    dialog.dismiss();
                    mPresenter.addPurchaseOrder();
                });
            } else {
                showMessage("請選擇食品");
            }
        } 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));
        }
    }

    @Override
    public void loadAdapter(List<List<PurchaseFoodBean>> supplierFoods) {
        shoppingCartAdapter = new ShoppingCartAdapter(mContext, supplierFoods);
        shoppingCartAdapter.setOnFoodDeleteListener((supplierIndex, foodListVosBean) -> {
            SupplyShoppingCart.getInstance().getCartFoods().remove(foodListVosBean);

            List<PurchaseFoodBean> purchaseFoodBeans = shoppingCartAdapter.getData().get(supplierIndex);
            purchaseFoodBeans.remove(foodListVosBean);

            if (purchaseFoodBeans.size() <= 0) {
                shoppingCartAdapter.removeAt(supplierIndex);
            }
        });
        rvOrderContent.setAdapter(shoppingCartAdapter);
        shoppingCartAdapter.setOnInfoChangeListener(() -> mPresenter.calculateTotalPrice(cbOrderContentAllSelect));
    }

    @Override
    public void setTotalInfo(int typeTotal, double 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));
    }
}
