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

import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
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.ProAddBean;
import com.wd.workoffice.bean.event.CheckTicketEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.ProAddAdapter;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.widget.AddAndReduceView;

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

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 ProductOrderProActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.ll_bottom)
    RelativeLayout llBottom;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    private Map<String, Object> param;
    private List<ProAddBean.RecordsBean> clientList;
    private ProAddAdapter clientAdapter;
    private int page = 1;
    private List<ProAddBean.RecordsBean> carList = new ArrayList<>();

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


    private void openDialog(ProAddBean.RecordsBean data, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_choose_pro_from, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvDesc = view.findViewById(R.id.tv_desc);
        AddAndReduceView num = view.findViewById(R.id.ar_num);
        TextView etPrice = view.findViewById(R.id.et_price);
        etPrice.setClickable(false);
        for (ProAddBean.RecordsBean recordsBean : carList) {
            if (data.getId() == recordsBean.getId()) {
//                etPrice.setText(recordsBean.getCarPrice());
                num.setNumber(recordsBean.getCarNum());
            }
        }
        etPrice.setText(String.valueOf(data.getCanPackageSum()));
        num.setMaxNum(data.getCanPackageSum());
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Double.valueOf(num.getNumber()) == 0d) {
                    toast("请填写数量");
                    return;
                }
                clientList.get(position).setCarNum(String.valueOf(num.getNumber()));
                addCart(data, num.getNumber());
                tvNum.setText("共 ".concat(clientList.size() + "").concat(" 件"));
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

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

    @Override
    protected void initData() {
        clientList = new ArrayList<>();
        clientAdapter = new ProAddAdapter(R.layout.item_product_add_pro, clientList);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        param.put("customerId", getIntent().getStringExtra("customerId"));
        param.put("tranFromStockId", getIntent().getStringExtra("targetStockId"));
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().saleOrderPro(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<ProAddBean.RecordsBean> dataList = JSON.parseObject(data.getData().toString(), ProAddBean.class).getRecords();

                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.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                openDialog(clientList.get(position), position);
            }
        });
    }

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


    @OnClick({R.id.tv_ok, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ok:
//                if (carList.size() == 0) {
//                    toast("请选择产品");
//                    return;
//                }
                startActivity(ProductOrderProTargetActivity.class,
                        "base",getIntent().getStringExtra("base"),
                        "usedStockId", getIntent().getStringExtra("usedStockId"),
                        "targetStockId", getIntent().getStringExtra("targetStockId"),
                        "customerId", getIntent().getStringExtra("customerId"),
                        "from", JSON.toJSONString(carList));
                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
    public void refresh(CheckTicketEvent event) {
        finish();
    }
}
