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.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
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.StockInListViewAdapter;
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.YgtxStockInAddBinding;
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.util.ArrayList;
import java.util.Optional;


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

    private YgtxStockInAddBinding binding;
    private Context context;
    private StockInListViewAdapter stockInListViewAdapter;
    private ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private StockModel stockModel;
    private String in_stock_flag;
    private String from;
    private String erpInstockCode;
    private boolean isSubmit = true;
    private boolean isResumed = false;

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

    private void initData(){
        erpInstockCode = getParamString("erpInstockCode");
        if(!StringUtils.isEmpty(erpInstockCode)){
            binding.tvInCode.setText(erpInstockCode);
            loadErpTask(1);
        }
        stockInListViewAdapter = new StockInListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(stockInListViewAdapter);
        binding.lvProduct.setOnItemClickListener((parent, view, position, id) -> {
            StockLineModel stockLineModel = stockLineList.get(position);
            stockIn(stockLineModel);
        });

        in_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "in_stock_flag");
        if(StringUtils.isEmpty(in_stock_flag)){
            ToastUtils.showToast(context, "请设置入库单编码的标识");
            finish();
        }
        binding.tvScanTips.setOnClickListener(view->{
            loadErpTask(1);
        });
//=====================test=====================
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("RK_250510001");
//        });
//        binding.tvInCode.setOnClickListener(view->{
//            receiverTask("11182010266");
//        });
//=====================test=====================
    }

    private void stockIn(StockLineModel stockLineModel){
        //查询时，只显示完成的入库单物品
        if("1".equals(from) && !"2".equals(stockLineModel.getStatus())){
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("erpInstockCode", stockModel.getErpInstockCode());
        bundle.putSerializable("stockLine", stockLineModel);
        toActivity(StockInBindActivity.class, bundle);
    }

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

        from = getParamString("from");
        if("1".equals(from)){
            binding.tvScanTips.setVisibility(View.GONE);
            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(stockModel!=null){
                    syncErp();
                }
            });
        }
        if(!"1".equals(from)) {
            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 -> {
                toActivity(StockInActivity.class);
            });
        }
    }

    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);
        if("1".equals(from)) {
           return;
        }
        String inCode = binding.tvInCode.getText().toString();
        if(barcode.startsWith(in_stock_flag)) {
            try {
                binding.tvInCode.setText(barcode);
                erpInstockCode = barcode;
                loadErpTask(1);
            } 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) {
        StockLineModel selItem = findItem(barcode);
        if(selItem !=null){
            stockIn(selItem);
            return;
        }
        ToastUtils.showToast(context, "入库单不存在" + barcode + "物品");
    }

    private StockLineModel findItem(String barcode){
        StockLineModel selItem = null;
        StockLineModel selItem1 = null;
        int i=0;
        int j = 0;
        for(;i<stockLineList.size();i++){
            StockLineModel item = stockLineList.get(i);
            stockLineList.forEach(lineItem->lineItem.setSel("0"));
            if(item.getItemCode().equals(barcode) && StringUtils.isEmpty(item.getBoxCode())){
                selItem = item;
                selItem.setSel("1");
                break;
            }
            if(item.getItemCode().equals(barcode) && selItem1 == null){
                selItem1 = item;
                selItem1.setSel("1");
                j = i;
            }
        }
        if(selItem == null){
            selItem = selItem1;
            i = j;
        }
        stockInListViewAdapter.notifyDataSetChanged();
        if(selItem!=null){
            binding.lvProduct.smoothScrollToPosition(i, 3);
            binding.lvProduct.smoothScrollToPositionFromTop(i, 0, 500);
        }
        return selItem;
    }

    private void loadErpTask(int from) {
        if(StringUtils.isEmpty(erpInstockCode)){
            erpInstockCode = binding.tvInCode.getText().toString();
        }
        if(StringUtils.isEmpty(erpInstockCode)){
            ToastUtils.showToast(context, "入库单号不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(!isSubmit){
            ToastUtils.showToast(context, "请稍候!!!");
            return;
        }
        isSubmit = false;
        MyProgress myProgress = MyProgress.getInstance();
        if(from != 0) {
            myProgress.show(context, "提示", "正在加载");
        }
        RequestParams params = httParams(Constant.ERP_IN_STOCK);
        params.addBodyParameter("erpInstockCode", erpInstockCode);
//        params.addBodyParameter("isAutomatic", "0");
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    stockLineList.clear();
                    if (rs.getInt("code") == 200) {
                        stockModel = new Gson().fromJson(rs.get("data").toString(), StockModel.class);
                        stockLineList.addAll(stockModel.getRmsTaskInstockLineList());
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    stockInListViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    private void syncErp(){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.SYNC_IN_STOCK);
        if(stockModel==null){
//            ToastUtils.showToast(context, "入库单不存在");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        params.addBodyParameter("instockId", stockModel.getInstockId());
        params.addBodyParameter("operator", Constant.user.getLoginName());
        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(StockInNewActivity.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() == 2){
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                if(StringUtils.isEmpty(erpInstockCode)){
                    erpInstockCode = message.getMessage();
                }
                if(!StringUtils.isEmpty(erpInstockCode)){
                    loadErpTask(0);
                }
            }, 1000);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResumed = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getCommonTopTitle() {
        return "入库单信息";
    }

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

}