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.StockItemViewAdapter;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.MaterialStockModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.databinding.YgtxStockItemBinding;
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.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.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


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

    private YgtxStockItemBinding binding;
    private Context context;
    private StockItemViewAdapter stockItemViewAdapter;
    private ArrayList<MaterialStockModel> materialStockModels = new ArrayList<>();
    private String areaCode;

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

    private void initData(){
        areaCode = getParamString("areaCode");
        String from = getParamString("from");
        if(!StringUtils.isEmpty(areaCode)){
            binding.tvInCode.setText(areaCode);
            loadErpTask(areaCode);
        }
        if("1".equals(from)){
            binding.tvScanTips.setVisibility(View.GONE);
        }
        stockItemViewAdapter = new StockItemViewAdapter(materialStockModels, context);
        binding.lvProduct.setAdapter(stockItemViewAdapter);
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("125030402856");
//        });
//        binding.tvInCode.setOnClickListener(view->{
//            receiverTask("11182010258");
//        });
    }

    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);
        binding.tvInCode.setText(barcode);
        loadErpTask(barcode);
    }

    private void loadErpTask(String searchCode) {
        if(StringUtils.isEmpty(searchCode)){
            searchCode = binding.tvInCode.getText().toString();
        }
        if(StringUtils.isEmpty(searchCode)){
            ToastUtils.showToast(context, "库位号不能为空");
            return;
        }
        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", searchCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    materialStockModels.clear();
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<MaterialStockModel>>() {}.getType();
                        List<MaterialStockModel> stockModels = new Gson().fromJson(rs.get("data").toString(), rds);
                        materialStockModels.addAll(stockModels);
                        stockItemViewAdapter.notifyDataSetChanged();
                    }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(StockItemActivity.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;
    }

}