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.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockPackingHistoryViewAdapter;
import com.ygtx.emcs.activity.adapter.StockPackingListViewAdapter;
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.databinding.YgtxStockOutAddBinding;
import com.ygtx.emcs.databinding.YgtxStockPackingHistoryBinding;
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 StockPackageHistoryActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(StockInActivity.class);

    private YgtxStockPackingHistoryBinding binding;
    private Context context;
    private StockPackingHistoryViewAdapter stockPackingHistoryViewAdapter;
    private List<WmPackage> wmPackageList = new ArrayList<>();
    private String erpOutstockCode;

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

    private void initData(){
        erpOutstockCode = getParamString("erpOutstockCode");
        if(!StringUtils.isEmpty(erpOutstockCode)){
            binding.tvOutCode.setText(erpOutstockCode);
            loadErpTask(erpOutstockCode);
        }
        stockPackingHistoryViewAdapter = new StockPackingHistoryViewAdapter(wmPackageList, context);
        binding.lvBox.setAdapter(stockPackingHistoryViewAdapter);
        binding.lvBox.setOnItemClickListener((parent, view, position, id) -> {
            WmPackage wmPackage = wmPackageList.get(position);
            toPackageLine(wmPackage);
        });
    }

    private void toPackageLine(WmPackage wmPackage){
        Bundle bundle = new Bundle();
        bundle.putSerializable("packageId", wmPackage.getPackageId());
        toActivity(StockPackageHistoryItemActivity.class, bundle);
    }

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

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

    private void loadErpTask(String erpOutstockCode) {
        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.LIST_PACKAGE);
        params.addBodyParameter("stockCode", erpOutstockCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    wmPackageList.clear();
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<WmPackage>>() {}.getType();
                        List<WmPackage> packageList = new Gson().fromJson(rs.get("data").toString(), rds);
                        wmPackageList.addAll(packageList);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    stockPackingHistoryViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    @Override
    protected String getCommonTopTitle() {
        return "装箱记录";
    }

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

}