package com.ygtx.emcs.activity;

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

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockPackingListViewAdapter;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.StockLineModel;
import com.ygtx.emcs.activity.model.StockModel;
import com.ygtx.emcs.activity.model.WmPackage;
import com.ygtx.emcs.activity.model.WmPackageLine;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.comm.Res;
import com.ygtx.emcs.databinding.YgtxStockPackingBinding;
import com.ygtx.emcs.util.Constant;
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.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


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

    private YgtxStockPackingBinding binding;
    private Context context;
    private StockPackingListViewAdapter stockPackingListViewAdapter;
    private final ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private List<String> scanBarcodeList = new ArrayList<>();
    private String out_stock_flag;
    private StockModel stockModel;
    private WmPackage wmPackage;
    private String erpOutstockCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgtxStockPackingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);
        context = this;
        registerReceiver();
        initCommonTop2();
        initView();
        initData();
    }

    private void initData(){
        Constant.packingLineMap.clear();
        out_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "out_stock_flag");
        if(StringUtils.isEmpty(out_stock_flag)){
            ToastUtils.showToast(context, "请设置出库单编码的标识");
            finish();
        }
        erpOutstockCode = getParamString("erpOutstockCode");
        if(!StringUtils.isEmpty(erpOutstockCode)){
            binding.tvOutCode.setText(erpOutstockCode);
            loadErpTask(erpOutstockCode);
        }
        stockPackingListViewAdapter = new StockPackingListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(stockPackingListViewAdapter);
        binding.lvProduct.setOnItemLongClickListener((parent, view, position, id) -> {
            StockLineModel stockLineModel = stockLineList.get(position);
            if(stockLineModel.getPackageNum().intValue()>0) {
                stockLineModel.setPackageNum(stockLineModel.getPackageNum().subtract(BigDecimal.ONE));
                stockPackingListViewAdapter.notifyDataSetChanged();
            }
            return false;
        });
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("CK_20250329002");
//        });
//        binding.tvOutCode.setOnClickListener(view->{
//            receiverTask("0220013310125");
//        });
//        binding.tvOutCode.setOnLongClickListener(view->{
//            receiverTask("060209101J");
//            return false;
//        });
    }

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

        Button 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(StringUtils.isEmpty(erpOutstockCode)){
                ToastUtils.showToast(context, "出库单号不能为空");
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putSerializable("erpOutstockCode", erpOutstockCode);
            toActivity(StockPackageHistoryActivity.class, bundle);
        });

        binding.btnPackage.setOnClickListener(view->{
            if(Constant.packingLineMap.size() == 0){
                ToastUtils.showToast(context, "请扫描装箱的物品");
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putSerializable("stockModel", stockModel);
            bundle.putString("attr1", wmPackage.getAttr1());
            toActivity(StockPackagePrinterActivity.class, bundle);
        });
    }

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

    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        String inCode = binding.tvOutCode.getText().toString();
        if(barcode.startsWith(out_stock_flag)){
            try {
                binding.tvOutCode.setText(barcode);
                erpOutstockCode = barcode;
                loadErpTask(barcode);
            }catch (Throwable ex){
                mylog.error("任务发送异常：", ex);
                ToastUtils.showToast(context, "发送异常");
            }
        }else{
            if(StringUtils.isEmpty(inCode)){
                ToastUtils.showToast(context, "请扫出库单号");
                return;
            }
            checkItem(barcode);
        }
    }

    private void checkItem(String barcode) {
        if(!barcode.contains("$")){
            ToastUtils.showToast(context, "无效的物料标签");
            return;
        }
        String[] values = barcode.split("\\$");
        String itemCode = values[0];
        String stockCode = values[3];
        if(!stockCode.equals(erpOutstockCode)){
            ToastUtils.showToast(context, "物品出库单是"+stockCode);
            return;
        }
        boolean isValid = checkBarcode(barcode);
        if(!isValid){
            return;
        }
        BigDecimal perQty = new BigDecimal(values[1]);
        Optional<StockLineModel> optionalStockLineModel = stockLineList.stream().filter(item -> item.getItemCode().equals(itemCode)).findFirst();
        if (optionalStockLineModel.isPresent()) {
            StockLineModel stockLineModel = optionalStockLineModel.get();
            if(stockLineModel.getTotalPackage()==null){
                stockLineModel.setTotalPackage(BigDecimal.ZERO);
            }
            if(Constant.packingLineMap.containsKey(stockLineModel.getItemCode())){
                StockLineModel lineModel = Constant.packingLineMap.get(stockLineModel.getItemCode());
                if(lineModel != null){
                    BigDecimal bagNum = lineModel.getBagNum();
                    BigDecimal addBagNum = bagNum.add(BigDecimal.ONE);
                    BigDecimal addQty = lineModel.getPackageNum().add(perQty);
                    if(stockLineModel.getTotalPackage() == null){
                        stockLineModel.setTotalPackage(BigDecimal.ZERO);
                    }
                    BigDecimal total = addQty.add(stockLineModel.getTotalPackage());
                    if(total.compareTo(stockLineModel.getOrderQuantity()) > 0){
                        ToastUtils.showToast(context, "已超过出库单数量");
                        return;
                    }
                    lineModel.setBagNum(addBagNum);//包数
                    lineModel.setPackageNum(addQty);//总数
                    lineModel.setPerBag(perQty);
                    stockLineModel = lineModel;
                }
            }else{
                if(stockLineModel.getTotalPackage()
                        .compareTo(stockLineModel.getOrderQuantity()) >= 0){
                    ToastUtils.showToast(context, "已超过出库单数量");
                    return;
                }
                stockLineModel.setBagNum(BigDecimal.ONE);
                stockLineModel.setPerBag(perQty);
                BigDecimal addQty = BigDecimal.ONE.multiply(perQty);
                stockLineModel.setPackageNum(addQty);
            }
            scanBarcodeList.add(barcode);
            Constant.packingLineMap.put(stockLineModel.getItemCode(), stockLineModel);
            stockPackingListViewAdapter.notifyDataSetChanged();
            return;
        }
        ToastUtils.showToast(context, "出库单不存在" + itemCode + "物品");
    }

    private boolean checkBarcode(String barcode){
        if(scanBarcodeList.contains(barcode)){
            ToastUtils.showToast(context, "该二维码已扫过，"+barcode);
            return false;
        }
        return true;
    }

    private void initPackageNum(){
        List<WmPackageLine> packageLineList = wmPackage.getWmPackageLineList();
        stockLineList.forEach(line->{
            Optional<WmPackageLine> optionalWmPackageLine = packageLineList.stream()
                    .filter(item->item.getItemCode().equals(line.getItemCode())).findFirst();
            if(optionalWmPackageLine.isPresent()){
                BigDecimal packageNum = optionalWmPackageLine.get().getQuantityPackage();
                line.setPackageNum(BigDecimal.ZERO);
                line.setBagNum(BigDecimal.ZERO);
                line.setTotalPackage(packageNum);//已打包数
            }
        });
        stockPackingListViewAdapter.notifyDataSetChanged();
    }

    private void loadErpTask(String erpOutstockCode) {
        if(StringUtils.isEmpty(erpOutstockCode)){
            erpOutstockCode = binding.tvOutCode.getText().toString();
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(StringUtils.isEmpty(erpOutstockCode)){
            ToastUtils.showToast(context, "出库单号不能为空");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.PACKAGE_STOCK_OUT_LIST);
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        params.addBodyParameter("isSplit", "0");
        params.addBodyParameter("fromPackage", "1");
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    stockLineList.clear();
                    Constant.packingLineMap.clear();
                    if (rs.getInt("code") == 200) {
                        stockModel = new Gson().fromJson(rs.get("data").toString(), StockModel.class);
                        if(stockModel.getRmsTaskOutstockLineList()!=null) {
                            stockLineList.addAll(stockModel.getRmsTaskOutstockLineList());
                        }
                        if(stockModel.getPackageStatus()!=null && stockModel.getPackageStatus() == 2){
                            binding.btnPackage.setEnabled(false);
                            binding.btnPackage.setBackgroundColor(Color.GRAY);
                            binding.btnPackage.setText("已打包");
                        }else{
                            binding.btnPackage.setEnabled(true);
                            binding.btnPackage.setBackgroundResource(R.drawable.blu);
                            binding.btnPackage.setText("装箱清单");
                        }
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    loadPackage();
                    stockPackingListViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    private void loadPackage() {
        if(StringUtils.isEmpty(erpOutstockCode)){
            erpOutstockCode = binding.tvOutCode.getText().toString();
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.GET_STOCK_PACKAGE);
        params.addBodyParameter("stockCode", erpOutstockCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        wmPackage = new Gson().fromJson(rs.get("data").toString(), WmPackage.class);
                        initPackageNum();
                    }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(StockPackageActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

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

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

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

}