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

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.OrderDetail;
import com.wd.workoffice.bean.event.CheckAddStockEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
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.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 入库申请-销售订单下的坩埚类型
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class AddStockApplyCrucibleAddActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_max_num)
    TextView tvMaxNum;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.et_box_num)
    EditText etBoxNum;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_num)
    TextView tvRemarkNum;
    @BindView(R.id.tv_bottom)
    TextView tvBottom;
    @BindView(R.id.ll_choose_from)
    LinearLayout llChooseFrom;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    private Map<String, Object> param;
    private String orderType;
    private OrderDetail dataBean;
    private List<AddStockChooseBean.RecordsBean> productList;
    private AddStockCrucibleChooseAdapter productAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        WorkUtils.addNumListener(etRemark, tvRemarkNum);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
    }

    @Override
    protected void initData() {
        orderType = getIntent().getStringExtra("orderType");
        productList = new ArrayList<>();
        productAdapter = new AddStockCrucibleChooseAdapter(R.layout.item_add_stock_choose, productList, 1);
        productAdapter.bindToRecyclerView(rvData);
        productAdapter.notifyDataSetChanged();
        param = new HashMap<>();
        param.put("productId", getIntent().getStringExtra("productId"));
        param.put("simpleCode", getIntent().getStringExtra("simpleCode"));
        getNum();
    }

    /**
     * 获取数量
     */
    private void getNum() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().saleOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().purchaseOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().supplierOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().crucibleOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().insideOrderDetail(getIntent().getStringExtra("id"), "1");
        } else {
            observable = RtfUtils.getRtf().insideOrderDetail(getIntent().getStringExtra("id"), "1");
        }
        observable.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;
                }
                dataBean = JSON.parseObject(data.getData().toString(), OrderDetail.class);
                List<OrderDetail.OrderItemsBean> orderItems = dataBean.getOrderItems();
                for (OrderDetail.OrderItemsBean orderItem : orderItems) {
                    if (TextUtils.equals(orderItem.getId(), getIntent().getStringExtra("orderItemId"))) {
                        tvMaxNum.setText(MathUtils.converData(orderItem.getCanInStoreProductSum(), 3));
                    }
                }
            }
        });
    }

    @Override
    protected void initEvent() {
    }


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


    private void submit() {
        String num = tvNum.getText().toString();
        String remark = etRemark.getText().toString();
        String boxCode = etBoxNum.getText().toString();
        if (TextUtils.isEmpty(num)) {
            toast("请输入入库数量");
            return;
        }
        if (dataBean != null) {
            List<OrderDetail.OrderItemsBean> orderItems = dataBean.getOrderItems();
            for (OrderDetail.OrderItemsBean orderItem : orderItems) {
                if (TextUtils.equals(orderItem.getId(), getIntent().getStringExtra("orderItemId"))) {
                    if (new BigDecimal(Double.valueOf(num)).compareTo(new BigDecimal(orderItem.getCanInStoreProductSum())) == 1) {
                        toast(String.format("可申请入库数量最大为%s", MathUtils.converData(orderItem.getCanInStoreProductSum(), 3)));
                        return;
                    }
                }
            }
        }

        param.put("productAmount", num);
        param.put("boxCode", boxCode);
        param.put("orderItemId", getIntent().getStringExtra("orderItemId"));
        param.put("applyRemark", remark);
        coverPro();
        RtfUtils.getRtf().addStockApplyForwardAdd(getIntent().getStringExtra("id"), 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;
                }
                toast("提交申请成功");
                EventBus.getDefault().post(new CheckAddStockEvent());
                finish();
            }
        });
    }

    private void coverPro() {
        List<JSONObject> backList = new ArrayList<>();
        for (AddStockChooseBean.RecordsBean data : productList) {
            JSONObject jsonData = new JSONObject();
            jsonData.put("crucibleId",data.getCrucibleId());
            jsonData.put("fromStockId",data.getStockId());
            jsonData.put("productId",data.getProductId());
            jsonData.put("actionQuantity",data.getChooseNum());
            backList.add(jsonData);
        }
        param.put("stockFromDetails", backList);
    }


    @OnClick({R.id.tv_bottom, R.id.ll_choose_from})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bottom:
                submit();
                break;
            case R.id.ll_choose_from:
                startActivityForResult(AddStockCrucibleChooseActivity.class, 10001,
                        "depId", getIntent().getStringExtra("depId")
                        , "productId", getIntent().getStringExtra("productId")
                        , "pro", JSON.toJSONString(productList));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            List<AddStockChooseBean.RecordsBean> backList = JSON.parseArray(data.getStringExtra("stock")
                    , AddStockChooseBean.RecordsBean.class);
            productList.clear();
            productList.addAll(backList);
            productAdapter.notifyDataSetChanged();
            tvNum.setText(data.getStringExtra("count"));
        }
    }

}
