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

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
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.DeviceBean;
import com.wd.workoffice.bean.event.AddDeviceEvent;
import com.wd.workoffice.bean.event.CheckDeviceEvent;
import com.wd.workoffice.bean.event.ModifyCarEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.DeviceProductAdapter;
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 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 DeviceBuyProductActivity extends WorkToolBarActivity {
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    private Map<String, Object> param;
    private List<DeviceBean.RecordsBean> clientList;
    private DeviceProductAdapter clientAdapter;
    private int page = 1;
    private List<DeviceBean.RecordsBean> carList = new ArrayList<>();

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


    private void openDialog(DeviceBean.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);
        for (DeviceBean.RecordsBean recordsBean : carList) {
            if (data.getId() == recordsBean.getId()) {
                etPrice.setText(recordsBean.getCarPrice());
                num.setNumber(recordsBean.getCarNum());
            }
        }
        WorkUtils.addDecimalsListener(etPrice);
        etPrice.setHint("请输入价格");
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (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(DeviceBean.RecordsBean chooseProduct, String number, String price) {
        boolean isHas = false;
        for (DeviceBean.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 DeviceProductAdapter(R.layout.item_device_product, clientList);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        param.put("parentId", 0);
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().equipmentList(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<DeviceBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), DeviceBean.class).getRecords();
                if (page == 1) {
                    clientList.clear();
                    clientList.addAll(getList);
                    clientAdapter.notifyDataSetChanged();
                    clientAdapter.loadMoreComplete();
                } else {
                    clientAdapter.loadMoreComplete();
                    clientList.addAll(getList);
                    clientAdapter.notifyDataSetChanged();
                }
                if (getList.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_device_buy_pro;
    }


    @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(DeviceBuyCarActivity.class,
                        "pro", JSON.toJSONString(carList),
                        "depId", getIntent().getStringExtra("depId"),
                        "depName", getIntent().getStringExtra("depName"));
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @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, DeviceBean.RecordsBean.class));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddDeviceEvent event) {
      finish();
    }
}
