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.os.Handler;
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.StockOutListViewAdapter;
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.YgtxStockOutAddBinding;
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.Optional;


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

    private YgtxStockOutAddBinding binding;
    private Context context;
    private StockOutListViewAdapter stockLineListViewAdapter;
    private final ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private String out_stock_flag;
    private String from;
    private StockModel stockModel;
    private String erpOutstockCode;

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

//    View.OnClickListener printer = v -> {
//        String position = (String)v.getTag();
//        if(!position.contains(",")){
//            ToastUtils.showToast(context, position + "格式错误");
//            return;
//        }
//        String[] params = position.split(",");
//        StockLineModel stockLineModel = stockLineList.get(Integer.parseInt(params[0]));
//        stockLineModel.setPerBag(new BigDecimal(params[1]));
//        printItem(stockLineModel);
//    };

    private void initData(){
        erpOutstockCode = getParamString("erpOutstockCode");
        if(!StringUtils.isEmpty(erpOutstockCode)){
            binding.tvOutCode.setText(erpOutstockCode);
            loadErpTask(erpOutstockCode);
        }
        stockLineListViewAdapter = new StockOutListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(stockLineListViewAdapter);
        binding.lvProduct.setOnItemClickListener((parent, view, position, id) -> {
            StockLineModel stockLineModel = stockLineList.get(position);
            if("1".equals(from) && !"2".equals(stockLineModel.getStatus())){
                return;
            }
            stockOut(stockLineModel);
        });
        out_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "out_stock_flag");
        if(StringUtils.isEmpty(out_stock_flag)){
            ToastUtils.showToast(context, "请设置出库单编码的标识");
            finish();
        }
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("CK_20250304002");
//        });
//        binding.tvOutCode.setOnClickListener(view->{
//            receiverTask("0220013310125");
//        });
    }

    private void stockOut(StockLineModel stockLineModel){
        Bundle bundle = new Bundle();
        bundle.putString("erpOutstockCode", stockModel.getErpOutstockCode());
        bundle.putSerializable("stockLine", stockLineModel);
        bundle.putSerializable("from", from);
        toActivity(StockOutBindActivity.class, bundle);
    }

    private void initView(){
        from = getParamString("from");
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(view -> {
            finish();
        });
        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 -> {
                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(StockOutActivity.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.tvOutCode.getText().toString();
        if(barcode.startsWith(out_stock_flag)){
            try {
                binding.tvOutCode.setText(barcode);
                loadErpTask(barcode);
            }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) {
        Optional<StockLineModel> optionalStockLineModel = stockLineList.stream().filter(item -> item.getItemCode().equals(barcode)).findFirst();
        if (optionalStockLineModel.isPresent()) {
            stockOut(optionalStockLineModel.get());
            return;
        }
        ToastUtils.showToast(context, "出库单不存在" + barcode + "物品");
    }

    private void loadErpTask(String erpOutstockCode) {
        if(StringUtils.isEmpty(erpOutstockCode)){
            erpOutstockCode = binding.tvOutCode.getText().toString();
        }
        if(StringUtils.isEmpty(erpOutstockCode)){
            ToastUtils.showToast(context, "出库单号不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.ERP_OUT_STOCK);
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        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);
                        if(stockModel.getRmsTaskOutstockLineList()!=null) {
                            stockLineList.addAll(stockModel.getRmsTaskOutstockLineList());
                        }
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    stockLineListViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

            @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_OUT_STOCK);
        if(stockModel==null){
            ToastUtils.showToast(context, "出库单不存在");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        params.addBodyParameter("outstockId", stockModel.getOutstockId());
        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 {
                    ToastUtils.showToast(context, rs.getString("msg"));
                    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(StockOutNewActivity.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() == 3){
            loadErpTask(null);
        }
    }

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

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

}