package com.wd.workoffice.ui.activity.bat.order;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.OrderDetail;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.event.ModifyCarEvent;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.ui.activity.bat.store.StoreSaleCarActivity;
import com.wd.workoffice.ui.adapter.StoreProductAdapter;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.widget.AddAndReduceView;
import com.wd.workoffice.widget.BadgeCarProvider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.appcompat.app.AlertDialog;
import androidx.core.view.MenuItemCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 坩埚销售产品
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class AddCrucibleProductActivity extends WorkToolBarActivity {
    @BindView(R.id.rv_data)
    RecyclerView rvProduct;
    private Map<String, Object> param;
    private List<ProductBean.RecordsBean> clientList;
    private StoreProductAdapter clientAdapter;
    private List<ProductBean.RecordsBean> carList = new ArrayList<>();
    private String code;
    private BadgeCarProvider mActionProvider;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvProduct.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        code = getIntent().getStringExtra("code");
    }


    private void openDialog(ProductBean.RecordsBean data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_add_cart_double, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        AddAndReduceView num = view.findViewById(R.id.ar_num);
        num.setOnNumberChangedListener(new AddAndReduceView.OnNumberChangedListener() {
            @Override
            public void OnNumberChanged(String vs) {

            }
        });
        num.setMaxNum(data.getCanUseProductSum());
        EditText etPrice = view.findViewById(R.id.et_price);
        etPrice.setText(MathUtils.converData(data.getInternalPrice(),3));
        WorkUtils.addDecimalsListener(etPrice);
        for (ProductBean.RecordsBean recordsBean : carList) {
            if (data.getId() == recordsBean.getId()) {
                etPrice.setText(recordsBean.getCarPrice());
                num.setNumber(recordsBean.getCarNum());
            }
        }
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.equals(code, PermissionType.PROCESS_SUPPLY.getCode()) && TextUtils.isEmpty(etPrice.getText().toString())) {
                    toast("请填写销售单价");
                    return;
                }
                if (Double.valueOf(num.getNumber()) == 0d) {
                    toast("请填写数量");
                    return;
                }
                addCart(data, num.getNumber(), etPrice.getText().toString());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

    /**
     * 添加购物车
     *
     * @param chooseProduct 产品
     * @param number        数量
     * @param price         单价
     */
    private void addCart(ProductBean.RecordsBean chooseProduct, String number, String price) {
        boolean isHas = false;
        for (ProductBean.RecordsBean recordsBean : carList) {
            if (chooseProduct.getId() == recordsBean.getId()) {
                isHas = true;
                recordsBean.setCarNum(number);
                recordsBean.setCarPrice(price);
            }
        }
        if (!isHas) {
            chooseProduct.setCarNum(number);
            chooseProduct.setCarPrice(price);
            carList.add(chooseProduct);
        }
        toast("加入购物车成功");
        clientAdapter.notifyDataSetChanged();
        changeCarBadge();
    }

    @Override
    protected void initData() {
        clientList = new ArrayList<>();
        clientAdapter = new StoreProductAdapter(R.layout.item_store_product, clientList, 1);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        List<OrderDetail.OrderItemsBean> pro = JSON.parseArray(getIntent().getStringExtra("pro"), OrderDetail.OrderItemsBean.class);
        coverData(pro);
    }

    private void coverData(List<OrderDetail.OrderItemsBean> pro) {
        for (OrderDetail.OrderItemsBean orderItemsBean : pro) {
            ProductBean.RecordsBean data = new ProductBean.RecordsBean();
            data.setName(orderItemsBean.getProductName());
            data.setId(orderItemsBean.getProductId());
            data.setSimpleCode(orderItemsBean.getProductSimpleCode());
            data.setCanUseProductSum(orderItemsBean.getCanOutStoreProductSum());
            data.setInternalPrice(orderItemsBean.getInnerPrice());
            clientList.add(data);
        }
        clientAdapter.notifyDataSetChanged();
    }


    @Override
    protected void initEvent() {
//        clientAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//            @Override
//            public void onLoadMoreRequested() {
//                param.put("current", page);
//                getData();
//            }
//        }, rvProduct);
        clientAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                openDialog(clientList.get(position));
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_add_crucible_pro;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_store_cart, menu);
        MenuItem menuItem = menu.findItem(R.id.cart);
        mActionProvider = (BadgeCarProvider) MenuItemCompat.getActionProvider(menuItem);
        mActionProvider.setOnClickListener(new BadgeCarProvider.OnClickListener() {
            @Override
            public void onClick() {
                if (carList.size() == 0) {
                    toast("购物车没有产品");
                    return;
                }
                startActivity(AddCrucibleCarActivity.class,
                        "pro", JSON.toJSONString(carList),
                        "stockId", getIntent().getStringExtra("stockId"),
                        "procedureOrderId", getIntent().getStringExtra("procedureOrderId"),
                        "customerId", getIntent().getStringExtra("customerId"),
                        "code", getIntent().getStringExtra("code"));
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.cart:
                if (carList.size() == 0) {
                    toast("购物车没有产品");
                    return super.onOptionsItemSelected(item);
                }
                startActivity(AddCrucibleCarActivity.class,
                        "pro", JSON.toJSONString(carList),
                        "stockId", getIntent().getStringExtra("stockId"),
                        "procedureOrderId", getIntent().getStringExtra("procedureOrderId"),
                        "customerId", getIntent().getStringExtra("customerId"),
                        "code", getIntent().getStringExtra("code"));
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ModifyCarEvent event) {
        String pro = event.getPro();
        carList.clear();
        carList.addAll(JSON.parseArray(pro, ProductBean.RecordsBean.class));
        changeCarBadge();
    }

    private void changeCarBadge() {
        if (carList.size() > 0) {
            mActionProvider.setBadgeVisibility(View.VISIBLE);
        } else {
            mActionProvider.setBadgeVisibility(View.GONE);
        }
    }
}
