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.Bundle;
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.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.FrozenSemenEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.WeightManEntity;
import com.phlx.anchorcollect.event.EventMsg;
import com.phlx.anchorcollect.event.EventTag;
import com.phlx.anchorcollect.ui.bind.BindActivity;
import com.phlx.anchorcollect.ui.labelchange.LabelChangeActivity;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect.ui.setting.SettingActivity;
import com.phlx.anchorcollect.ui.setting.SyncActivity;
import com.phlx.anchorcollect.util.LoginInfoUtils;
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 BasicsCollectVM extends BaseViewModel<Repository> implements OnInventoryListener {

    public Drawable drawableImg;
    //照片路径
    public String markeImgUrl;
    private File markFile;

    //存放非list控件
    public List<GenTableColumn> uiList = new ArrayList<>();
    public GenTableColumn currentParamEntity;
    public GenTableColumn remarkParamEntity = new GenTableColumn();
    public GenTableColumn photoParamEntity = 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<String> onChangeLabelEvent = new SingleLiveEvent<>();//换绑标签的弹窗


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

    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<>("");//总增重日期

    public SingleLiveEvent<String> setRfidValueEvent = new SingleLiveEvent<>();//设置弹窗的扫到的标签epc

    public SingleLiveEvent<String> setChangeLabelRfidValueEvent = new SingleLiveEvent<>();//设置换绑标签弹窗的扫到的标签epc


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

    private SimpleDateFormat dateFormat;

    public boolean isModify = false;

    private List<CattleResumeEntity> uploadData;

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

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

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

    private Disposable weightBus;

    public boolean isWeightScan = false;

    public int scanFunction = 0;//0 是普通扫描耳标，1 是弹出窗的扫描耳标, 2 是换绑耳标的扫描耳标


    public BasicsCollectVM(@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 String getMarkImgUrl() {
        return markeImgUrl;
    }

    public void setMarkImgUrl() {

        File externalFileRootDir = getApplication().getExternalFilesDir("/collect/picture/");
//                                    externalFileRootDir.mkdirs();
//        Environment.getExternalStorageDirectory().getAbsolutePath()
        String savePath = externalFileRootDir.getAbsolutePath();//不分开就少个斜杠
        markeImgUrl = savePath + "/anchorCiq" + Configs.tempCattleResume.getUnid() + ".jpg";
        markFile = new File(markeImgUrl);
    }

    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);

        int i = 0;
        for (GenTableColumn gtc : Configs.cattleresume) {
            if (i < 4) {
                uiList.add(gtc);
            } else {
                CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.BASE_ARCHIVES);
                observableList.add(cgi);
            }
            i++;
        }

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

        //初始化照片
        photoParamEntity.setContent("");
        photoParamEntity.setShowName("");
        photoParamEntity.setHtmlType("photo");
        photoParamEntity.setIsEdit("1");

    }

    public void initDataForTag(String tag) {

        if (isModify)
            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) {

//        clearTempInfo();
        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);
    }

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

            if (StringUtils.isEmpty(tag.get())) {
                onShowDialogEvent.setValue("请完成可视耳标的录入");
                return;
            }
            //在这判断一下图片
            if (Configs.tempCattleResume == null || StringUtils.isEmpty(Configs.tempCattleResume.getPhotoPath())) {
                ToastUtils.showShort("请上传打标图片");
                return;
            }
            //判断必填
            for (GenTableColumn gtc : Configs.cattleresume) {
                if ("1".equals(gtc.getIsRequired()) && StringUtils.isEmpty(gtc.getContent())) {
                    onShowDialogEvent.setValue("请完成" + gtc.getColumnComment() + "的录入");
                    return;
                }
            }

            saveCattleresume();
        }
    });

    //扫描rfid
    public void scanRfid() {
        if (!isScan && isWeightScan) {
            rfidTag = "";
            if (isModify)
                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().queryAsyncAll(WeightManEntity.class, builder3, 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();
            }
        });
    }

    public void onItemClick(GenTableColumn entity) {

//        if (Configs.tempUnid == null) {
//            ToastUtils.showShort("请扫描耳标或者输入耳标信息");
//            return;
//        }
        if (Configs.tempUnid != null && !"1".equals(entity.getIsEdit())) {
            ToastUtils.showShort("该项无法修改！");
            return;
        }

        if (Configs.tempTag == null) {
            ToastUtils.showShort("请输入耳标信息");
            return;
        }

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

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

    //设置
    public BindingCommand onSettingClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(SettingActivity.class);
        }
    });

    //修改标签
    public BindingCommand onLabelChangeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onChangeLabelEvent.call();
        }
    });

    //同步数据
    public BindingCommand onSyncClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            if (!Configs.isOnLine) {
//                ToastUtils.showShort("请在联网模式下同步数据！");
//                return;
//            }
//            startActivity(SyncActivity.class);
            if (Configs.isOnLine) {
                startActivity(SyncActivity.class);
            } else {
                startActivity(BindActivity.class);
            }
        }
    });

    //当前牛信息展示
    public BindingCommand onCattleInfoClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onCattleClickEvent.call();
        }
    });

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

    public void click(int id) {

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

        if (StringUtils.isEmpty(rfid.get())) {
            ToastUtils.showShort("请扫描耳标");
            return;
        }

        if (StringUtils.isEmpty(tag.get())) {
            ToastUtils.showShort("请输入可视耳标");
            return;
        }

        //99备注，100照片
        if (id == 99) {
            currentParamEntity = remarkParamEntity;
            return;//基础信息不可修改
        } else {
            if (id == 100) {
                currentParamEntity = photoParamEntity;
            } else {
                currentParamEntity = uiList.get(id);
            }
            if (!"1".equals(currentParamEntity.getIsEdit())) {
                return;
            }

            if (Configs.tempCattleResume == null) {
                Configs.tempCattleResume = new CattleResumeEntity();
            }
            if (Configs.tempCattleResume.getUnid() == null) {
                Configs.tempCattleResume.setUnid(IdUtil.createSnowflake(3, 1).nextId());
            }

            setMarkImgUrl();
        }

        onCardClickEvent.call();
    }

    //跳转到换绑页面
    public void forwardChangeLabel(String epc, String noticeNo) {

        Bundle mBundle = new Bundle();
        mBundle.putString("epc", epc);
        mBundle.putString("noticeNo", noticeNo);
        startActivity(LabelChangeActivity.class, mBundle);
    }

    private void queryCattleResume(QueryBuilder<CattleResumeEntity> builder) {

        DbUtil.getInstance().queryAsyncAll(CattleResumeEntity.class, builder, new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {

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

                    isModify = true;
                    markeImgUrl = getApplication().getExternalFilesDir("/collect/picture/").getAbsolutePath()
                            + "/anchorCiq" + result.get(0).getUnid() + ".jpg";
                    markFile = new File(markeImgUrl);
//                    File externalFileRootDir = getApplication().getExternalFilesDir("/collect/picture/");
////                                    externalFileRootDir.mkdirs();
//                    String savePath = externalFileRootDir.getAbsolutePath();
//                    markeImgUrl = savePath + "/anchorCiq" + result.get(0).getUnid() + ".jpg";
//                    markFile = new File(markeImgUrl);

                    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);
                    remarkParamEntity.setShowName(result.get(0).getRemark());

                    //查询牛的品种和所属种蓄站
                    Configs.deptName = SPUtils.getInstance().getString(Configs.SP_DEPT_NAME, "");
                    QueryBuilder<DictEntity> builder2 =
                            DbUtil.getInstance().getQueryBuilder(DictEntity.class)
                                    .where(DictEntityDao.Properties.DictType.eq("zxgl_cattle_raiseVarieties")
                                            , DictEntityDao.Properties.DictValue.eq(result.get(0).getRaiseVarieties()));
                    List<DictEntity> dictEntities2 = DbUtil.getInstance().queryAll(DictEntity.class, builder2);
                    if (dictEntities2 != null && dictEntities2.size() > 0) {
                        Configs.raiseVarieties = dictEntities2.get(0).getDictLabel();
                    }

                    queryGainWeight();

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

                        for (GenTableColumn gtc : Configs.cattleresume) {

                            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 {
                    if (isModify)
                        onNotifyAllEvent.setValue(true);
                    isModify = false;
                }

            }

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

    private void saveCattleresume() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.cattleresume) {
            //防止转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();
        CattleResumeEntity cattleResumeEntity = gson.fromJson(jsonObject, CattleResumeEntity.class);

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!isModify) {//新增
//            uuid = IdUtil.createSnowflake(3, 1).nextId();
            cattleResumeEntity.setUnid(Configs.tempCattleResume.getUnid());
            cattleResumeEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

            cattleResumeEntity.setCreateTime(dateFormat.format(new Date()));
        } else {
            cattleResumeEntity.setCreateBy(Configs.tempCattleResume.getCreateBy());
            cattleResumeEntity.setCreateTime(Configs.tempCattleResume.getCreateTime());
            cattleResumeEntity.setUnid(Configs.tempUnid);
            cattleResumeEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            cattleResumeEntity.setUpdateTime(dateFormat.format(new Date()));

        }
        //保存图片  改在上传时候读
//        if (Configs.tempCattleResume.getPhotoPath() != null && !Configs.tempCattleResume.getPhotoPath().equals("")) {
//            cattleResumeEntity.setPhoto(BaseImageUtils.bitmapToString(Configs.tempCattleResume.getPhotoPath(),
//            getApplication()));
//        }
        cattleResumeEntity.setPhotoPath(Configs.tempCattleResume.getPhotoPath());
        cattleResumeEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
        cattleResumeEntity.setRegistrationNo(rfid.get());
        cattleResumeEntity.setIndividualNo(tag.get());//修改去配置里修改
        cattleResumeEntity.setRemark(remarkParamEntity.getContent());
        cattleResumeEntity.setUploadStatus("0");

        //添加冻精系谱到牛只系谱
        if(!StringUtils.isEmpty(cattleResumeEntity.getFatherReg())){
            FrozenSemenEntity frozenSemenEntity =  LoginInfoUtils.getFrozenSemenForName(cattleResumeEntity.getFatherReg());
            if(frozenSemenEntity!=null){
                cattleResumeEntity.setFfNum(frozenSemenEntity.getFuCode());
                cattleResumeEntity.setFmNum(frozenSemenEntity.getMuCode());
                cattleResumeEntity.setFffNum(frozenSemenEntity.getZfCode());
                cattleResumeEntity.setFfmNum(frozenSemenEntity.getZmCode());
                cattleResumeEntity.setFmfNum(frozenSemenEntity.getWzfCode());
                cattleResumeEntity.setFmmNum(frozenSemenEntity.getWzmCode());
            }
        }

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

        DbUtil.getInstance().insertAsyncBatch(CattleResumeEntity.class, uploadData, new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    isModify = false;
                    clearTempInfo();
                    onNotifyAllEvent.setValue(true);
                    onShowDialogEvent.setValue("保存基础信息成功!");
                } else {
                    ToastUtils.showShort("保存基础信息失败");
                }
            }
        });
    }


    @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) {

            switch (scanFunction) {
                case 0:
                    if (!map.containsKey(rfidTag)) {
                        epcList.add(epc);
                        map.put(rfidTag, epcList.size() - 1);
                        //查数据库
//                addSubscribe(Observable.create((ObservableOnSubscribe<CattleResumeEntity>) emitter -> {
//                    try {
//
//                        KLog.e("epc:" + epc);
//                        QueryBuilder<CattleResumeEntity> builder =
//                                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
//                                        .where(CattleResumeEntityDao.Properties.RegistrationNo.eq(epc));
//                        List<CattleResumeEntity> labels = DbUtil.getInstance().queryAll(CattleResumeEntity.class,
//                        builder);
//
//                        if (labels.size() > 0) {
//                            emitter.onNext(labels.get(0));
//                        } else {
//                            CattleResumeEntity entity = new CattleResumeEntity();
//                            entity.setRegistrationNo(epc);
//                            entity.setIndividualNo("");
//                            emitter.onNext(entity);
//                        }
//                    } catch (Exception e) {
//                        emitter.onError(e);
//                    }
//
//                }).compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
//                        .compose(RxUtils.schedulersTransformer()).compose(RxUtils.exceptionTransformer())
//                        .doOnSubscribe(disposable -> {
//                        })
//                        .subscribe((Consumer<CattleResumeEntity>) response -> {
//                            epcList.add(response.getIndividualNo() + "----" + response.getRegistrationNo());
//                            map.put(rfidTag, epcList.size() - 1);
//                        }, (Consumer<ResponseThrowable>) throwable -> {
//                            dismissDialog();
//                            ToastUtils.showShort(throwable.message);
//                        }));
                    }
                    break;
                case 1:
                    setRfidValueEvent.setValue(epc);
                    break;
                case 2:
                    setChangeLabelRfidValueEvent.setValue(epc);
                    break;
            }
        } else {
            ToastUtils.showShort("盘点到标签：" + epc + "|停止盘点");
//            initDataForRfid(epc);
            switch (scanFunction) {
                case 0:
                    initDataForRfid(epc);
                    break;
                case 1:
                    setRfidValueEvent.setValue(epc);
                    break;
                case 2:
                    setChangeLabelRfidValueEvent.setValue(epc);
                    break;
            }
        }
    }

    @Override
    public void getInventoryData(InventoryData inventoryData) {
        if (inventoryData != null) {
            Log.e("lei", "getInventoryData: " + inventoryData.toString());
            Message messenger = handler.obtainMessage();
            messenger.what = 0x333;
            messenger.obj = inventoryData;
            handler.sendMessage(messenger);
        }
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        weightBus =
                RxBus.getDefault().toObservable(EventMsg.class).subscribe(eventType -> {
                    if (eventType.getAction().equals(EventTag.EVENT_WEIGHT_DATA_BASICS)) {
                        Double weightNum = Double.parseDouble(eventType.getObj().toString().trim());
                        if (weightNum > 25) {
                            scanFunction = 0;
                            scanRfid();
//                            if (isWeightScan)
                            Configs.tempWeight = weightNum;
                            isWeightScan = false;
                        } else {
                            String lastWeight = weight.get();
                            if (!StringUtils.isEmpty(lastWeight) && !lastWeight.equals("----") && Double.parseDouble(lastWeight) > 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);
    }

    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() {

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

}
