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

import android.content.DialogInterface;
import android.content.Intent;
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.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.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.util.DialogUtils;
import com.wd.workoffice.util.UserKeeper;
import com.wd.workoffice.util.WorkUtils;
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.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
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;
    private Map<String, Object> param;
    private List<ProductBean.RecordsBean> proList;
    private StoreProductAdapter proAdapter;
    private int page = 1;
    private String type;
    private Integer clientId;
    private BatChooseInfoPresenter batChooseInfoPresenter;
    private List<String> processNameList = new ArrayList<>();
    private List<ProcessBean> processList;
    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;
    private List<String> stockNameList = new ArrayList<>();
    private StockBean chooseStock;

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

    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);
                tvCommonDesc.setText("入库仓库");
                tvCommonContent.setHint("请选择入库仓库");
                break;
            case "4":
                break;
            case "5":
                permissionCode = PermissionType.PROCESS_CRUCIBLE.getCode();
                llClient.setVisibility(View.GONE);
                llSupplier.setVisibility(View.GONE);
                tvCommonDesc.setText("入库仓库");
                tvCommonContent.setHint("请选择入库仓库");
                break;
            case "6":
                permissionCode = PermissionType.PROCESS_INSIDE.getCode();
                llClient.setVisibility(View.GONE);
                llSupplier.setVisibility(View.GONE);
                tvCommonDesc.setText("入库仓库");
                tvCommonContent.setHint("请选择入库仓库");
                break;
        }
    }

    @Override
    protected void initData() {
        proList = new ArrayList<>();
        proAdapter = new StoreProductAdapter(R.layout.item_store_product, proList);
        proAdapter.bindToRecyclerView(rvData);
        proAdapter.setEmptyView(R.layout.view_empty_order, rvData);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        param.put("processType", permissionCode);
        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.getStock(stockParam);
        }
        if (TextUtils.equals("6", type)) {
            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) {
                openDialog(proList.get(position));
            }
        });
    }

    @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 (carList.size() == 0) {
                    toast("购物车没有产品");
                    return super.onOptionsItemSelected(item);
                }
                startActivity(StoreSaleCarActivity.class,
                        "pro", JSON.toJSONString(carList),
                        "supplierId", getIntent().getStringExtra("supplierId"),
                        "subProcess", getIntent().getStringExtra("subProcess"),
                        "subProcessId", getIntent().getStringExtra("subProcessId"),

                        "inStockId", getIntent().getStringExtra("inStockId"),
                        "customerId", getIntent().getStringExtra("customerId"),
                        "receiveDeptId", getIntent().getStringExtra("depId"),
                        "code", getIntent().getStringExtra("code"));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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


    @OnClick({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_client:
                startActivityForResult(ChooseClientActivity.class, 10001
                        , "code", "CUSTOMER");
                break;
            case R.id.ll_supplier:
//                startActivityForResult(ChooseClientActivity.class, 10001,
//                        "title", "选择供应商", "code", "SUPPLIER");
                startActivityForResult(ChooseClientActivity.class, 10002,
                        "code", "SUPPLIER", "supplier", "选择供应商");

                break;
            case R.id.btn_search:
                if (clientId == null) {
                    toast("请选择用户");
                    return;
                }
                param.put("name", etKey.getText().toString());
                param.put("current", 1);
                page = 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;
                        }
                        processDialog.show();
                        break;
                    case "2":
                        if (!WorkUtils.hasPermission(PagePermissionType.SUB_PROCESS.getPermission())) {
                            toast(R.string.permission);
                            return;
                        }
                        if (clientId == null) {
                            toast("请先选择客户");
                            return;
                        }
                        processDialog.show();
                        break;
                    case "3":
                        if (supplyId == null) {
                            toast("请先选择供应商");
                            return;
                        }
                        stockDialog.show();
                        break;
                    case "4":
                        break;
                    case "5":
                        stockDialog.show();
                        break;
                    case "6":
                        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);
                    param.put("transitPartId", clientId);
                    switch (type) {
                        case "1":
                            batChooseInfoPresenter.getProcess(permissionCode, clientId);
                            break;
                        case "2":
                            batChooseInfoPresenter.getProcess(permissionCode, clientId);
                            break;
                        case "3":
                            break;
                        case "4":
                            break;
                        case "5":
                            break;
                        case "6":
                            break;
                    }
                    batChooseInfoPresenter.getPro(param);
                }
                break;
            case 10002:
                if (resultCode == 10001) {
                    String clientName = data.getStringExtra("clientName");
                    supplyId = data.getIntExtra("id", 0);
                    tvSupplier.setText(clientName);
                }
                break;
        }
    }

    @Override
    public void getStock(List<StockBean> dataList) {
        stockList = dataList;
        stockNameList.clear();
        for (StockBean dep : dataList) {
            stockNameList.add(dep.getName());
        }
        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 processList(List<ProcessBean> dataList) {
        processList = dataList;
        processNameList.clear();
        for (ProcessBean process : dataList) {
            processNameList.add(process.getName());
        }
        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++;
        }
    }

    @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));
    }

    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);
        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);
        if (TextUtils.equals(permissionCode, PermissionType.PROCESS_SUPPLY.getCode())) {
            llPrice.setVisibility(View.GONE);
        } else {
            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(permissionCode, PermissionType.PROCESS_SUPPLY.getCode()) && TextUtils.isEmpty(etPrice.getText().toString())) {
                    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, int 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("加入购物车成功");
    }
}
