package com.ygtx.emcs.activity;

import static com.ygtx.emcs.comm.BaseApplication.mScanManager;
import static com.ygtx.emcs.util.Constant.PRINTER_ITEM_SEL_KEY;
import static com.ygtx.emcs.util.Constant.SEL_BATCH_CODE;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.model.DictModel;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.MaterialStockModel;
import com.ygtx.emcs.activity.model.StockLineAreaModel;
import com.ygtx.emcs.activity.model.StockLineModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.Res;
import com.ygtx.emcs.databinding.YgtxBindItemBinding;
import com.ygtx.emcs.databinding.YgtxBindOutItemBinding;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.DateUtil;
import com.ygtx.emcs.util.HttpsUtil;
import com.ygtx.emcs.util.MyProgress;
import com.ygtx.emcs.util.StringUtils;
import com.ygtx.emcs.util.ToastUtils;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class StockOutBindActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(StockOutBindActivity.class);

    private YgtxBindOutItemBinding binding;
    private Context context;
    private List<View> itemAreaView = new ArrayList<>();
    private StockLineModel lineModel;
    private String erpOutstockCode;
    private Button submit;
    private List<MaterialStockModel> materialStockModels = new ArrayList<>();
    private List<DictModel> dictModelList = new ArrayList<>();
    private List<MaterialStockModel> batchModelList = new ArrayList<>();
    private BigDecimal totalQty;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow1;
    private String fileName;
    private String batchCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgtxBindOutItemBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);
        context = this;
        if(Constant.user == null){
            ToastUtils.showToast(context, "请先登录");
            finish();
        }
        registerReceiver();
        initCommonTop2();
        initView();
        initData();
    }

    private void initData(){
        lineModel = (StockLineModel)getParamSerializable("stockLine");
        erpOutstockCode = getParamString("erpOutstockCode");
        String from = getParamString("from");
//        if("1".equals(from)){
//            binding.llPrinter.setVisibility(View.GONE);
//        }
        binding.etItemCode.setText(lineModel.getItemCode());
        binding.etItemName.setText(lineModel.getItemName());
        binding.etItemSpec.setText(lineModel.getSpecification());
        binding.tvQty.setText(lineModel.getQuantity());
        if("2".equals(lineModel.getStatus())){
            submit.setVisibility(View.GONE);
            binding.btAdd.setVisibility(View.GONE);
            if(("1".equals(lineModel.getOutCheck())
                    &&"1".equals(lineModel.getAutomatic()))
                    || "0".equals(lineModel.getAutomatic())){
                binding.btnChange.setVisibility(View.VISIBLE);
            }
            searchLineTask(lineModel.getLineId());
        }else{
            searchStock(lineModel.getItemCode(), lineModel.getAutomatic());
            totalQty = new BigDecimal(lineModel.getQuantity());
        }
        if("1".equals(lineModel.getAutomatic())){
            if("2".equals(lineModel.getStatus())
                    ||"1".equals(lineModel.getStatus())){
                submit.setVisibility(View.GONE);
            }else{
                submit.setText("出库");
            }
            if(!"2".equals(lineModel.getStatus())){
                binding.llPrinter.setVisibility(View.GONE);
            }
            if(lineModel.getOutMode()!=null
                    && lineModel.getOutMode() == 1){
                binding.tvBatchCode.setText(lineModel.getErpBatchCode());
            }
            binding.tvBoxCode.setText(lineModel.getBoxCode());
        }else{
            binding.llBatchCode.setVisibility(View.GONE);
            binding.llBatchCodeLine.setVisibility(View.GONE);
            binding.llBoxCode.setVisibility(View.GONE);
            binding.llBoxCodeLine.setVisibility(View.GONE);
        }
//        if("1".equals(lineModel.getIsSplit())){
//            binding.llPrinter.setVisibility(View.GONE);
//        }
        binding.llBatchCode.setOnClickListener(this::selBatchCodeLabel);
        searchBatchLabel();
        searchItemLabel();

// ========================test========================
//        binding.etItemName.setOnClickListener(v->{
//            receiverTask("B0007");
//        });
//        binding.etItemCode.setOnClickListener(v->{
//            receiverTask("B0008");
//        });
// ========================test========================
    }

    private void initView(){
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(view -> {
            finish();
        });

        binding.btAdd.setOnClickListener(v -> {
            addAreaItem();
        });

        binding.btnChange.setOnClickListener(v->{
            Bundle bundle = new Bundle();
            bundle.putString("boxCode", lineModel.getBoxCode());
            bundle.putString("from", "1");
            toActivity(StockChangeActivity.class, bundle);
        });

        submit = findViewById(R.id.c_iv_common_submit);
        submit.setBackgroundColor(Res.getColor("transparent"));
        submit.setTextColor(Res.getColor("white"));
        submit.setVisibility(View.VISIBLE);
        submit.setText("提交");
        submit.setOnClickListener(view -> {
            if("1".equals(lineModel.getAutomatic())){
                sendStockOut();
                return;
            }
            BigDecimal outOrderQty = calculateQty();
            if(outOrderQty.compareTo(totalQty) > 0){
                ToastUtils.showToast(context, "当前物品出库数量超过出库单数量");
                return;
            }
            if(outOrderQty.compareTo(totalQty) < 0){
                ToastUtils.showToast(context, "请按出库单数量出库");
                return;
            }
            String areaValue = getItemAreaValue();
            saveStockOut(areaValue);
        });

        binding.btnPrinter.setOnClickListener(v->{
            StockLineModel stockLineModel = new StockLineModel();
            stockLineModel.setLineId(lineModel.getLineId());
            String perBag = binding.etPerBag.getText().toString();
            if(StringUtils.isEmpty(perBag)){
                perBag = "1";
            }
            stockLineModel.setPerBag(new BigDecimal(perBag));
            printItem(stockLineModel);
        });

        binding.btnSelItem.setOnClickListener(this::selPrinterLabel);
    }

    private View addAreaItem(){
        LayoutInflater inflater = LayoutInflater.from(this);
        View areaView = inflater.inflate(R.layout.ygtx_bind_out_item_area, null);
        binding.llBindArea.addView(areaView);
        itemAreaView.add(areaView);
        return areaView;
    }

    private void setItemAreaValue(List<StockLineAreaModel> stockLineAreaList){
        for (StockLineAreaModel lineAreaModel:stockLineAreaList){
            View areaView = addAreaItem();
            setItemValue(lineAreaModel, areaView);
        }
    }

    private void setNewItemAreaValue(List<MaterialStockModel> materialStockModelList){
        for (MaterialStockModel lineAreaModel:materialStockModelList){
            View areaView = addAreaItem();
            setStockItemValue(lineAreaModel, areaView);
        }
    }

    private void setItemValue(StockLineAreaModel lineAreaModel, View areaView){
        EditText qty = areaView.findViewById(R.id.et_qty);
        TextView areaCode = areaView.findViewById(R.id.et_areaCode);
        TextView tv_batch_code = areaView.findViewById(R.id.tv_batch_code);
        TextView total = areaView.findViewById(R.id.tv_total);
        TextView stockTitle = areaView.findViewById(R.id.tv_stock_title);
        TextView tv_boxCode = areaView.findViewById(R.id.tv_box_code);
        LinearLayout ll_change = areaView.findViewById(R.id.ll_change);
        Button btn_change = areaView.findViewById(R.id.btn_change);
        btn_change.setOnClickListener(v->{
            Bundle bundle = new Bundle();
            bundle.putString("boxCode", lineAreaModel.getAreaCode());
            bundle.putString("from", "1");
            toActivity(StockChangeActivity.class, bundle);
        });
        if("2".equals(lineModel.getStatus())){
            qty.setEnabled(false);
            ll_change.setVisibility(View.VISIBLE);
            stockTitle.setText("原库存:");
        }else{
            ll_change.setVisibility(View.GONE);
            stockTitle.setText("库存:");
        }
        total.setText(lineAreaModel.getStockQuantity());
        areaCode.setText(lineAreaModel.getAreaCode());
        tv_batch_code.setText(lineAreaModel.getBatchCode());
        qty.setText(lineAreaModel.getQuantity());
        tv_boxCode.setText(lineAreaModel.getBoxCode());
    }

    private void setStockItemValue(MaterialStockModel stockModel, View areaView){
        EditText qty = areaView.findViewById(R.id.et_qty);
        TextView tv_qty_tips = areaView.findViewById(R.id.tv_qty_tips);
        TextView areaCode = areaView.findViewById(R.id.et_areaCode);
        TextView tv_batch_code = areaView.findViewById(R.id.tv_batch_code);
        TextView total = areaView.findViewById(R.id.tv_total);
        TextView stockTitle = areaView.findViewById(R.id.tv_stock_title);
        TextView boxCodeTv = areaView.findViewById(R.id.tv_box_code);
        LinearLayout ll_change = areaView.findViewById(R.id.ll_change);
        if("2".equals(lineModel.getStatus())){
            qty.setEnabled(false);
            ll_change.setVisibility(View.VISIBLE);
            stockTitle.setText("原库存:");
        }else{
            ll_change.setVisibility(View.GONE);
            stockTitle.setText("库存:");
        }
        String quantity = stockModel.getQuantityOnhand().toString();
        total.setText(quantity);
        if(qty.getVisibility() != View.GONE){
            if(StringUtils.isEmpty(stockModel.getAreaCode())){
                qty.setEnabled(false);
                areaCode.setTextColor(Color.RED);
                areaCode.setText("不在库位上");
            }else if(Constant.XBK.equals(stockModel.getAreaCode())){
                qty.setEnabled(false);
                areaCode.setTextColor(Color.RED);
                areaCode.setText("在线边上");
            }else{
                areaCode.setTextColor(Color.GRAY);
                qty.setEnabled(true);
                areaCode.setText(stockModel.getAreaCode());
            }
        }
        if("1".equals(lineModel.getAutomatic())){
            qty.setVisibility(View.GONE);
            tv_qty_tips.setVisibility(View.GONE);
        }
        areaCode.setTag(stockModel.getMaterialStockId());
        tv_batch_code.setText(stockModel.getBatchCode());
        areaView.setTag(stockModel.getMaterialStockId());
        boxCodeTv.setText(stockModel.getAttr1());
    }

    private String getItemAreaValue(){
        StringBuilder val = new StringBuilder();
        String rs = null;
        for (View view:itemAreaView){
            EditText qty = view.findViewById(R.id.et_qty);
            String outQty = qty.getText().toString();
            if(StringUtils.isEmpty(outQty)){
                continue;
            }
            if(Double.parseDouble(outQty) <= 0){
                continue;
            }
            TextView total = view.findViewById(R.id.tv_total);
            TextView areaCode = view.findViewById(R.id.et_areaCode);
            TextView boxCode = view.findViewById(R.id.tv_box_code);
            val.append(",").append(areaCode.getText().toString())
                    .append("|")
                    .append(total.getText().toString())
                    .append("|")
                    .append(qty.getText().toString())
                    .append("|")
                    .append(areaCode.getTag().toString())
                    .append("|")
                    .append(boxCode.getText().toString());
        }
        if(val.length() > 0){
            rs = val.substring(1);
        }
        return rs;
    }

    private void registerReceiver() {
        if (mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            if(Constant.MODEL.contains("ET")) {
                filter.addAction(ET_SCAN_ACTION);
            }
            registerReceiver(mReceiver, filter);
        }
    }

    private void updateStockOutLine() throws Throwable {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(lineModel.getLineId()==null){
            ToastUtils.showToast(context, "出库单没有生成");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.UPDATE_STOCK_OUT_LINE);
        params.addBodyParameter("outstockId", lineModel.getOutstockId().toString());
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        if("随机".equals(batchCode)){
            params.addBodyParameter("outMode", "0");
        }else{
            params.addBodyParameter("outMode", "1");
            params.addBodyParameter("erpBatchCode", batchCode);
        }
        params.addBodyParameter("operator", Constant.user.getLoginName());
        x.http().request(HttpMethod.PUT, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        mylog.info("更新出库方式成功");
                        ToastUtils.showToast(context, "切换成功");
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
                submit.setEnabled(true);
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void sendStockOut(){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(lineModel.getLineId()==null){
            ToastUtils.showToast(context, "出库单没有生成");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.SEND_STOCK_OUT);
        params.addBodyParameter("outstockId", lineModel.getOutstockId().toString());
        params.addBodyParameter("outstockLineId", lineModel.getLineId().toString());
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        params.addBodyParameter("fromType", "0");
        params.addBodyParameter("taskType", "2");
        params.addBodyParameter("path", "/ckgl");
        params.addBodyParameter("outstockBatch", "1");
        params.addBodyParameter("operator", Constant.user.getLoginName());
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        new Handler().postDelayed(()->{
                            EventMessage message = new EventMessage(3, erpOutstockCode);
                            EventBus.getDefault().post(message);
                            finish();
                        }, 100);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
                submit.setEnabled(true);
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void saveStockOut(String areaValue){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.SAVE_OUT_STOCK_AREA);
        if(lineModel.getLineId()==null){
            ToastUtils.showToast(context, "出库单没有生成");
            return;
        }
        if(StringUtils.isEmpty(areaValue)){
            ToastUtils.showToast(context, "没有可出库的物品");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        params.addBodyParameter("areaValue", areaValue);
        params.addBodyParameter("operator", Constant.user.getLoginName());
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        new Handler().postDelayed(()->{
                            EventMessage message = new EventMessage(3, erpOutstockCode);
                            EventBus.getDefault().post(message);
                            finish();
                        }, 100);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
                submit.setEnabled(true);
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void searchLineTask(Long lineId) {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.ERP_OUT_STOCK_AREA_LIST);
        params.addBodyParameter("lineId", lineId.toString());
        params.addBodyParameter("pageNum", "1");
        params.addBodyParameter("pageSize", "100");
        params.addBodyParameter("orderByColumn", "create_time");
        params.addBodyParameter("isAsc", "desc");
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    List<StockLineAreaModel> stockLineAreaModels = new ArrayList<>();
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<StockLineAreaModel>>() {}.getType();
                        int total = rs.getInt("total");
                        if(total == 0){
                            mylog.info("没有记录");
                            return;
                        }
                        stockLineAreaModels = new Gson().fromJson(rs.get("rows").toString(), rds);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    if(stockLineAreaModels.size()> 0){
                        binding.llBindArea.removeAllViews();
                        setItemAreaValue(stockLineAreaModels);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void searchStock(String itemCode, String automatic) {
       if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.STOCK_LIST_STOCK);
        params.addBodyParameter("itemCode", itemCode);
        params.addBodyParameter("automatic", automatic);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<MaterialStockModel>>() {}.getType();
                        materialStockModels = new Gson().fromJson(rs.get("data").toString(), rds);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    if(materialStockModels.size()> 0){
                        setNewItemAreaValue(materialStockModels);
                        binding.tvNoStock.setVisibility(View.GONE);
                    }else{
                        binding.tvNoStock.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }


    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        if("2".equals(lineModel.getStatus())){
            return;
        }
        if(!"1".equals(lineModel.getAutomatic())){
            checkAreaCode(barcode);
        }
    }

    private void checkAreaCode(String areaCode){
        if(materialStockModels.isEmpty()){
            return;
        }
        BigDecimal outOrderQty = calculateQty();
        if(outOrderQty.compareTo(totalQty) >= 0){
            ToastUtils.showToast(context, "当前出库数量超过出库单数量");
            return;
        }
        List<MaterialStockModel> materialStockModels = getMaterialStock(areaCode);
        if(materialStockModels.size() == 0){
            ToastUtils.showToast(context, "该库位上没有需要的物品");
            return;
        }
        View areaView = null;
        MaterialStockModel materialStockModel1 = null;
        for (MaterialStockModel materialStockModel:materialStockModels) {
            areaView = getAreaView(materialStockModel.getMaterialStockId());
            if (areaView == null) {
                continue;
            }
            EditText qtyET = areaView.findViewById(R.id.et_qty);
            if(qtyET.getVisibility() == View.GONE){
                ToastUtils.showToast(context, "该为位不可用");
                continue;
            }
            String qty = qtyET.getText().toString();
            if(StringUtils.isEmpty(qty)){
                materialStockModel1 = materialStockModel;
                break;
            }
        }
        if (areaView == null || materialStockModel1 == null) {
            ToastUtils.showToast(context, "库位码不可用");
            return;
        }

        BigDecimal stockQty = materialStockModel1.getQuantityOnhand();
        String orderQty = totalQty.subtract(outOrderQty).toString();
        EditText qtyET = areaView.findViewById(R.id.et_qty);
        if(stockQty.compareTo(totalQty) == 0){
            qtyET.setText(orderQty);
        }
        else if(stockQty.compareTo(totalQty) > 0){
            qtyET.setText(orderQty);
        }else{
            String outStockQty = stockQty.toString();
            qtyET.setText(outStockQty);
        }
    }

    private BigDecimal calculateQty(){
        BigDecimal inQty = BigDecimal.ZERO;
        for (View view:itemAreaView){
            EditText qtyET = view.findViewById(R.id.et_qty);
            String qty = qtyET.getText().toString();
            if(StringUtils.isEmpty(qty)){
                continue;
            }
            inQty = inQty.add(new BigDecimal(qty));
        }
        return inQty;
    }

    private List<MaterialStockModel> getMaterialStock(String areaCode){
        List<MaterialStockModel> materialStockModelList = new ArrayList<>();
        for (MaterialStockModel materialStockModel:materialStockModels){
           if(areaCode.equals(materialStockModel.getAreaCode())){
               materialStockModelList.add(materialStockModel);
           }
        }
        return materialStockModelList;
    }

    private View getAreaView(Long materialId){
        for (View areaView:itemAreaView){
            if(materialId==null){
                return null;
            }
            if(materialId.equals(areaView.getTag())){
                return areaView;
            }
        }
        return null;
    }


    private void printItem(StockLineModel stockLineModel) {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在发送数据");
        RequestParams params = httParams(Constant.PRINTER_ITEM);
        params.addBodyParameter("lineId", stockLineModel.getLineId().toString());
        params.addBodyParameter("perBag", stockLineModel.getPerBag().toString());
        params.addBodyParameter("operator", Constant.user.getLoginName());
        params.addBodyParameter("fileName", fileName);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        ToastUtils.showToast(context, "打印成功");
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void searchItemLabel() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.PRINTER_ITEM_SEL+"/" + PRINTER_ITEM_SEL_KEY);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<DictModel>>() {}.getType();
                        dictModelList = new Gson().fromJson(rs.get("data").toString(), rds);
                        if(dictModelList.isEmpty()){
                            ToastUtils.showToast(context, "没有配置标签文件");
                            return;
                        }
                        if(StringUtils.isEmpty(fileName) && dictModelList.size()>0){
                            String label = dictModelList.get(0).getDictLabel();
                            if(label!=null && label.contains(".")){
                                label = label.split("\\.")[0];
                                binding.btnSelItem.setText(label);
                            }else{
                                binding.btnSelItem.setText(label);
                            }
                            fileName = dictModelList.get(0).getDictValue();
                        }
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void searchBatchLabel() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(SEL_BATCH_CODE);
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<MaterialStockModel>>() {}.getType();
                        batchModelList = new Gson().fromJson(rs.get("data").toString(), rds);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    public void selPrinterLabel(View view){
        List<Map<String,String>> params = new ArrayList<>();
        if(!dictModelList.isEmpty()){
            dictModelList.forEach(item->{
                Map<String,String> param = new HashMap<>();
                param.put("name", item.getDictLabel());
                param.put("value", item.getDictValue());
                params.add(param);
            });
        }
        View popup_list_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_list_view,null);
        ListView mListView = popup_list_view.findViewById(R.id.lv_data);
        Button itemCancel = popup_list_view.findViewById(R.id.bt_item_cancel);
        itemCancel.setOnClickListener(v -> {
            if(popupWindow!=null){
                popupWindow.dismiss();
                setBackgroundAlpha(1.0f);
            }
        });
        mListView.setBackgroundResource(R.color.white);
        SimpleAdapter simplead = new SimpleAdapter(this, params,
                R.layout.popupwindow_list_item, new String[] { "name"},
                new int[] {R.id.tv_msg});
        mListView.setAdapter(simplead);
        mListView.setOnItemClickListener((parent, view1, position, id) -> {
            try {
                String value = params.get(position).get("value");
                String name = params.get(position).get("name");
                if(name!=null) {
                    if (name.contains(".")) {
                        name = name.split("\\.")[0];
                    }
                    binding.btnSelItem.setText(name);
                }
                fileName = value;
                popupWindow.dismiss();
                setBackgroundAlpha(1.0f);
            }catch (Exception ex){
                mylog.error("选择标签异常", ex);
            }
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow.setContentView(popup_list_view);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        setBackgroundAlpha(0.5f);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    public void selBatchCodeLabel(View view){
        if("2".equals(lineModel.getStatus())
                ||"1".equals(lineModel.getStatus())){
            return;
        }
        List<String> params1 = new ArrayList<>();
        params1.add("随机");
        if(!batchModelList.isEmpty()){
            batchModelList.forEach(item->{
                params1.add(item.getBatchCode());
            });
        }
        View popup_list_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_list_view,null);
        ListView mListView = popup_list_view.findViewById(R.id.lv_data);
        Button itemCancel = popup_list_view.findViewById(R.id.bt_item_cancel);
        Button itemOk = popup_list_view.findViewById(R.id.bt_item_ok);
        itemOk.setVisibility(View.VISIBLE);
        itemCancel.setOnClickListener(v -> {
            if(popupWindow1!=null){
                popupWindow1.dismiss();
                setBackgroundAlpha(1.0f);
            }
        });
        itemOk.setOnClickListener(v->{
            try {
                batchCode = "";
                SparseBooleanArray checked = mListView.getCheckedItemPositions();
                for (int i = 0; i < checked.size(); i++) {
                    if (checked.valueAt(i)) {
                        int position = checked.keyAt(i);
                        String selectedItem = params1.get(position);
                        batchCode +=  "," + selectedItem;
                    }
                }
                if(!StringUtils.isEmpty(batchCode)){
                    batchCode = batchCode.substring(1);
                }
                binding.tvBatchCode.setText(batchCode);
                updateStockOutLine();
            }catch (Throwable ex){
                mylog.error("选择批号异常", ex);
            }
            popupWindow1.dismiss();
            setBackgroundAlpha(1.0f);
        });
        mListView.setBackgroundResource(R.color.white);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_list_item_multiple_choice,
                params1);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener((parent, v, position, id) -> {
            if(position == 0) {
                for (int i = 0; i < mListView.getCount(); i++) {
                    mListView.setItemChecked(i, false);
                }
                mListView.setItemChecked(position, true);
            }else{
                mListView.setItemChecked(0, false);
            }
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow1 = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow1.setContentView(popup_list_view);
        popupWindow1.setOutsideTouchable(false);
        popupWindow1.setFocusable(false);
        popupWindow1.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        setBackgroundAlpha(0.5f);
        popupWindow1.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    @Override
    protected String getCommonTopTitle() {
        return "出库库位";
    }

    @Override
    protected int getCommonTopICO() {
        return 0;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void onReceiveMsg(EventMessage message){
        if(message.getType() == 4){
            searchLineTask(lineModel.getLineId());
        }
    }
}