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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
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.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.wd.workoffice.R;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.ProcessBean;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.StockBean;
import com.wd.workoffice.bean.TradingBean;
import com.wd.workoffice.bean.event.ModifyCarEvent;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.contract.BatChooseInfoContract;
import com.wd.workoffice.presenter.BatChooseInfoPresenter;
import com.wd.workoffice.ui.adapter.StoreProductAdapter;
import com.wd.workoffice.ui.adapter.TradingProDetailAdapter;
import com.wd.workoffice.ui.adapter.TradingProductAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.UserKeeper;
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.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
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;
import butterknife.OnClick;

/**
 * 选择数据
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class ChooseInfoActivity extends WorkToolBarActivity implements BatChooseInfoContract.View {

    @BindView(R.id.ll_client)
    LinearLayout llClient;
    @BindView(R.id.ll_supplier)
    LinearLayout llSupplier;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.tv_common_desc)
    TextView tvCommonDesc;
    @BindView(R.id.tv_common_content)
    TextView tvCommonContent;
    @BindView(R.id.ll_common)
    LinearLayout llCommon;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_client)
    TextView tvClient;
    @BindView(R.id.tv_supplier)
    TextView tvSupplier;
    @BindView(R.id.tv_in_stock)
    TextView tvInStock;
    @BindView(R.id.tv_in_stock_content)
    TextView tvInStockContent;
    @BindView(R.id.ll_in_stock)
    LinearLayout llInStock;
    @BindView(R.id.tv_send_stock)
    TextView tvSendStock;
    @BindView(R.id.tv_send_stock_content)
    TextView tvSendStockContent;
    @BindView(R.id.ll_send_stock)
    LinearLayout llSendStock;
    private Map<String, Object> param;
    private List<ProductBean.RecordsBean> proList;
    private StoreProductAdapter proAdapter;
    private int page = 1;
    private int insidePage = 1;
    private String type;
    private Integer clientId;
    private BatChooseInfoPresenter batChooseInfoPresenter;
    private List<String> processNameList = new ArrayList<>();
    private List<ProcessBean> processList = new ArrayList<>();
    private ProcessBean chooseProcess;
    private QMUIDialog.MenuDialogBuilder processDialog;
    private QMUIDialog.MenuDialogBuilder stockDialog;
    String permissionCode;
    private List<ProductBean.RecordsBean> carList = new ArrayList<>();
    private Integer supplyId;
    private Map<String, Object> stockParam;
    private List<StockBean> stockList = new ArrayList<>();
    private List<String> stockNameList = new ArrayList<>();
    private StockBean chooseStock;
    //    Map<String, Object> carMap = new HashMap<>();
    private List<TradingBean.RecordsBean> tradingProductList;
    private TradingProductAdapter tradingProductAdapter;
    private Map<String, Object> tradeParam;
    private Map<String, Object> insideParam;
    private StockBean chooseSendStock;
    private BadgeCarProvider mActionProvider;
    private TradingProDetailAdapter tradingProDetailAdapter;
    private List<ProductBean.RecordsBean> changeProList;
    private List<TradingBean.RecordsBean> tradingCarList = new ArrayList<>();

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        batChooseInfoPresenter = new BatChooseInfoPresenter();
        batChooseInfoPresenter.onAttach(this);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        type = getIntent().getStringExtra("type");
        changeView();
    }

    @Override
    protected void initData() {
        proList = new ArrayList<>();
        if (TextUtils.equals("2", type)) {
            proAdapter = new StoreProductAdapter(R.layout.item_store_product, proList, 2);
        } else {
            proAdapter = new StoreProductAdapter(R.layout.item_store_product, proList);
        }

        proAdapter.bindToRecyclerView(rvData);
        proAdapter.setEmptyView(R.layout.view_empty_order, rvData);
        param = WorkUtils.pageKey();
        tradeParam = WorkUtils.pageKey();
        insideParam = WorkUtils.pageKey();
        insideParam.put("current", 1);
        param.put("current", 1);
        param.put("processType", permissionCode);
        if (!TextUtils.equals(getIntent().getStringExtra("deptId"), "-1")) {//生产计划-1
            param.put("outDeptId", getIntent().getStringExtra("deptId"));
        }

        stockParam = WorkUtils.simpleParam();
        stockParam.put("deptId", UserKeeper.getInstance().getUserDepId());
        if (TextUtils.equals("3", type)) {
            batChooseInfoPresenter.getPro(param);
            batChooseInfoPresenter.getStock(stockParam);
        }
        if (TextUtils.equals("5", type)) {
            batChooseInfoPresenter.getPro(param);
            batChooseInfoPresenter.getStock(stockParam);
        }
        if (TextUtils.equals("6", type)) {
            tradingProductList = new ArrayList<>();
            tradingProductAdapter = new TradingProductAdapter(R.layout.item_trading_product, tradingProductList);
            tradingProductAdapter.bindToRecyclerView(rvData);
            tradeParam.put("deptId", getIntent().getStringExtra("deptId"));//内部交易
            batChooseInfoPresenter.getTradingProList(tradeParam);
            batChooseInfoPresenter.getStock(stockParam);
        }
    }


    @Override
    protected void initEvent() {
        proAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                param.put("current", page);
                batChooseInfoPresenter.getPro(param);
            }
        }, rvData);
        proAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (TextUtils.equals("6", type)) {
                    openDialogInside(tradingProductList.get(position));
                } else {
                    openDialog(proList.get(position));
                }
            }
        });
        if (TextUtils.equals(type, "6")) {
            tradingProductAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    openDialogInside(tradingProductList.get(position));
                }
            });
        }
    }


    @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() {
                goCar();
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.cart:
                if (goCar()) return super.onOptionsItemSelected(item);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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


    @OnClick({R.id.ll_send_stock, R.id.ll_in_stock, R.id.ll_client, R.id.ll_supplier, R.id.btn_search, R.id.ll_common})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_send_stock:
                if (clientId == null) {
                    toast("请选择客户");
                    return;
                }
                startActivityForResult(ChooseStockActivity.class, 10005, "sign", "SEND","siteType", "OUT"
                        , "customerId", clientId.toString());
                break;
            case R.id.ll_in_stock:
//                if (clientId == null) {
//                    toast("请选择客户");
//                    return;
//                }
                startActivityForResult(ChooseStockActivity.class, 10004, "siteType", "IN"
                );
                break;
            case R.id.ll_client:
                switch (type) {
                    case "1":
                        startActivityForResult(StoreSaleClientActivity.class, 10001,
                                "depId",UserKeeper.getInstance().getUserDepId(),
                                "code", "CUSTOMER",
                                "processes", permissionCode);
                        break;
                    case "2":
                        startActivityForResult(StoreSaleClientActivity.class, 10001,
                                "depId",UserKeeper.getInstance().getUserDepId(),
                                "code", "CUSTOMER",
                                "processes", permissionCode);
                        break;
                    case "3":
                        break;
                    case "4":
                        break;
                    case "5":
                        break;
                    case "6":
                        break;
                }
                break;
            case R.id.ll_supplier:
                switch (type) {
                    case "1":
                        break;
                    case "2":
                        startActivityForResult(StoreSaleClientActivity.class, 10002,
                                "depId", getIntent().getStringExtra("deptId"),
                                "code", "SUPPLIER", "supplier", "选择供应商",
                                "processes", "PROCESS_PACKAGE");
                        break;
                    case "3":
                        startActivityForResult(StoreSaleClientActivity.class, 10002,
                                "depId", getIntent().getStringExtra("deptId"),
                                "code", "SUPPLIER", "supplier", "选择供应商",
                                "processes", "PROCESS_PACKAGE");
                        break;
                    case "4":
                        break;
                    case "5":
                        break;
                    case "6":
                        break;
                }
                break;
            case R.id.btn_search:
                switch (type) {
                    case "1":
                        if (clientId == null) {
                            toast("请选择客户");
                            return;
                        }
                        break;
                    case "2":
                        if (clientId == null) {
                            toast("请选择客户");
                            return;
                        }
                        break;
                }

                page = 1;
                if (TextUtils.equals("6", type)) {
                    tradeParam.put("current", 1);
                    tradeParam.put("name", etKey.getText().toString());
                    batChooseInfoPresenter.getTradingProList(tradeParam);
                } else {
                    param.put("searchValue", etKey.getText().toString());
                    param.put("current", 1);
                    batChooseInfoPresenter.getPro(param);
                }
                break;
            case R.id.ll_common:
                switch (type) {
                    case "1":
                        if (!WorkUtils.hasPermission(PagePermissionType.SUB_PROCESS.getPermission())) {
                            toast(R.string.permission);
                            return;
                        }
                        if (clientId == null) {
                            toast("请先选择客户");
                            return;
                        }
//                        if (processList.size() == 0) {
//                            toast("没有数据哦");
//                            return;
//                        }
//                        processDialog.show();
                        startActivityForResult(ChooseProcessActivity.class, 10003,
                                "processCode", permissionCode, "transitPartId", clientId.toString());
                        break;
                    case "2":
                        if (!WorkUtils.hasPermission(PagePermissionType.SUB_PROCESS.getPermission())) {
                            toast(R.string.permission);
                            return;
                        }
                        if (clientId == null) {
                            toast("请先选择客户");
                            return;
                        }
//                        if (processList.size() == 0) {
//                            toast("没有数据哦");
//                            return;
//                        }
//                        processDialog.show();
                        startActivityForResult(ChooseProcessActivity.class, 10003,
                                "processCode", permissionCode, "transitPartId", clientId.toString());
                        break;
                    case "3":
                        if (supplyId == null) {
                            toast("请先选择供应商");
                            return;
                        }
                        if (stockList.size() == 0) {
                            toast("没有数据哦");
                            return;
                        }
                        stockDialog.show();
                        break;
                    case "4":
                        break;
                    case "5":
                        if (stockList.size() == 0) {
                            toast("没有数据哦");
                            return;
                        }
                        stockDialog.show();
                        break;
                    case "6":
                        if (stockList.size() == 0) {
                            toast("没有数据哦");
                            return;
                        }
                        stockDialog.show();
                        break;
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (resultCode == 10001) {
                    String clientName = data.getStringExtra("clientName");
                    clientId = data.getIntExtra("id", 0);
                    tvClient.setText(clientName);
                    switch (type) {
                        case "1":
                            param.put("transitPartId", clientId);
                            chooseSendStock = null;
                            tvSendStockContent.setText("");
//                            batChooseInfoPresenter.getProcess(permissionCode, clientId);
                            page = 1;
                            param.put("current", 1);
                            carList.clear();
                            batChooseInfoPresenter.getPro(param);
                            break;
                        case "2":
                            tvCommonContent.setText("");
                            chooseSendStock = null;
                            tvSendStockContent.setText("");
//                            batChooseInfoPresenter.getProcess(permissionCode, clientId);
                            break;
                        case "3":
                            break;
                        case "4":
                            break;
                        case "5":
                            break;
                        case "6":
                            break;
                    }

                }
                break;
            case 10002:
                if (resultCode == 10002) {
                    String clientName = data.getStringExtra("clientName");
                    supplyId = data.getIntExtra("id", 0);
                    tvSupplier.setText(clientName);
                    switch (type) {
                        case "1":
                            break;
                        case "2":
                            param.put("transitPartId", supplyId);
                            page = 1;
                            param.put("current", 1);
                            carList.clear();
                            batChooseInfoPresenter.getPro(param);
                            break;
                        case "3":
                            param.put("transitPartId", supplyId);
                            carList.clear();
                            page = 1;
                            param.put("current", 1);
                            batChooseInfoPresenter.getPro(param);
                            break;
                        case "4":
                            break;
                        case "5":
                            break;
                        case "6":
                            break;
                    }
                }
                break;
            case 10003:
                if (resultCode == 10003) {
                    chooseProcess = JSON.parseObject(data.getStringExtra("process"), ProcessBean.class);
                    tvCommonContent.setText(chooseProcess.getName());
                }
                break;
            case 10004://入库
                if (resultCode == 10005) {
                    chooseStock = JSON.parseObject(data.getStringExtra("stock"), StockBean.class);
                    tvInStockContent.setText(chooseStock.getName());
                }
                break;
            case 10005://出库
                if (resultCode == 10005) {
                    chooseSendStock = JSON.parseObject(data.getStringExtra("stock"), StockBean.class);
                    tvSendStockContent.setText(chooseSendStock.getName());
                }
                break;
        }
    }

    @Override
    public void getStock(List<StockBean> dataList) {
        stockList = dataList;
        stockNameList.clear();
        for (StockBean dep : dataList) {
            stockNameList.add(dep.getName());
        }
        stockDialog = DialogUtils.listDialog(this);
        stockDialog.addItems(stockNameList.toArray(new String[stockNameList.size()]), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chooseStock = stockList.get(which);
                tvCommonContent.setText(stockNameList.get(which));
                dialog.dismiss();
            }
        });
    }

    @Override
    public void getTradingPro(List<ProductBean.RecordsBean> list) {
//        toast("搜索完成");
//        changeProList.clear();
//        changeProList.addAll(list);
//        tradingProDetailAdapter.notifyDataSetChanged();

        if (insidePage == 1) {
            changeProList.clear();
            changeProList.addAll(list);
            tradingProDetailAdapter.notifyDataSetChanged();
            tradingProDetailAdapter.loadMoreComplete();
        } else {
            tradingProDetailAdapter.loadMoreComplete();
            changeProList.addAll(list);
            tradingProDetailAdapter.notifyDataSetChanged();
        }
        if (list.size() == 0) {
            tradingProDetailAdapter.loadMoreEnd();
        } else {
            insidePage++;
        }
    }

    @Override
    public void getTradingProList(List<TradingBean.RecordsBean> dataList) {
        if (page == 1) {
            tradingProductList.clear();
            tradingProductList.addAll(dataList);
            tradingProductAdapter.notifyDataSetChanged();
            tradingProductAdapter.loadMoreComplete();
        } else {
            tradingProductAdapter.loadMoreComplete();
            tradingProductList.addAll(dataList);
            tradingProductAdapter.notifyDataSetChanged();
        }
        if (dataList.size() == 0) {
            tradingProductAdapter.loadMoreEnd();
        } else {
            page++;
        }
    }

    @Override
    public void processList(List<ProcessBean> dataList) {
        processList.clear();
        processList.addAll(dataList);
        processNameList.clear();
        for (ProcessBean process : dataList) {
            processNameList.add(process.getName());
        }
        processDialog = DialogUtils.listDialog(this);
        processDialog.addItems(processNameList.toArray(new String[processNameList.size()]), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chooseProcess = processList.get(which);
                tvCommonContent.setText(processNameList.get(which));
                dialog.dismiss();
            }
        });
    }

    @Override
    public void getPro(List<ProductBean.RecordsBean> dataList) {
        if (page == 1) {
            proList.clear();
            proList.addAll(dataList);
            proAdapter.notifyDataSetChanged();
            proAdapter.loadMoreComplete();
        } else {
            proAdapter.loadMoreComplete();
            proList.addAll(dataList);
            proAdapter.notifyDataSetChanged();
        }
        if (dataList.size() == 0) {
            proAdapter.loadMoreEnd();
        } else {
            page++;
        }
    }

    private void changeView() {
        switch (type) {
            case "1":
                permissionCode = PermissionType.PROCESS_SALE.getCode();
                llSupplier.setVisibility(View.GONE);
                break;
            case "2":
                permissionCode = PermissionType.PROCESS_PURCHASE.getCode();
                break;
            case "3":
                permissionCode = PermissionType.PROCESS_SUPPLY.getCode();
                llClient.setVisibility(View.GONE);
                llSendStock.setVisibility(View.GONE);
                tvCommonDesc.setText("入库仓库");
                tvCommonContent.setHint("请选择入库仓库");
                break;
            case "4":
                break;
            case "5":
                permissionCode = PermissionType.PROCESS_CRUCIBLE.getCode();
                llClient.setVisibility(View.GONE);
                llSupplier.setVisibility(View.GONE);
                llSendStock.setVisibility(View.GONE);
                tvCommonDesc.setText("入库仓库");
                tvCommonContent.setHint("请选择入库仓库");
                break;
            case "6":
                permissionCode = PermissionType.PROCESS_INSIDE.getCode();
                llClient.setVisibility(View.GONE);
                llSupplier.setVisibility(View.GONE);
                llSendStock.setVisibility(View.GONE);
                tvCommonDesc.setText("入库仓库");
                tvCommonContent.setHint("请选择入库仓库");
                break;
        }
    }

    private boolean goCar() {
        if (TextUtils.equals("6", type)) {
            if (chooseStock == null) {
                toast("请选择入库仓库");
                return true;
            }
            if (tradingCarList.size() == 0) {
                toast("购物车没有产品");
                return true;
            }
            startActivity(StoreTradingCarActivity.class,
                    "pro", JSON.toJSONString(tradingCarList),
                    "supplierId", supplyId == null ? "" : supplyId.toString(),
                    "subProcess", chooseProcess == null ? "" : chooseProcess.getName(),
                    "subProcessId", chooseProcess == null ? "" : chooseProcess.getId() + "",
                    "inStockId", chooseStock == null ? "" : chooseStock.getId() + "",
                    "customerId", clientId == null ? "" : clientId.toString(),
                    "receiveDeptId", getIntent().getStringExtra("deptId"),
                    "code", permissionCode);
        } else {
            if (carList.size() == 0) {
                toast("购物车没有产品");
                return true;
            }
            switch (type) {
                case "1":
                    if (clientId == null) {
                        toast("请选择客户");
                        return true;
                    }
                    if (chooseStock == null) {
                        toast("请选择入库仓库");
                        return true;
                    }
                    if (chooseSendStock == null) {
                        toast("请选择发货仓库");
                        return true;
                    }
                    break;
                case "2":
                    if (clientId == null) {
                        toast("请选择客户");
                        return true;
                    }
                    if (supplyId == null) {
                        toast("请选择供应商");
                        return true;
                    }
                    if (chooseStock == null) {
                        toast("请选择入库仓库");
                        return true;
                    }
                    if (chooseSendStock == null) {
                        toast("请选择发货仓库");
                        return true;
                    }
                    break;
                case "3":
                    if (supplyId == null) {
                        toast("请先选择供应商");
                        return true;
                    }
                    if (chooseStock == null) {
                        toast("请选择入库仓库");
                        return true;
                    }
                    break;
                case "4":
                    break;
                case "5":
                    if (chooseStock == null) {
                        toast("请选择入库仓库");
                        return true;
                    }
                    break;
                case "6":
                    if (chooseStock == null) {
                        toast("请选择入库仓库");
                        return true;
                    }
                    break;
            }
            startActivity(StoreSaleCarActivity.class,
                    "pro", JSON.toJSONString(carList),
                    "supplierId", supplyId == null ? "" : supplyId.toString(),
                    "subProcess", chooseProcess == null ? "" : chooseProcess.getName(),
                    "subProcessId", chooseProcess == null ? "" : chooseProcess.getId() + "",
                    "inStockId", chooseStock == null ? "" : chooseStock.getId() + "",
                    "intoStore", chooseStock == null ? "" : chooseStock.getId() + "",
                    "outerStore", chooseSendStock == null ? "" : chooseSendStock.getId() + "",
                    "customerId", clientId == null ? "" : clientId.toString(),
                    "receiveDeptId", getIntent().getStringExtra("deptId"),
                    "code", permissionCode);
        }
        return false;
    }


    /**
     * 普通选择产品
     *
     * @param data
     */
    private void openDialog(ProductBean.RecordsBean data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_add_cart, null);
        LinearLayout llPrice = view.findViewById(R.id.ll_price);
        LinearLayout llInnerPrice = view.findViewById(R.id.ll_inner_price);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        AddAndReduceView num = view.findViewById(R.id.ar_num);
        EditText etPrice = view.findViewById(R.id.et_price);
        EditText etInnerPrice = view.findViewById(R.id.et_inner_price);
        WorkUtils.addDecimalsListener(etPrice);
        etPrice.setText(MathUtils.converData(data.getInternalPrice(), 3));
        etInnerPrice.setText(MathUtils.converData(data.getInternalPrice(), 3));
        if (TextUtils.equals(permissionCode, PermissionType.PROCESS_PURCHASE.getCode())) {
            llInnerPrice.setVisibility(View.VISIBLE);
        } else {
            llInnerPrice.setVisibility(View.GONE);
        }
        for (ProductBean.RecordsBean recordsBean : carList) {
            if (data.getId() == recordsBean.getId()) {
                etInnerPrice.setText(recordsBean.getCarInnerPrice());
                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(permissionCode, PermissionType.PROCESS_PURCHASE.getCode())
                        && TextUtils.isEmpty(etInnerPrice.getText().toString())) {
                    toast("请填写内部单价");
                    return;
                }
                if (TextUtils.isEmpty(etPrice.getText().toString())) {
                    toast("请填写销售单价");
                    return;
                }
                if (TextUtils.equals(num.getNumber(), "0")) {
                    toast("请选择数量");
                    return;
                }
                addCart(data, num.getNumber(), etPrice.getText().toString(), etInnerPrice.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         单价
     * @param innerPrice     外采购修改内部单价
     */
    private void addCart(ProductBean.RecordsBean chooseProduct, String number, String price, String innerPrice) {
        boolean isHas = false;
        for (ProductBean.RecordsBean recordsBean : carList) {
            if (chooseProduct.getId() == recordsBean.getId()) {
                isHas = true;
                recordsBean.setCarNum(number);
                recordsBean.setCarPrice(price);
                recordsBean.setCarInnerPrice(innerPrice);
                recordsBean.setInternalPrice(Double.parseDouble(innerPrice));
            }
        }
        if (!isHas) {
            chooseProduct.setCarNum(number);
            chooseProduct.setCarPrice(price);
            chooseProduct.setCarInnerPrice(innerPrice);
            chooseProduct.setInternalPrice(Double.parseDouble(innerPrice));
            carList.add(chooseProduct);
        }
        proAdapter.notifyDataSetChanged();
        toast("加入购物车成功");
        changeCarBadge();
    }


    /**
     * 内部交易选择产品
     *
     * @param quantity
     */
    private void openDialogInside(TradingBean.RecordsBean quantity) {
        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);
        TextView tvSearch = view.findViewById(R.id.iv_search);
        EditText tvKey = view.findViewById(R.id.et_key);
        AddAndReduceView 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));
        changeProList = new ArrayList<>();
        tradingProDetailAdapter = new TradingProDetailAdapter(R.layout.item_trading_product_dialog, changeProList);
        tradingProDetailAdapter.bindToRecyclerView(rvProduct);
        tradingProDetailAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                insideParam.put("current", insidePage);
                batChooseInfoPresenter.getTradingPro(insideParam);
            }
        }, rvProduct);
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tvKey.getText().toString())) {
                    toast("请输入搜索关键字");
                    return;
                }
                insidePage = 1;
                insideParam.put("current", insidePage);
                insideParam.put("name", tvKey.getText().toString());
                batChooseInfoPresenter.getTradingPro(insideParam);
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = useNum.getNumber();
                if (Double.parseDouble(number) == 0d) {
                    toast("请选择使用数量");
                    return;
                }
                List<ProductBean.RecordsBean> info = new ArrayList<>();
                if (tradingProDetailAdapter.getChoosePos() == -1) {
                    toast("请选择置换产品");
                    return;
                }
                info.add(changeProList.get(tradingProDetailAdapter.getChoosePos()));
                quantity.setChooseNum(String.valueOf(useNum.getNumber()));
                addCartInside(quantity, info, num.getNumber());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

    /**
     * 內部添加购物车
     *
     * @param quantity
     * @param data
     * @param number
     */
    private void addCartInside(TradingBean.RecordsBean quantity, List<ProductBean.RecordsBean> data, String number) {
        for (ProductBean.RecordsBean bean : data) {
            bean.setCarNum(number);
        }
        boolean isHas = false;
        for (TradingBean.RecordsBean recordsBean : tradingCarList) {
            if (quantity.getId() == recordsBean.getId()) {
                isHas = true;
                recordsBean.setChooseNum(quantity.getChooseNum());
                recordsBean.setChooseName(data.get(0).getSimpleCode());
                recordsBean.setChangePro(data.get(0));

            }
        }
        if (!isHas) {
            quantity.setChangePro(data.get(0));
            quantity.setChooseName(data.get(0).getSimpleCode());
            tradingCarList.add(quantity);
        }
        if (data.size() > 0) {
            mActionProvider.setBadgeVisibility(View.VISIBLE);
        } else {
            mActionProvider.setBadgeVisibility(View.GONE);
        }
        toast("加入购物车成功");
        tradingProductAdapter.notifyDataSetChanged();
    }

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

    @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();
        if (TextUtils.equals("6", type)) {
            tradingCarList.clear();
            tradingCarList.addAll(JSON.parseArray(pro, TradingBean.RecordsBean.class));
            for (TradingBean.RecordsBean tradingPro : tradingProductList) {//购物车信息置空
                tradingPro.setChooseNum(null);
                tradingPro.setChooseName(null);
                tradingPro.setChangePro(null);
            }
            for (TradingBean.RecordsBean recordsBean : tradingCarList) {//判断购物车信息，添加信息
                for (TradingBean.RecordsBean bean : tradingProductList) {
                    if (bean.getId() == recordsBean.getId()) {
                        bean.setChooseNum(recordsBean.getChooseNum());
                        bean.setChooseName(recordsBean.getChooseName());
                        bean.setChangePro(recordsBean.getChangePro());
                    }
                }

            }
            tradingProductAdapter.notifyDataSetChanged();
        } else {
            carList.clear();
            carList.addAll(JSON.parseArray(pro, ProductBean.RecordsBean.class));
            for (ProductBean.RecordsBean proInfo : proList) {//购物车信息置空
                proInfo.setCarNum(null);
                proInfo.setCarPrice(null);
                proInfo.setCarInnerPrice(null);
            }
            for (ProductBean.RecordsBean recordsBean : carList) {
                for (ProductBean.RecordsBean bean : proList) {
                    if (bean.getId() == recordsBean.getId()) {
                        bean.setCarNum(recordsBean.getCarNum());
                        bean.setCarPrice(recordsBean.getCarPrice());
                        bean.setCarInnerPrice(recordsBean.getCarInnerPrice());
                    }
                }

            }
            proAdapter.notifyDataSetChanged();
        }
        changeCarBadge();
    }
}
