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

import android.content.Intent;
import android.text.TextUtils;
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.AddStockChooseBean;
import com.wd.workoffice.bean.ProductBean;
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.AddStockCrucibleChooseAdapter;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.ll_bottom)
    RelativeLayout llBottom;
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    private List<AddStockChooseBean.RecordsBean> productList;
    private AddStockCrucibleChooseAdapter productAdapter;
    private int page = 1;
    private Map<String, Object> param;

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

    @Override
    protected void initData() {
        productList = new ArrayList<>();
        productAdapter = new AddStockCrucibleChooseAdapter(R.layout.item_add_stock_choose, productList);
        productAdapter.bindToRecyclerView(rvProduct);
        productAdapter.notifyDataSetChanged();
        param = WorkUtils.pageKey();
        param.put("current", page);
        param.put("deptId", getIntent().getStringExtra("depId"));
        param.put("productId", getIntent().getStringExtra("productId"));
        getData();
        changeNumAndPrice();

    }

    private void changeChooseStatue() {
        String pro = getIntent().getStringExtra("pro");
        if (!TextUtils.isEmpty(pro)) {
            Map<Integer, Boolean> isChoose = productAdapter.getIsChoose();
            List<AddStockChooseBean.RecordsBean> chooseList = JSON.parseArray(pro, AddStockChooseBean.RecordsBean.class);
            for (AddStockChooseBean.RecordsBean chooseStock : chooseList) {
                for (int i = 0; i < productList.size(); i++) {
                    if (productList.get(i).getId() == chooseStock.getId()) {
                        isChoose.put(i, true);
                        productList.get(i).setChooseNum(chooseStock.getChooseNum());
                    }
                }
            }
            productAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void initEvent() {
//        productAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//            @Override
//            public void onLoadMoreRequested() {
//                param.put("current", page);
//                getData();
//            }
//        }, rvProduct);
    }

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

    @OnClick(R.id.tv_ok)
    public void onViewClicked() {
        Map<Integer, Boolean> isChoose = productAdapter.getIsChoose();
        boolean isHas = false;
        List<AddStockChooseBean.RecordsBean> backList = new ArrayList<>();
        for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
            if (entry.getValue()) {
                isHas = true;
                backList.add(productList.get(entry.getKey()));
                if (TextUtils.isEmpty(productList.get(entry.getKey()).getChooseNum())||
                        TextUtils.equals(productList.get(entry.getKey()).getChooseNum(), "0")) {
                    toast("请输入数量");
                    return;
                }
            }
        }
        if (isHas) {
            Intent intent = new Intent();
            intent.putExtra("stock", JSON.toJSONString(backList));
            intent.putExtra("count", tvPrice.getText().toString().split(": ")[1]);
            setResult(10001, intent);
            finish();
        } else {
            toast("请选择来源仓库");
        }
    }

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

    private void changeNumAndPrice() {
        String allPrice = "";
        Map<Integer, Boolean> isChoose = productAdapter.getIsChoose();
        for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
            if (entry.getValue()) {
                allPrice = MathUtils.add(allPrice, productList.get(entry.getKey()).getChooseNum(), 3);
            }
        }
        tvPrice.setText("小计: ".concat(allPrice));
    }

    private void getData() {
        RtfUtils.getRtf().productionPlan(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<AddStockChooseBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), AddStockChooseBean.class).getRecords();
                productList.clear();
                productList.addAll(getList);
                productAdapter.notifyDataSetChanged();
                changeChooseStatue();
//                if (page == 1) {
//                    productList.clear();
//                    productList.addAll(getList);
//                    productAdapter.notifyDataSetChanged();
//                    productAdapter.loadMoreComplete();
//                } else {
//                    productAdapter.loadMoreComplete();
//                    productList.addAll(getList);
//                    productAdapter.notifyDataSetChanged();
//                }
//                if (getList.size() == 0) {
//                    productAdapter.loadMoreEnd();
//                } else {
//                    page++;
//                }
            }
        });
    }
}
