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

import android.os.Bundle;
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.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.StoreProductAdapter;
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.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 StoreSaleProductActivity 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_desc1)
    TextView tvDesc1;
    @BindView(R.id.tv_desc2)
    TextView tvDesc2;
    @BindView(R.id.tv_desc3)
    TextView tvDesc3;
    @BindView(R.id.tv_desc4)
    TextView tvDesc4;
    @BindView(R.id.tv_desc5)
    TextView tvDesc5;
    @BindView(R.id.tv_receive_dep)
    TextView tvReceiveDep;
    @BindView(R.id.ll_choose)
    LinearLayout llChoose;
    private Map<String, Object> param;
    private List<ProductBean.RecordsBean> clientList;
    private StoreProductAdapter clientAdapter;
    private int page = 1;
    private List<ProductBean.RecordsBean> carList = new ArrayList<>();
    private String code;

    @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_PURCHASE.getCode())) {
            tvDesc1.setText("订单类型：" + WorkUtils.getPermissionName(getIntent().getStringExtra("code")));
            tvDesc2.setText("客户名称：" + getIntent().getStringExtra("clientName"));
            tvDesc3.setText("生产厂：" + getIntent().getStringExtra("depName"));
            tvDesc4.setText("供应商：" + getIntent().getStringExtra("supplierName"));
            tvDesc5.setText("订单子流程：" + getIntent().getStringExtra("subProcess"));
        } else if (TextUtils.equals(code, PermissionType.PROCESS_SALE.getCode())) {
            tvDesc1.setText("客户名称：" + getIntent().getStringExtra("clientName"));
            tvDesc2.setText("厂家：" + getIntent().getStringExtra("depName"));
            tvDesc5.setText("订单流程：" + getIntent().getStringExtra("process"));
            tvDesc3.setVisibility(View.GONE);
            tvDesc4.setVisibility(View.GONE);
        } else if (TextUtils.equals(code, PermissionType.PROCESS_INSIDE.getCode())) {
            tvReceiveDep.setText("接单部门：" + getIntent().getStringExtra("depName"));
            llChoose.setVisibility(View.GONE);
            tvReceiveDep.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(code, PermissionType.PROCESS_SUPPLY.getCode())) {
            tvDesc1.setText("订单类型：" + WorkUtils.getPermissionName(getIntent().getStringExtra("code")));
            tvDesc2.setText("客户名称：" + getIntent().getStringExtra("clientName"));
            tvDesc3.setText("生产厂：" + getIntent().getStringExtra("depName"));
            tvDesc4.setText("供应商：" + getIntent().getStringExtra("supplierName"));
            tvDesc5.setText("订单子流程：" + getIntent().getStringExtra("subProcess"));
        } else if (TextUtils.equals(code, PermissionType.PROCESS_CRUCIBLE.getCode())) {
            tvReceiveDep.setText("接单部门：" + getIntent().getStringExtra("depName"));
            llChoose.setVisibility(View.GONE);
            tvReceiveDep.setVisibility(View.VISIBLE);
        } else {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    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(code, 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(code, 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, 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("加入购物车成功");
    }

    @Override
    protected void initData() {
        clientList = new ArrayList<>();
        clientAdapter = new StoreProductAdapter(R.layout.item_store_product, clientList);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        param.put("processType", getIntent().getStringExtra("code"));
        param.put("outDeptId", getIntent().getStringExtra("depId"));
        if (!TextUtils.isEmpty(getIntent().getStringExtra("transitPartId"))) {
            param.put("transitPartId", getIntent().getStringExtra("transitPartId"));
        }
//        param.put("searchValue", "1");
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().getProductList(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<ProductBean.RecordsBean> dataList;
                ProductBean jsonData = JSON.parseObject(data.getData().toString(), ProductBean.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) {
                openDialog(clientList.get(position));
            }
        });
    }

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


    @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("name", 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();
        carList.clear();
        carList.addAll(JSON.parseArray(pro, ProductBean.RecordsBean.class));
    }

}
