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

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
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.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.TradingBean;
import com.wd.workoffice.bean.event.ModifyCarEvent;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.TradingProDetailAdapter;
import com.wd.workoffice.ui.adapter.TradingProductAdapter;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.widget.AddAndReduceDoubleView;
import com.wd.workoffice.widget.AddAndReduceView;

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

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

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import io.reactivex.disposables.Disposable;

/**
 * 商店-销售-产品
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class StoreTradingProductActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    @BindView(R.id.tv_receive_dep)
    TextView tvReceiveDep;
    @BindView(R.id.ll_choose)
    LinearLayout llChoose;
    private Map<String, Object> param;
    private List<TradingBean.RecordsBean> clientList;
    private TradingProductAdapter clientAdapter;
    private int page = 1;
    private List<TradingBean.RecordsBean> carList = new ArrayList<>();
    private String code;
    Map<String, Object> carMap = new HashMap<>();

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvProduct.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        code = getIntent().getStringExtra("code");
        if (TextUtils.equals(code, PermissionType.PROCESS_INSIDE.getCode())) {
            tvReceiveDep.setText("接单部门：" + getIntent().getStringExtra("depName"));
            llChoose.setVisibility(View.GONE);
            tvReceiveDep.setVisibility(View.VISIBLE);
        }
        etKey.setHint("输入产品");
    }


    private void openDialog(TradingBean.RecordsBean quantity, List<ProductBean.RecordsBean> data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_add_cart_trading, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        AddAndReduceDoubleView useNum = view.findViewById(R.id.ar_use_num);
        useNum.setMaxNum(quantity.getQuantity());
        AddAndReduceView num = view.findViewById(R.id.ar_num);
        RecyclerView rvProduct = view.findViewById(R.id.rv_pro);
        rvProduct.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        List<ProductBean.RecordsBean> dataList = new ArrayList<>();
        dataList.addAll(data);
        TradingProDetailAdapter tradingProDetailAdapter = new TradingProDetailAdapter(R.layout.item_trading_product_dialog, dataList);
        tradingProDetailAdapter.bindToRecyclerView(rvProduct);

        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double number = useNum.getNumber();
                if (number == 0d) {
                    toast("请选择使用数量");
                    return;
                }
                Map<Integer, Boolean> isChoose = tradingProDetailAdapter.getIsChoose();
                List<ProductBean.RecordsBean> info = new ArrayList<>();
                for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
                    if (entry.getValue()) {
                        ProductBean.RecordsBean recordsBean = dataList.get(entry.getKey());
                        info.add(recordsBean);
                    }
                }
                if (info.size() == 0) {
                    toast("请选择置换产品");
                    return;
                }
                quantity.setChooseNum(String.valueOf(useNum.getNumber()));
                addCart(quantity, info, num.getNumber());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

    private void addCart(TradingBean.RecordsBean quantity, List<ProductBean.RecordsBean> data, int number) {
        for (ProductBean.RecordsBean bean : data) {
            bean.setCarNum(number);
        }
        carMap.put("pro", JSON.toJSONString(quantity));
        carMap.put("proDetail", JSON.toJSONString(data));
        toast("加入购物车成功");
    }

    @Override
    protected void initData() {
        clientList = new ArrayList<>();
        clientAdapter = new TradingProductAdapter(R.layout.item_trading_product, clientList);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        param.put("deptId", getIntent().getStringExtra("depId"));
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().tradingPro(param).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                List<TradingBean.RecordsBean> dataList;
                TradingBean jsonData = JSON.parseObject(data.getData().toString(), TradingBean.class);
                if (jsonData != null) {
                    dataList = jsonData.getRecords();
                } else {
                    dataList = new ArrayList<>();
                }
                if (page == 1) {
                    clientList.clear();
                    clientList.addAll(dataList);
                    clientAdapter.notifyDataSetChanged();
                    clientAdapter.loadMoreComplete();
                } else {
                    clientAdapter.loadMoreComplete();
                    clientList.addAll(dataList);
                    clientAdapter.notifyDataSetChanged();
                }
                if (dataList.size() == 0) {
                    clientAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }

    @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) {
                getDialogDetail(clientList.get(position));
            }
        });
    }

    private void getDialogDetail(TradingBean.RecordsBean soleCode) {
        showLoading();
        RtfUtils.getRtf().tradingProDialog(soleCode.getProductSoleCode()).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                List<ProductBean.RecordsBean> productBean = JSON.parseArray(data.getData().toString(), ProductBean.RecordsBean.class);
                openDialog(soleCode, productBean);
            }
        });
    }

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_store_cart, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.cart:
                if (!carMap.containsKey("pro")) {
                    toast("购物车没有产品");
                    return super.onOptionsItemSelected(item);
                }
                startActivity(StoreTradingCarActivity.class,
                        "pro", JSON.toJSONString(carMap),
                        "supplierId", getIntent().getStringExtra("supplierId"),
                        "subProcess", getIntent().getStringExtra("subProcess"),
                        "inStockId", getIntent().getStringExtra("inStockId"),
                        "customerId", getIntent().getStringExtra("customerId"),
                        "receiveDeptId", getIntent().getStringExtra("depId"),
                        "code", getIntent().getStringExtra("code"));
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick({R.id.tv_choose, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_choose:
                finish();
                break;
            case R.id.btn_search:
                param.put("searchValue", etKey.getText().toString());
                param.put("current", 1);
                page = 1;
                getData();
                break;
        }
    }

    @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();
        carMap.put("proDetail",JSON.parseArray(pro, ProductBean.RecordsBean.class));
    }

}
