package com.ygtx.emcs.activity;

import static com.ygtx.emcs.comm.BaseApplication.mScanManager;

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.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockPackingItemViewAdapter;
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.Res;
import com.ygtx.emcs.databinding.YgtxStockOutAddBinding;
import com.ygtx.emcs.databinding.YgtxStockPackingHistoryListBinding;
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.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


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

    private YgtxStockPackingHistoryListBinding binding;
    private Context context;
    private StockPackingItemViewAdapter stockPackingItemViewAdapter;
    private final ArrayList<WmPackageLine> wmPackageLines = new ArrayList<>();
    private StockModel stockModel;
    private String packageId;
    private Button submit;

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

    private void initData(){
        packageId = getParamString("packageId");
        stockPackingItemViewAdapter = new StockPackingItemViewAdapter(wmPackageLines, context);
        binding.lvProduct.setAdapter(stockPackingItemViewAdapter);
        loadErpTask();
    }

    private void loadErpTask() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.PACKAGE_ITEM_LIST);
        params.addBodyParameter("packageId", packageId);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    wmPackageLines.clear();
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<WmPackageLine>>() {}.getType();
                        List<WmPackageLine> packageList = new Gson().fromJson(rs.get("data").toString(), rds);
                        wmPackageLines.addAll(packageList);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    stockPackingItemViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    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);
        }
    }

    private void printItem() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(wmPackageLines.isEmpty()){
            ToastUtils.showToast(context, "没有可以打印的清单物品");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在发送数据");
        RequestParams params = httParams(Constant.PRINTER_PACKAGE);
        params.addParameter("packageId", packageId);
        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, "打印成功");
                    }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(StockPackageHistoryItemActivity.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
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
    }

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

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

}