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.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.StockPackingPrintetViewAdapter;
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.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.comm.Res;
import com.ygtx.emcs.databinding.YgtxStockPackingPrinterBinding;
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.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


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

    private YgtxStockPackingPrinterBinding binding;
    private Context context;
    private StockPackingPrintetViewAdapter stockPackingPrintetViewAdapter;
    private final ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private String attr1;
    private StockModel stockModel;
    private Button submit;

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

    private void initData(){
        attr1 = getParamString("attr1");
        stockModel = (StockModel)getParamSerializable("stockModel");
        binding.tvOutCode.setText(stockModel.getErpOutstockCode());
        binding.tvPackageIndex.setText(attr1);
        stockLineList.clear();
        stockLineList.addAll(Constant.packingLineMap.values());
        stockPackingPrintetViewAdapter = new StockPackingPrintetViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(stockPackingPrintetViewAdapter);
    }

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

        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 -> {
            printItem();
        });
    }

    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) {

    }

    private void printItem() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(stockLineList.isEmpty()){
            ToastUtils.showToast(context, "没有可以打印的清单物品");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在发送数据");
        RequestParams params = httParams(Constant.PRINTER_PACKAGE);
        params.addParameter("stockCode", stockModel.getErpOutstockCode());
        params.addParameter("stockId", stockModel.getOutstockId());
        params.addParameter("wmPackageLineList", stockLineList);
        params.addParameter("attr1", attr1);
        params.addParameter("inspector", Constant.user.getLoginName());
        params.addParameter("inspectorName", Constant.user.getNickName());
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        ToastUtils.showToast(context, "打印成功");
                        EventMessage message = new EventMessage(4, "刷新打包出库单");
                        EventBus.getDefault().post(message);
                        Constant.packingLineMap.clear();
                        finish();
                    }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(StockPackagePrinterActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
                submit.setEnabled(true);
            }

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


    @Override
    protected String getCommonTopTitle() {
        return "装箱清单";
    }

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

}