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

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
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.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
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.event.ModifyCarEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.SendApplyCrucibleChooseAdapter;
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.math.BigDecimal;
import java.util.ArrayList;
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 SendApplyCrucibleChooseActivity 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;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tv_count_desc)
    TextView tvCountDesc;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    private List<AddStockChooseBean.RecordsBean> productList;
    private SendApplyCrucibleChooseAdapter 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));
        tvCountDesc.setText(String.format("(可申请数量%s)", getIntent().getStringExtra("num")));
    }

    @Override
    protected void initData() {
        productList = new ArrayList<>();
        productAdapter = new SendApplyCrucibleChooseAdapter(R.layout.item_add_stock_choose, productList);
        productAdapter.bindToRecyclerView(rvProduct);
        productAdapter.notifyDataSetChanged();
        param = WorkUtils.pageKey();
        param.put("current", page);
        param.put("deptId", getIntent().getStringExtra("deptId"));
        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_send_apply_choose;
    }

    private void submit() {
//        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;
//                }
//            }
//        }

        List<AddStockChooseBean.RecordsBean> chooseList = productAdapter.getChooseList();
        for (AddStockChooseBean.RecordsBean recordsBean : chooseList) {
            if (TextUtils.isEmpty(recordsBean.getChooseNum()) ||
                    TextUtils.equals(recordsBean.getChooseNum(), "0")) {
                toast("请输入数量");
                return;
            }
        }

        if (chooseList.size() != 0) {
            if (new BigDecimal(Double.valueOf(tvPrice.getText().toString().split(": ")[1])).
                    compareTo(new BigDecimal(Double.valueOf(getIntent().getStringExtra("num")))) == 1) {
                toast(String.format("可申请数量最大为%s", MathUtils.converData(getIntent().getStringExtra("num"), 3)));
                return;
            }
            Intent intent = new Intent();
            intent.putExtra("stock", JSON.toJSONString(chooseList));
            intent.putExtra("position", getIntent().getStringExtra("position"));
            intent.putExtra("count", tvPrice.getText().toString().split(": ")[1]);
            setResult(10002, 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 = "";
        List<AddStockChooseBean.RecordsBean> chooseList = productAdapter.getChooseList();
        for (AddStockChooseBean.RecordsBean recordsBean : chooseList) {
            allPrice = MathUtils.add(allPrice, recordsBean.getChooseNum(), 3);
        }
//        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.notifyData();
//                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++;
//                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_finish, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.finish:
                submit();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick({R.id.tv_ok, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ok:
                submit();
                break;
            case R.id.btn_search:
                page = 1;
                param.put("stockName", etKey.getText().toString());
                param.put("current", page);
                getData();
                break;
        }
    }
}
