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

import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
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.StockBean;
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.StoreCarAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.UserKeeper;
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.HashMap;
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 StoreSaleCarActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_num)
    TextView tvNum;
    @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<ProductBean.RecordsBean> productList;
    private StoreCarAdapter productAdapter;
    private int warningFlag = 0;

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

    @Override
    protected void initData() {
        productList = new ArrayList<>();
        if (!TextUtils.equals(PermissionType.PROCESS_PURCHASE.getCode(), getIntent().getStringExtra("code"))) {
            productAdapter = new StoreCarAdapter(R.layout.item_store_car, productList, 2);
        } else {
            productAdapter = new StoreCarAdapter(R.layout.item_store_car, productList);
        }
        productAdapter.bindToRecyclerView(rvProduct);
        String pro = getIntent().getStringExtra("pro");
        productList.addAll(JSON.parseArray(pro, ProductBean.RecordsBean.class));
        productAdapter.notifyDataSetChanged();
        changeNumAndPrice(false);
    }

    @Override
    protected void initEvent() {
        productAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                QMUIDialog.MessageDialogBuilder dialog = DialogUtils.okAndCancelDialog(StoreSaleCarActivity.this);
                dialog.setMessage("是否删除").addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        productList.remove(position);
                        productAdapter.notifyDataSetChanged();
                        EventBus.getDefault().post(new ModifyCarEvent(JSON.toJSONString(productList)));
                    }
                }).show();
            }
        });
    }

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

    @OnClick(R.id.tv_ok)
    public void onViewClicked() {
        if (productList.size() == 0) {
            toast("购物车里没有产品哦");
            return;
        }
        if (warningFlag == 1) {
            QMUIDialog.MessageDialogBuilder builder = DialogUtils.okAndCancelDialog(this);
            builder.setTitle("提示").setMessage("包含达到预警数量的产品，是否继续提交").
                    addAction("取消", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            goNext();
                            dialog.dismiss();
                        }
                    }).show();
        } else {
            goNext();
        }
    }

    private void goNext() {
        String allPrice = "";
        for (ProductBean.RecordsBean recordsBean : productList) {
            allPrice = MathUtils.add(allPrice, MathUtils.multiply(recordsBean.getCarNum(), MathUtils.converData(recordsBean.getInternalPrice(), 3), 3), 3);
        }
        startActivity(StoreSaleConfirmActivity.class, "pro", JSON.toJSONString(productList),
                "subProcess", getIntent().getStringExtra("subProcess"),
                "supplierId", getIntent().getStringExtra("supplierId"),
                "subProcessId", getIntent().getStringExtra("subProcessId"),
                "inStockId", getIntent().getStringExtra("inStockId"),
                "intoStore", getIntent().getStringExtra("intoStore"),
                "outerStore", getIntent().getStringExtra("outerStore"),
                "customerId", getIntent().getStringExtra("customerId"),
                "receiveDeptId", getIntent().getStringExtra("receiveDeptId"),
                "code", getIntent().getStringExtra("code"),
                "launchOrderAmount", allPrice);
    }

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

    private void changeNumAndPrice(boolean isNeedRefresh) {
        tvNum.setText("共 ".concat(productList.size() + "").concat(" 件"));
        String allPrice = "";
        for (ProductBean.RecordsBean recordsBean : productList) {
            allPrice = MathUtils.add(allPrice, MathUtils.multiply(recordsBean.getCarNum(), MathUtils.converData(recordsBean.getInternalPrice(), 3), 3), 3);
        }
        tvPrice.setText("总计: ¥ ".concat(allPrice));
        if (isNeedRefresh)
            checkNum();
    }

    /**
     * 检查库存预警
     */
    private void checkNum() {
        Map<String, Object> param = new HashMap<>();
        param.put("launchDeptId", UserKeeper.getInstance().getUserDepId());
        List<JSONObject> proList = new ArrayList<>();
        for (ProductBean.RecordsBean proBean : productList) {
            JSONObject data = new JSONObject();
            data.put("productId", proBean.getId());
            data.put("productCount", proBean.getCarNum());
            proList.add(data);
        }
        param.put("basalOrderItems", proList);
        RtfUtils.getRtf().proNumCheck(WorkUtils.convertMapToBody(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;
                }
                JSONArray warningList = JSON.parseArray(data.getData().toString());
                for (ProductBean.RecordsBean pro : productList) {
                    pro.setFlag(0);
                }
                if (warningList.size() > 0) {
                    warningFlag = 1;
                    for (int i = 0; i < warningList.size(); i++) {
                        JSONObject proWarning = warningList.getJSONObject(i);
                        Integer productId = proWarning.getInteger("productId");
                        for (ProductBean.RecordsBean pro : productList) {
                            if (pro.getId() == productId) {
                                pro.setFlag(1);
                            }
                        }
                    }
                } else {
                    warningFlag = 0;
                }
                productAdapter.notifyData();
            }
        });
    }
}
