package com.ygtx.emcs.activity;

import static com.ygtx.emcs.comm.BaseApplication.mScanManager;
import static com.ygtx.emcs.util.Constant.CACHE_BIND_CONFIG;
import static com.ygtx.emcs.util.Constant.user;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.BoxItemListViewAdapter;
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.databinding.YgtxBoxCheckBinding;
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.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.ArrayList;


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

    private YgtxBoxCheckBinding binding;
    private Context context;
    private BoxItemListViewAdapter boxItemListViewAdapter;
    private ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private StockModel stockModel = new StockModel();
    private String box_flag;

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

    private void initData(){
        binding.lvProduct.setOnItemLongClickListener((parent, view1, position, id) -> {
            stockLineList.remove(position);
            boxItemListViewAdapter.notifyDataSetChanged();
            return false;
        });
        boxItemListViewAdapter = new BoxItemListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(boxItemListViewAdapter);
        binding.btnOk.setOnClickListener(v -> {
            pushData("ok");
        });
        binding.btnNg.setOnClickListener(v -> {
            pushData("ng");
        });
        box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");
        if(StringUtils.isEmpty(box_flag)){
            ToastUtils.showToast(context, "请设置料框编码的标识");
            finish();
        }
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("Box0002");
//        });
//        binding.tvScanTips.setOnLongClickListener(view->{
//            receiverTask("090160008120");
//            return true;
//        });
    }

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


    public void pushData(String status){
        String boxCode = binding.tvBoxCode.getText().toString();
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框码不能为空");
            return;
        }
        int i = checkItemStatus();
        if(i == 0 && "ok".equals(status)){
            ToastUtils.showToast(context, "物料没有全部通过");
            return;
        }
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在上传");
        RequestParams params = httParams(Constant.BOX_CHECK_BIND);
        params.addParameter("checkUser", user.getUserId());
        params.addParameter("checkStatus", status);
        params.addParameter("boxCode", boxCode);
        params.addParameter("wmRmsBoxItemList", stockLineList);
        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, "检验完成");
                        stockLineList.clear();
                        binding.tvBoxCode.setText("");
                        binding.tvCheckStatus.setText("");
                        boxItemListViewAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    public void getBoxByBoxCodeList(String boxCode) throws Throwable {
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框编码不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在查询");
        RequestParams params = httParams(Constant.BOX_LIST_VIEW);
        params.addParameter("boxCode", boxCode);
        try {
            x.http().get(params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject result) {
                    try {
                        parserItemList(result);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showToast(context, e.getMessage());
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    HttpsUtil.parserError(BoxCheckActivity.this, ex);
                    mylog.error("请求异常：", ex);
                }
                @Override
                public void onCancelled(CancelledException cex) {
                    HttpsUtil.parserError(BoxCheckActivity.this, cex);
                }
                @Override
                public void onFinished() {
                    progress.close();
                }
            });
        }catch (Throwable ex){
            ex.printStackTrace();
            throw ex;
        }
    }

    private void parserItemList(JSONObject rs) throws Exception {
        mylog.info(rs.toString());
        try {
            if (rs.getInt("code") == 200 && rs.has("data")) {
                JSONObject data = rs.getJSONObject("data");
                stockModel = new Gson().fromJson(data.toString(), StockModel.class);
                if("ok".equals(stockModel.getCheckStatus())){
                    binding.tvCheckStatus.setTextColor(Color.GREEN);
                    binding.tvCheckStatus.setText("已通过");
                }else if("ng".equals(stockModel.getCheckStatus())){
                    binding.tvCheckStatus.setTextColor(Color.RED);
                    binding.tvCheckStatus.setText("未通过");
                }else{
                    binding.tvCheckStatus.setTextColor(Color.BLUE);
                    binding.tvCheckStatus.setText("待检验");
                }
                stockLineList.clear();
                stockLineList.addAll(stockModel.getWmRmsBoxItemList());
                boxItemListViewAdapter.notifyDataSetChanged();
            }else{
                throw new Exception(rs.getString("msg"));
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    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);
        try {
            if(barcode.startsWith(box_flag)){
                binding.tvBoxCode.setText(barcode);
                getBoxByBoxCodeList(barcode);
            }else{
                StockLineModel existStockLine = isExist(barcode);
                if(existStockLine == null){
                    ToastUtils.showToast(context, "物料不存在");
                }else{
                    existStockLine.setCheckUser(user.getUserId().toString());
                    existStockLine.setSelStatus("ok");
                    existStockLine.setCheckStatus("ok");
                    int i = checkItemStatus();
                    if(i == 1){
                        new Handler().postDelayed(()->{
                            pushData("ok");
                        }, 2000);
                    }
                    boxItemListViewAdapter.notifyDataSetChanged();
                }
            }
        }catch (Throwable ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    private int checkItemStatus(){
        int i = 0;
        for (StockLineModel stockLineModel :stockLineList){
            if("ok".equals(stockLineModel.getSelStatus())){
                i++;
            }
        }
        if(stockLineList.size() == i){
            return 1;
        }
        return 0;
    }

    private StockLineModel isExist(String itemCode){
        for (StockLineModel stockLineModel :stockLineList){
            if(stockLineModel.getItemCode().equals(itemCode)){
                return stockLineModel;
            }
        }
        return null;
    }


    @Override
    protected String getCommonTopTitle() {
        return "料框检验";
    }

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

}