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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
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.OrderDetail;
import com.wd.workoffice.bean.StockBean;
import com.wd.workoffice.bean.event.CheckUseEvent;
import com.wd.workoffice.bean.event.ModifyCarEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.store.ChooseStockActivity;
import com.wd.workoffice.ui.activity.bat.work.DeviceBuyCarActivity;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
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 UseApplyAddActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_bottom)
    TextView tvBottom;
    @BindView(R.id.et_img_code)
    TextView etImgCode;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_num)
    TextView tvRemarkNum;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.tv_stock_content)
    TextView tvStockContent;
    @BindView(R.id.ll_stock)
    LinearLayout llStock;
    @BindView(R.id.iv_stock_arrow)
    ImageView ivStockArrow;
    private Map<String, Object> param;
    private String orderType;
    private OrderDetail dataBean;
    private StockBean chooseStock;
    private String usedStore;
    private String usedStoreName;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        WorkUtils.addDecimalsListener(etNum);
        WorkUtils.addNumListener(etRemark, tvRemarkNum);

    }

    @Override
    protected void initData() {
        orderType = getIntent().getStringExtra("orderType");
        usedStore = getIntent().getStringExtra("usedStore");
        usedStoreName = getIntent().getStringExtra("usedStoreName");
        changeStockView();
        param = new HashMap<>();
        param.put("productId", getIntent().getStringExtra("productId"));
        param.put("orderItemId", getIntent().getStringExtra("orderItemId"));
        param.put("simpleCode", getIntent().getStringExtra("simpleCode"));
        etImgCode.setText(getIntent().getStringExtra("simpleCode"));
        getNum();
    }


    @Override
    protected void initEvent() {
    }


    /**
     * 获取数量
     */
    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 if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            observable = RtfUtils.getRtf().productOrderDetail(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"))) {
                        tvNum.setText(String.format("最大领用数量(%s)", MathUtils.converData(orderItem.getCanUseProductSum(), 3)));
                    }

                }
                usedStore = dataBean.getUsedStore();
                usedStoreName = dataBean.getUsedStoreName();
                changeStockView();
            }
        });
    }

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


    private void submit() {
        String num = etNum.getText().toString();
        String remark = etRemark.getText().toString();
        param.put("productAmount", num);
        param.put("orderId", getIntent().getStringExtra("id"));
        param.put("applyRemark", remark);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().useApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().usePoApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            observable = RtfUtils.getRtf().useAoApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().useApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        }
        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;
                }
                toast("提交申请成功");
                EventBus.getDefault().post(new CheckUseEvent());
                finish();
            }

        });
    }

    @OnClick({R.id.tv_bottom, R.id.ll_stock})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bottom:
                String num = etNum.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.getCanUseProductSum())) == 1) {
                                toast(String.format("可申请领用数量最大为%s", MathUtils.converData(orderItem.getCanUseProductSum(), 3)));
                                return;
                            }
                        }

                    }
                }

                if (TextUtils.equals(orderType, OrderType.SALE.getCode()) || TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())
                        || TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
                    if (TextUtils.isEmpty(usedStore)) {
                        if (TextUtils.equals(orderType, OrderType.SALE.getCode())){
                            QMUIDialog.MessageDialogBuilder dialog = DialogUtils.okAndCancelDialog(UseApplyAddActivity.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();
                                    addStock();
                                }
                            }).show();
                            return;
                        }
                        addStock();
                    } else {
                        submit();
                    }
                }else{
                    submit();
                }
                break;
            case R.id.ll_stock:
                if (TextUtils.equals(orderType, OrderType.SALE.getCode()) || TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())
                        || TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
                    if (TextUtils.isEmpty(usedStore)) {
                        startActivityForResult(ChooseStockActivity.class, 10001,
                                "siteType", "OUT", "customerId", getIntent().getStringExtra("customerId"));
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (resultCode == 10005) {
                    chooseStock = JSON.parseObject(data.getStringExtra("stock"), StockBean.class);
                    tvStockContent.setText(chooseStock.getName());
                }
                break;
        }
    }

    private void changeStockView() {
        if (TextUtils.equals(orderType, OrderType.SALE.getCode()) || TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())
                || TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            if (TextUtils.isEmpty(usedStore)) {
                ivStockArrow.setVisibility(View.VISIBLE);
            } else {
                ivStockArrow.setVisibility(View.GONE);
                tvStockContent.setText(usedStoreName);
            }
            llStock.setVisibility(View.VISIBLE);
        }
    }

    private void addStock() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("orderId", getIntent().getStringExtra("id"));
        if (chooseStock == null) {
            toast("请选择领用仓库");
            return;
        }
        param.put("usedStore", chooseStock.getId());
        showLoading();
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().soUsedStore(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().poUsedStore(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            observable = RtfUtils.getRtf().aoUsedStore(WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().aoUsedStore(WorkUtils.convertMapToBody(param));
        }
        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;
                }
                submit();
            }
        });
    }
}
