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

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
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.event.CheckReturnEvent;
import com.wd.workoffice.bean.event.CheckSendEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 ReturnAddActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_bottom)
    TextView tvBottom;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.tv_return_type)
    TextView tvReturnType;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.ll_choose_stock)
    LinearLayout llChooseStock;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_num)
    TextView tvRemarkNum;
    @BindView(R.id.tv_max_num)
    TextView tvMaxNum;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    private Map<String, Object> param;
    private String orderType;
    private List<String> typeList = new ArrayList<>();
    private String enterStockType;
    private QMUIDialog.MenuDialogBuilder typeDialog;
    private QMUIDialog.MenuDialogBuilder deptDialog;
    private int chooseType = 0;//1 从现场库退到内库 3 未结算库核  4 现场库退给供应商
    private JSONArray deptList;
    private List<String> deptNameList;
    private Integer chooseDep;
    private OrderDetail dataBean;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        orderType = getIntent().getStringExtra("orderType");
        enterStockType = getIntent().getStringExtra("enterStockType");
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            typeList.add("从现场库退到内库");
            tvReturnType.setText("从现场库退到内库");
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            switch (enterStockType) {
                case "1":
                    typeList.add("从现场库退到内库");
                    typeList.add("未结算库核销");
                    typeList.add("现场库退给供应商");
                    break;
                case "2":
                    typeList.add("未结算库核销");
                    typeList.add("现场库退给供应商");
                    break;
            }
        }
        typeDialog = DialogUtils.listDialog(this);
        typeDialog.addItems(typeList.toArray(new String[typeList.size()]), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvReturnType.setText(typeList.get(which));
                changeView();
                dialog.dismiss();
            }
        });
        deptDialog = DialogUtils.listDialog(this);
        WorkUtils.addDecimalsListener(etNum);
        WorkUtils.addNumListener(etRemark, tvRemarkNum);
    }

    private void changeView() {
        //1 从现场库退到内库 3 未结算库核  4 现场库退给供应商
        String returnType = tvReturnType.getText().toString();
        switch (returnType) {
            case "从现场库退到内库":
                chooseType = 1;
                llChooseStock.setVisibility(View.VISIBLE);
                llMoney.setVisibility(View.GONE);
                break;
            case "未结算库核销":
                chooseType = 3;
                llChooseStock.setVisibility(View.GONE);
                llMoney.setVisibility(View.VISIBLE);
                break;
            case "现场库退给供应商":
                chooseType = 4;
                llChooseStock.setVisibility(View.GONE);
                llMoney.setVisibility(View.GONE);
                break;
            default:
                llChooseStock.setVisibility(View.GONE);
                llMoney.setVisibility(View.GONE);
                break;
        }
        param.put("returnType", chooseType);
    }

    @Override
    protected void initData() {
//        String num = getIntent().getStringExtra("returnNum");
//        tvMaxNum.setText(String.format("*退货最大数量(%s)", num));
        param = new HashMap<>();
        param.put("orderId", getIntent().getStringExtra("id"));
        param.put("productId", getIntent().getStringExtra("productId"));
        param.put("orderItemId", getIntent().getStringExtra("orderItemId"));
        changeView();
        getDept();
        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"))) {
                        if (TextUtils.isEmpty(enterStockType)) {
                            tvMaxNum.setText(String.format("*退货最大数量(%s)", MathUtils.converData(orderItem.getCanUseProductSum(), 3)));
                        } else {
                            String returnNum = TextUtils.equals(enterStockType, "1") ?
                                    orderItem.getCanOutReturnSum() : orderItem.getCanUsedReturnSum();
                            tvMaxNum.setText(String.format("*退货最大数量(%s)", MathUtils.converData(returnNum, 3)));
                        }

                    }
                }
            }
        });
    }


    private void getDept() {
        RtfUtils.getRtf().returnDept(getIntent().getStringExtra("deptId")).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;
                }
                deptList = JSON.parseArray(data.getData().toString());
                deptNameList = new ArrayList<>();
                for (int i = 0; i < deptList.size(); i++) {
                    JSONObject deptData = deptList.getJSONObject(i);
                    deptNameList.add(deptData.getString("name"));
                }
                deptDialog.addItems(deptNameList.toArray(new String[deptNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tvStock.setText(deptNameList.get(which));
                        chooseDep = deptList.getJSONObject(which).getInteger("id");
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    @Override
    protected void initEvent() {
    }


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


    private void submit() {
        String num = etNum.getText().toString();
        String price = etPrice.getText().toString();
        String remark = etRemark.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 (TextUtils.isEmpty(enterStockType)) {
                        if (new BigDecimal(num).compareTo(new BigDecimal(orderItem.getCanUseProductSum())) == 1) {
                            toast(String.format("可申请退货数量最大为%s", MathUtils.converData(orderItem.getCanUseProductSum(), 3)));
                            return;
                        }
                    } else {
                        String returnNum = TextUtils.equals(enterStockType, "1") ?
                                orderItem.getCanOutReturnSum() : orderItem.getCanUsedReturnSum();
                        if (new BigDecimal(num).compareTo(new BigDecimal(returnNum)) == 1) {
                            toast(String.format("可申请退货数量最大为%s", MathUtils.converData(returnNum, 3)));
                            return;
                        }

                    }

                }
            }
        }
        if (TextUtils.isEmpty(price) && chooseType == 3) {
            toast("请输入核销金额");
            return;
        }
        param.put("productAmount", num);
        param.put("writeOff", price);
        param.put("applyRemark", remark);
        if (chooseType == 1) {
            if (chooseDep == null) {
                toast("请选择退货仓库");
                return;
            }
            param.put("backStockId", chooseDep);
        }
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().returnSoAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().returnPoAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().returnSoAdd(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 CheckReturnEvent());
                finish();
            }
        });
    }


    @OnClick({R.id.tv_bottom, R.id.ll_type, R.id.ll_choose_stock})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bottom:
                submit();
                break;
            case R.id.ll_type:
                typeDialog.show();
                break;
            case R.id.ll_choose_stock:
                deptDialog.show();
                break;
        }
    }

}
