package com.phlx.anchorcollect.ui.fragment.vm;

import android.annotation.SuppressLint;
import android.app.Application;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseIntArray;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.phlx.anchorcollect.App;
import com.phlx.anchorcollect.BR;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.Repository;
import com.phlx.anchorcollect.db.DbUtil;
import com.phlx.anchorcollect.db.gen.CattleResumeEntityDao;
import com.phlx.anchorcollect.db.gen.DictEntityDao;
import com.phlx.anchorcollect.db.gen.MedicalRecordEntityDao;
import com.phlx.anchorcollect.db.gen.WeightManEntityDao;
import com.phlx.anchorcollect.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.CattleResumeEntity;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.MedicalRecordEntity;
import com.phlx.anchorcollect.entity.WeightManEntity;
import com.phlx.anchorcollect.event.EventMsg;
import com.phlx.anchorcollect.event.EventTag;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect.util.EntityUtils;
import com.phlx.anchorcollect.util.TextUtil;
import com.uhf.structures.InventoryData;
import com.uhf.structures.OnInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.IdUtil;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class WeightManVM extends BaseViewModel<Repository> implements OnInventoryListener {

    public Drawable drawableImg;
    //照片路径
    public String imgUrl;
    private File imgFile;

    //存放非list控件
    public List<GenTableColumn> uiList = new ArrayList<>();
    public GenTableColumn currentParamEntity;
    public GenTableColumn remarkParamEntity = new GenTableColumn();

    //给RecyclerView添加ObservableList
    public ObservableList<CollectGridItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<CollectGridItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_collect_grid);

    public SingleLiveEvent<Boolean> onCattleClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onCardClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onTagClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onNotifyAllEvent = new SingleLiveEvent<>();//true是清空页面
    public SingleLiveEvent<List<String>> onShowEpcListEvent = new SingleLiveEvent<>();//普通盘点模式下epc列表

    public SingleLiveEvent<String> onShowDialogEvent = new SingleLiveEvent<>();//弹窗提示

    public SingleLiveEvent<WeightManEntity> onCoverRecordEvent = new SingleLiveEvent<>();//查询是否覆盖称重记录

    public ObservableField<String> tag = new ObservableField<>("");
    public ObservableField<String> rfid = new ObservableField<>("");
    public ObservableField<Double> weight = new ObservableField<>(0.0);

    public ObservableField<Double> lastGainWeight = new ObservableField<>(0.0);//上次增重
    public ObservableField<Double> adgGainWeight = new ObservableField<>(0.0);//日增重
    public ObservableField<Double> totalGainWeight = new ObservableField<>(0.0);//总增重
    public ObservableField<String> lastGainDate = new ObservableField<>("");//上次增重日期
    public ObservableField<String> adgGainDate = new ObservableField<>("");//日增重日期
    public ObservableField<String> totalGainDate = new ObservableField<>("");//总增重日期

    private SimpleDateFormat dateFormat;

    private List<WeightManEntity> uploadData;
    private long uuid;

    //设置固定4个选项的值
    public ObservableField<String> tile01 = new ObservableField<>("");
    public ObservableField<String> value01 = new ObservableField<>("");
    public ObservableField<String> tile02 = new ObservableField<>("");
    public ObservableField<String> value02 = new ObservableField<>("");
    public ObservableField<String> tile03 = new ObservableField<>("");
    public ObservableField<String> value03 = new ObservableField<>("");
    public ObservableField<String> tile04 = new ObservableField<>("");
    public ObservableField<String> value04 = new ObservableField<>("");

    private SoundPool soundPool;//盘点到标签时的提示音
    private SparseIntArray musicId;

    public boolean isScan = false;//是否在扫描

    private String rfidTag = "";//扫描到的标记

    private static Map<String, Integer> map;//去重
    private ArrayList<String> epcList;

    private Disposable weightBus;

    private boolean isWeightScan = false;


    public WeightManVM(@NonNull Application application, Repository model) {
        super(application, model);

        //ImageView的占位图片，可以解决RecyclerView中图片错误问题
        drawableImg = ContextCompat.getDrawable(getApplication(), R.drawable.no_image);

        map = new HashMap<>();
        epcList = new ArrayList<>();

        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 5);
        musicId = new SparseIntArray();
        musicId.put(1, soundPool.load(getApplication(), R.raw.readcard, 1));
        musicId.put(2, soundPool.load(getApplication(), R.raw.failure, 1));

    }

    public void addInventoryListener() {
        App.getInstance().getLinkage().setOnInventoryListener(this);
    }

    public void removeInventoryListener() {
        App.getInstance().getLinkage().setOnInventoryListener(null);
    }

    public void initGen() {

//        imgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() +
//                "/collect/picture/"
//                + "anchorCiq" + tag + ".jpg";
//        imgFile = new File(imgUrl);
        uiList.clear();
        int i = 0;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (GenTableColumn gtc : Configs.weightMan) {
            if (gtc.getHtmlType().equals("datetime")) {
                if (gtc.getContent() == null || "".equals(gtc.getContent())) {
                    gtc.setContent(dateFormat.format(new Date()));
                    gtc.setShowName(dateFormat.format(new Date()));
                }
            }
            if (i < 4) {
                uiList.add(gtc);
            } else {
                CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.WEIGHTING_MANAGE);
                observableList.add(cgi);
            }
            i++;
        }

        while (uiList.size() < 4) {
            uiList.add(new GenTableColumn());
        }

        //初始化一下备注
        remarkParamEntity.setColumnName("备注");
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        remarkParamEntity.setColumnComment("备注");
        remarkParamEntity.setHtmlType("input");
        remarkParamEntity.setJavaType("String");
        remarkParamEntity.setColumnType("varchar(500)");
        remarkParamEntity.setIsEdit("1");

    }

    public void initDataForTag(String tag) {

        clearTempInfo();
//        clearParamList();
//        onNotifyAllEvent.setValue(false);
        this.tag.set(tag);
        Configs.tempTag = tag;
        if (StringUtils.isEmpty(tag))
            return;

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.IndividualNo.eq(tag));
        queryCattleResume(builder);
    }

    public void initDataForRfid(String rfid) {

        this.rfid.set(rfid);
        Configs.tempRfid = rfid;
        if (StringUtils.isEmpty(rfid))
            return;

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.RegistrationNo.eq(rfid));
        queryCattleResume(builder);
    }

    public void initDataForUnid(Long unid) {

        clearTempInfo();
//        clearParamList();
//        onNotifyAllEvent.setValue(false);
        Configs.tempUnid = unid;
        if (unid == null)
            return;

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.Unid.eq(unid));
        queryCattleResume(builder);
    }

    //扫描rfid
    private void scanRfid() {

        if (!isScan && isWeightScan) {
            clearTempInfo();
//            clearParamList();
//            onNotifyAllEvent.setValue(false);

            if (Configs.inventoryStatus) {
                showDialog("正在扫描耳标!");
            }

            App.getInstance().getLinkage().startInventory(1, 0);
            isScan = true;
            ToastUtils.showShort("开始盘点");

            //几秒后停止盘点
            Message messenger = handler.obtainMessage();
            messenger.what = 0x222;
            handler.sendMessageDelayed(messenger, 5000);
        }
//        else{
//            App.getInstance().getLinkage().stopInventory();
//            isScan = false;
//            ToastUtils.showShort("停止盘点");
//            scanBtnTextContent.set("标签查询");
//        }
    }

    //查询 上次称重 日增重 总体增重
    private void queryGainWeight() {

        lastGainWeight.set(0.0);
        adgGainWeight.set(0.0);
        totalGainWeight.set(0.0);

        QueryBuilder<WeightManEntity> builder3 =
                DbUtil.getInstance().getQueryBuilder(WeightManEntity.class)
                        .where(WeightManEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid))
                        .orderDesc(WeightManEntityDao.Properties.WTime);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<WeightManEntity>() {
            @Override
            public void onSuccess(List<WeightManEntity> result) {

                if (result != null && result.size() > 0) {
                    //总增重
                    if (Configs.tempCattleResume != null && Configs.tempCattleResume.getBirthHeavy() != null) {

                        double doubleTotal = result.get(0).getWeight() - Configs.tempCattleResume.getBirthHeavy();
                        totalGainWeight.set(Double.parseDouble(new DecimalFormat("0.0").format(doubleTotal)));
                        lastGainDate.set(result.get(0).getWTime());
                        adgGainDate.set(result.get(0).getWTime());
                        totalGainDate.set(result.get(0).getWTime());
//                        Log.e("weight", "totalGainWeight:" + totalGainWeight.get());
                    }

                    if (result.size() >= 1) {
                        double doublelastGain = result.get(0).getWeight();
                        lastGainWeight.set(Double.parseDouble(new DecimalFormat("0.0").format(doublelastGain)));
//                        Log.e("weight", "lastGainWeight:" + lastGainWeight.get());
                        if (result.size() > 1) {//两条以上记录
                            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Calendar frontCalendar = Calendar.getInstance();
                            Calendar laterCurcalendar = Calendar.getInstance();
                            try {
                                frontCalendar.setTime(dateFormat.parse(result.get(1).getWTime()));
                                laterCurcalendar.setTime(dateFormat.parse(result.get(0).getWTime()));
//                                Log.e("weight", "qian" + result.get(1).getWTime());
//                                Log.e("weight", "hou" + result.get(0).getWTime());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            int days = 0; //定义一个变量来计算相隔天数
                            while (frontCalendar.before(laterCurcalendar)) {
                                frontCalendar.add(Calendar.DATE, 1);
                                days++;
                            }
                            double doubleADG = (result.get(0).getWeight() - result.get(1).getWeight()) / days;
                            adgGainWeight.set(Double.parseDouble(new DecimalFormat("0.0").format(doubleADG)));
//                            Log.e("weight", "days:" + days);
//                            Log.e("weight", "qian-weight:" + result.get(1).getWeight());
//                            Log.e("weight", "hou-weight:" + result.get(0).getWeight());
//                            Log.e("weight", "adgGainWeight:" + adgGainWeight.get());
                        }
                    }
                }
            }

            @Override
            public void onFailed() {
                cn.wandersnail.commons.util.ToastUtils.showShort("查询称重记录失败！");
                dismissDialog();
            }
        }).queryAsyncAll(WeightManEntity.class, builder3);
    }


    public void onItemClick(GenTableColumn entity) {

        if (!"1".equals(entity.getIsEdit())) return;

        if (Configs.tempUnid == null) {
            ToastUtils.showShort("请扫描耳标或者输入耳标信息");
            return;
        }

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

    public String getImgUrl() {
        return imgUrl;
    }

    //输入可视耳标
    public BindingCommand onTagInputClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onTagClickEvent.call();
        }
    });

    public void click(int id) {


        if (Configs.tempUnid == null) {
            ToastUtils.showShort("请扫描耳标或者输入耳标信息");
            return;
        }

        //99备注，100照片
        if (id == 99) {
            currentParamEntity = remarkParamEntity;
        } else {
            currentParamEntity = uiList.get(id);
        }

        if (!"1".equals(currentParamEntity.getIsEdit())) return;
        onCardClickEvent.call();
    }

    public BindingCommand onSaveClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (Configs.tempUnid == null) {
                onShowDialogEvent.setValue("请先扫描耳标！");
                return;
            }

            if (weight.get() < 25) {
                onShowDialogEvent.setValue("重量非法！请先称重！");
                return;
            }

            //判断必填
            for (GenTableColumn gtc : Configs.weightMan) {
                if ("1".equals(gtc.getIsRequired()) && StringUtils.isEmpty(gtc.getContent())) {
                    onShowDialogEvent.setValue("请完成" + gtc.getColumnComment() + "的录入");
                    return;
                }
            }

            JsonObject jsonObject = new JsonObject();
            for (GenTableColumn gtc : Configs.weightMan) {
                //防止转json类型错误
                if ("".equals(gtc.getContent())) {
                    switch (gtc.getJavaType()) {
                        case "Long":
                        case "Double":
                        case "Integer":
                        case "BigDecimal":
                            gtc.setContent("0");
                            break;
                    }
                }
                jsonObject.addProperty(gtc.getJavaField(), gtc.getContent());
            }

            Gson gson = new Gson();
            WeightManEntity weightManEntity = gson.fromJson(jsonObject, WeightManEntity.class);

            //先看当天是否有称重记录
            QueryBuilder<WeightManEntity> builder3 =
                    DbUtil.getInstance().getQueryBuilder(WeightManEntity.class)
                            .where(WeightManEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid)
                                    , WeightManEntityDao.Properties.WTime.eq(weightManEntity.getWTime())
                            );
            DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<WeightManEntity>() {
                @Override
                public void onSuccess(List<WeightManEntity> result) {

                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    if (result != null && result.size() > 0) {//本日有过称重记录
                        WeightManEntity newWeightManEntity = result.get(0);
                        newWeightManEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                        newWeightManEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

                        newWeightManEntity.setUpdateTime(dateFormat.format(new Date()));
                        newWeightManEntity.setUploadStatus("0");
                        newWeightManEntity.setWeight(weight.get());
                        newWeightManEntity.setRemark(remarkParamEntity.getContent());
                        onCoverRecordEvent.setValue(newWeightManEntity);
                    } else {

                        uuid = IdUtil.createSnowflake(3, 1).nextId();
                        weightManEntity.setUnid(uuid);
                        weightManEntity.setCattleresumeId(Configs.tempUnid);
                        weightManEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
                        weightManEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

                        weightManEntity.setCreateTime(dateFormat.format(new Date()));
                        weightManEntity.setUploadStatus("0");
                        weightManEntity.setWeight(weight.get());
                        weightManEntity.setRemark(remarkParamEntity.getContent());

                        saveWeightMan(weightManEntity);
                    }
                }

                @Override
                public void onFailed() {
                    cn.wandersnail.commons.util.ToastUtils.showShort("查询称重记录失败！");
                    dismissDialog();
                }
            }).queryAsyncAll(WeightManEntity.class, builder3);
        }
    });

    //点击去扫描rfid
    public BindingCommand onWeightChangedClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            isWeightScan = true;
            map = new HashMap<>();
            epcList.clear();
            scanRfid();
        }
    });

    private void queryCattleResume(QueryBuilder<CattleResumeEntity> builder) {

        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {

                if (result != null && result.size() > 0) {

                    imgUrl = getApplication().getExternalFilesDir("/collect/picture/").getAbsolutePath()
                            + "/anchorCiq" + result.get(0).getUnid() + ".jpg";
                    imgFile = new File(imgUrl);

                    Configs.tempCattleResume = result.get(0);
                    Configs.tempTag = result.get(0).getIndividualNo();
                    Configs.tempRfid = result.get(0).getRegistrationNo();
                    Configs.tempUnid = result.get(0).getUnid();
                    tag.set(Configs.tempTag);
                    rfid.set(Configs.tempRfid);

                    queryGainWeight();//刷新一下增重数据

                    String[] filedName = EntityUtils.getFiledName(result.get(0));
                    for (String name : filedName) {

                        for (GenTableColumn gtc : Configs.weightMan) {

                            if (gtc.getHtmlType() != null && gtc.getHtmlType().equals("datetime")) {
                                if (gtc.getContent() == null || "".equals(gtc.getContent())) {
                                    dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    gtc.setContent(dateFormat.format(new Date()));
                                    gtc.setShowName(dateFormat.format(new Date()));
                                }
                            }
                            if (name.equals(gtc.getJavaField())) {
                                try {
//                                    Log.e("key:", name);
                                    Object fieldValueByName = EntityUtils.getFieldValueByName(name, result.get(0));
                                    String value = fieldValueByName == null ? "" : fieldValueByName.toString();
//                                    Log.e("value:", value);
                                    gtc.setContent(value);
                                    String showName = value;
                                    // 如果是选择的，查字典项
                                    if (!StringUtils.isEmpty(gtc.getDictType())) {
                                        QueryBuilder<DictEntity> builder =
                                                DbUtil.getInstance().getQueryBuilder(DictEntity.class)
                                                        .where(DictEntityDao.Properties.DictType.eq(gtc.getDictType())
                                                                , DictEntityDao.Properties.DictValue.eq(value));
                                        List<DictEntity> dictEntities = DbUtil.getInstance().queryAll(DictEntity.class, builder);
                                        if (dictEntities != null && dictEntities.size() > 0) {
                                            showName = dictEntities.get(0).getDictLabel();
                                        }
                                    }
                                    gtc.setShowName(showName);

                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }
                    onNotifyAllEvent.setValue(false);
                } else {
                    onNotifyAllEvent.setValue(true);
                }

            }

            @Override
            public void onFailed() {
                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("基础档案数据库查询失败");
            }
        }).queryAsyncAll(CattleResumeEntity.class, builder);
    }

    public void saveWeightMan(WeightManEntity weightManEntity) {

        uploadData = new ArrayList<>();
        uploadData.add(weightManEntity);

        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    for (GenTableColumn gtc : uiList) {
                        gtc.setContent("");
                        gtc.setShowName("");
                        gtc.notifyChange();

                        if (gtc.getHtmlType() != null && gtc.getHtmlType().equals("datetime")) {
                            if (gtc.getContent() == null || "".equals(gtc.getContent())) {
                                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                gtc.setContent(dateFormat.format(new Date()));
                                gtc.setShowName(dateFormat.format(new Date()));
                            }
                        }
                    }

                    queryGainWeight();//刷新一下增重数据
                    ToastUtils.showShort("保存称重记录成功");
                } else {
                    ToastUtils.showShort("保存称重记录失败");
                }
            }
        }).insertAsyncBatch(WeightManEntity.class, uploadData);


    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x333) {
                InventoryData inventoryData = (InventoryData) msg.obj;
                if (inventoryData.getDataLength() > 0 && inventoryData.getEpcLength() > 0) {
                    String epc = TextUtil.byteToHexString(inventoryData.getEPC_Data(), inventoryData.getEpcLength()).substring(1);
                    String tid = TextUtil.byteToHexString(inventoryData.getData(), inventoryData.getDataLength());
                    soundPool.play(musicId.get(1), 1, 1, 0, 0, 1);
                    App.getInstance().getLinkage().stopInventory();
                    isScan = false;

                    if (!Configs.inventoryStatus && !"".equals(rfidTag))
                        return;

                    checkEpc(epc, tid);
                }
            } else if (msg.what == 0x222) {
                App.getInstance().getLinkage().stopInventory();
                isScan = false;
                ToastUtils.showShort("停止盘点");
                dismissDialog();
                if (Configs.inventoryStatus) {
                    if (epcList != null && epcList.size() > 0) {
                        onShowEpcListEvent.setValue(epcList);
                    } else {
                        onShowDialogEvent.setValue("未扫描到标签!");
                    }
                }
            }
        }
    };

    private void checkEpc(String epc, String tid) {
        rfidTag = epc + tid;
        if (Configs.inventoryStatus) {
            if (!map.containsKey(rfidTag)) {

                epcList.add(epc);
                map.put(rfidTag, epcList.size() - 1);
            }
        } else {
            ToastUtils.showShort("盘点到标签：" + epc + "|停止盘点");
            initDataForRfid(epc);
        }
    }


    @Override
    public void registerRxBus() {
        super.registerRxBus();
        weightBus =
                RxBus.getDefault().toObservable(EventMsg.class).subscribe(eventType -> {
                    if (eventType.getAction().equals(EventTag.EVENT_WEIGHT_DATA_WEIGHT)) {
                        Double weightNum = Double.parseDouble(eventType.getObj().toString().trim());
                        if (weightNum > 25) {
                            scanRfid();
//                            if (isWeightScan)
                                Configs.tempWeight = weightNum;
                            isWeightScan = false;
                        } else {
                            if (weight.get() != null && weight.get() > 25) {

                                lastGainWeight.set(0.0);
                                adgGainWeight.set(0.0);
                                totalGainWeight.set(0.0);
                                clearTempInfo();
                                onNotifyAllEvent.setValue(true);
                            }
                            isWeightScan = true;
                        }
                        weight.set(weightNum);
                    }
                });
        RxSubscriptions.add(weightBus);
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(weightBus);
    }

    @Override
    public void getInventoryData(InventoryData inventoryData) {
        if (inventoryData != null) {
            Message messenger = handler.obtainMessage();
            messenger.what = 0x333;
            messenger.obj = inventoryData;
            handler.sendMessage(messenger);
        }
    }


    private void clearTempInfo() {

        Configs.tempTag = "";
        Configs.tempUnid = null;
        Configs.tempRfid = "";
        Configs.tempCattleResume = null;
//        Configs.tempWeight = 0.0;
        tag.set("");
        rfid.set("");
        rfidTag = "";
    }


    //清空数据源
    public void clearParamList() {

        //备注清除数据
        imgUrl = "";
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        currentParamEntity = new GenTableColumn();
        for (GenTableColumn gtc : Configs.weightMan) {
            gtc.setShowName("");
            gtc.setContent("");
        }
    }
}
