package com.sxyz.rfid.ui.review.offline;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.Triggering;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.sxyz.rfid.App;
import com.sxyz.rfid.R;
import com.sxyz.rfid.base.BaseActivity;
import com.sxyz.rfid.databinding.ActivityOfflineReviewTaskDetailBinding;
import com.sxyz.rfid.greendao.GreenDaoManager;
import com.sxyz.rfid.greendao.model.WmsArea;
import com.sxyz.rfid.greendao.model.WmsInventory;
import com.sxyz.rfid.greendao.model.WmsInventoryResult;
import com.sxyz.rfid.greendao.model.WmsInventoryTask;
import com.sxyz.rfid.greendao.model.WmsInventoryTaskDetail;
import com.sxyz.rfid.greendao.model.WmsLocation;
import com.sxyz.rfid.greendao.model.WmsWarehouse;
import com.sxyz.rfid.ui.review.offline.adapter.ReviewOfflineDetailAdapter;
import com.sxyz.rfid.utils.L;
import com.sxyz.rfid.utils.StringUtil;
import com.sxyz.rfid.utils.ToastUtil;
import com.sxyz.rfid.widgets.AlertDialogUtil;
import com.sxyz.rfid.widgets.OEMSymbologyId;
import com.ubx.usdk.RFIDSDKManager;
import com.ubx.usdk.rfid.aidl.IRfidCallback;
import com.ubx.usdk.util.SoundTool;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sql.com.yz.db.DaoSession;
import sql.com.yz.db.WmsAreaDao;
import sql.com.yz.db.WmsInventoryDao;
import sql.com.yz.db.WmsInventoryResultDao;
import sql.com.yz.db.WmsInventoryTaskDao;
import sql.com.yz.db.WmsInventoryTaskDetailDao;
import sql.com.yz.db.WmsLocationDao;
import sql.com.yz.db.WmsWarehouseDao;

/**
 * 主要功能:  盘点任务详情
 *
 * @Description: 盘点任务详情
 * @Project: rfid-app
 * @Package: com.sxyz.rfid.ui.review
 * @author: chunyuanwu
 * @date: 2025年12月29日 18:18
 * @version: 1.0.0
 */
public class ReviewOfflineTaskActivity extends BaseActivity<ActivityOfflineReviewTaskDetailBinding> {
    private WmsInventoryTask item;
    private ReviewOfflineDetailAdapter mAdapter;
    private List<WmsInventoryTaskDetail> list = new ArrayList<>();
    private boolean isMenuOpen = false;
    private boolean isScan = false;
    private boolean isRfid = false;
    private int inventoryFlag = 0;
    private ScanCallback callback = new ScanCallback();
    private List<WmsInventoryTaskDetail> mList = new ArrayList<>();
    private DaoSession daoSession;

    @Override
    public void initParms(Bundle mBundle) {
        item = (WmsInventoryTask) mBundle.getSerializable("item");
        L.i("item ======\n " + new Gson().toJson(item));
    }

    @Override
    protected ActivityOfflineReviewTaskDetailBinding getViewBinding() {
        return ActivityOfflineReviewTaskDetailBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        initToolBar("执行盘点");
        findViewById(R.id.iv_back).setOnClickListener(v -> {
            if (isMenuOpen) {
                closeMenu();
            } else {
                onBackPressed();
            }
        });
        mBinding.rvOutboundDetails.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter = new ReviewOfflineDetailAdapter(R.layout.item_review_detail, list);
        mBinding.rvOutboundDetails.setAdapter(mAdapter);
    }

    @Override
    protected void setListener() {
        if (RFIDSDKManager.getInstance().getRfidManager() != null) {
            //注册rfid回调
            RFIDSDKManager.getInstance().getRfidManager().registerCallback(callback);
        }
        //复制按钮点击事件
        mBinding.tvTaskNo.setOnClickListener(v -> {
            StringUtil.copyToClipboard(this, item.getTaskNo());
        });
        //出库明细点击事件
        mAdapter.setOnItemClickListener(new ReviewOfflineDetailAdapter.OnItemClickListener() {
            @Override
            public void onCopy1ItemClick(int position, WmsInventoryTaskDetail item) {
                StringUtil.copyToClipboard(mActivity, item.getBatchNo());
            }

            @Override
            public void onCopy2ItemClick(int position, WmsInventoryTaskDetail item) {
                StringUtil.copyToClipboard(mActivity, item.getRfidTag());
            }
        });

        //如果菜单打开，点击空白区域关闭菜单
        mBinding.ivClose.setOnClickListener(v -> {
            if (isMenuOpen) {
                closeMenu();
            }
        });

        //rfid出库
        mBinding.btnRfidOutbound.setOnClickListener(v -> {
            if (!isMenuOpen) {
                mBinding.tvTitle.setText("RFID出库");
                isRfid = true;
                isScan = false;
                openMenu();
            }
        });

        //扫码出库
        mBinding.btnScanOutbound.setOnClickListener(v -> {
            if (!isMenuOpen) {
                mBinding.tvTitle.setText("扫码出库");
                isScan = true;
                isRfid = false;
                openMenu();
            }
        });
        //盘点方式 单盘/循环盘
        mBinding.RgInventory.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == mBinding.RbInventorySingle.getId()) {
                inventoryFlag = 0;
                App.mScanManager.setTriggerMode(Triggering.HOST);
            } else if (checkedId == mBinding.RbInventoryLoop.getId()) {
                inventoryFlag = 1;
                App.mScanManager.setTriggerMode(Triggering.CONTINUOUS);
            }
        });
    }

    @Override
    protected void initData() {
        daoSession = GreenDaoManager.getInstance().getDaoSession();
        if (daoSession == null) {
            //数据库不存在
            mList.clear();
            mAdapter.notifyDataSetChanged();
            mBinding.includedNoDb.llNoDb.setVisibility(View.VISIBLE);
        } else {
            //根据item.getTaskId()查询任务基础信息===========================================================================
            WmsInventoryTask task = daoSession.getWmsInventoryTaskDao().load(item.getTaskId());
//            L.i("task ======\n " + new Gson().toJson(task));
            //任务编号
            mBinding.tvTaskNo.setText(task.getTaskNo());
            switch (task.getTaskStatus()) {
                case "0":
                    mBinding.tvTaskStatus.setText("未完成");
                    mBinding.tvTaskStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.status_red_bg));
                    mBinding.tvTaskStatus.setTextColor(ContextCompat.getColor(this, R.color.red));
                    break;
                case "1":
                    mBinding.tvTaskStatus.setText("进行中");
                    mBinding.tvTaskStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.status_org_bg));
                    mBinding.tvTaskStatus.setTextColor(ContextCompat.getColor(this, R.color.text_orange3));
                    break;
                case "2":
                    mBinding.tvTaskStatus.setText("已完成");
                    mBinding.tvTaskStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.status_green_bg));
                    mBinding.tvTaskStatus.setTextColor(ContextCompat.getColor(this, R.color.green));
                    break;
                case "3":
                    mBinding.tvTaskStatus.setText("已结束");
                    mBinding.tvTaskStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.status_gray_bg));
                    mBinding.tvTaskStatus.setTextColor(ContextCompat.getColor(this, R.color.c_6666));
                    break;
                default:
                    mBinding.tvTaskStatus.setText("-");
                    mBinding.tvTaskStatus.setBackground(ContextCompat.getDrawable(this, R.drawable.status_gray_bg));
                    mBinding.tvTaskStatus.setTextColor(ContextCompat.getColor(this, R.color.c_6666));
                    break;
            }
            //任务名称
            mBinding.tvTaskName.setText(!StringUtils.isEmpty(task.getTaskName()) ? task.getTaskName() : "-");
            //仓库名称
            mBinding.txtWarehouseName.setText(!StringUtils.isEmpty(task.getWarehouseName()) ? task.getWarehouseName() : "-");
            //已盘数
            mBinding.txtReviewNumber.setText(task.getCountedItems() + "");
            //总盘点数
            mBinding.txtTotalNumber.setText(task.getTotalItems() + "");
            //出库人
            mBinding.txtRemark.setText(!StringUtils.isEmpty(task.getRemark()) ? task.getRemark() : "-");

            //根据item.getTaskId()查询任务明细信息列表===========================================================================
            mList = daoSession.getWmsInventoryTaskDetailDao().queryBuilder().where(WmsInventoryTaskDetailDao.Properties.TaskId.eq(item.getTaskId())).list();
            //L.i("list ======\n " + new Gson().toJson(mList));
            //设置新的数据集
            mAdapter.setNewInstance(mList);
            //隐藏暂无数据布局
            mBinding.includedNoDb.llNoDb.setVisibility(View.GONE);
            //判断是否为空 如果为空 则显示暂无数据 否则 隐藏暂无数据
            if (mList.isEmpty()) {
                mBinding.includedNothing.llNothing.setVisibility(View.VISIBLE);
            } else {
                mBinding.includedNothing.llNothing.setVisibility(View.GONE);
            }

            //根据item.getTaskId()查询任务结果===========================================================================
            WmsInventoryResult wmsInventoryResult = daoSession.getWmsInventoryResultDao().queryBuilder().where(WmsInventoryResultDao.Properties.TaskId.eq(item.getTaskId())).unique();
            //总盘点数
            mBinding.tvTotalItems.setText(wmsInventoryResult.getTotalItems() + "");
            //已盘数  过滤出已盘的项  统计数量
            mBinding.tvCountedItems.setText(wmsInventoryResult.getCountedItems() + "");
            //盘盈数
            mBinding.tvSurplusItems.setText(wmsInventoryResult.getSurplusItems() + "");
            //盘亏数
            mBinding.tvDeficitItems.setText(wmsInventoryResult.getDeficitItems() + "");
            //盘点进度 已盘数/总盘点数*100%
            int progress = (int) (wmsInventoryResult.getCountedItems() * 100.0 / wmsInventoryResult.getTotalItems());
            mBinding.tvProgress.setText(progress + "%");
            //进度条
            mBinding.progressBar.setProgress(progress);
        }
    }

    private void openMenu() {
        mBinding.sideMenu.animate().translationX(0).setDuration(300).start();
        isMenuOpen = true;
        if (isScan) {
            //开启扫码
            App.mScanManager.openScanner();
        }
    }

    private void closeMenu() {
        mBinding.sideMenu.animate().translationX(-mBinding.sideMenu.getWidth()).setDuration(300).start();
        isMenuOpen = false;
        isScan = false;
        isRfid = false;
        //关闭扫码
        App.mScanManager.stopDecode();
        App.mScanManager.closeScanner();
        //关闭rfid
        if (RFIDSDKManager.getInstance().getRfidManager() != null) {
            RFIDSDKManager.getInstance().getRfidManager().stopInventory();
        }

    }

    /**
     * 按键按下 开启扫描
     **/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == 515 || keyCode == 523) && event.getRepeatCount() == 0) {
            //RFID识别盘点
            if (isRfid) {
                if (inventoryFlag == 0) {//单盘
                    RFIDSDKManager.getInstance().getRfidManager().inventorySingle();//单次盘点
                } else if (inventoryFlag == 1) {//循环盘
                    RFIDSDKManager.getInstance().getRfidManager().startRead();//少量标签盘点建议使用：0；盘点标签超过 100-200建议使用：1.
                }
            }
            //二维码扫描
            if (isScan) {
//                mScanManager.startDecode();
            }
            mBinding.tvStatus.setText("正在盘点");
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 按键抬起 关闭扫描
     **/
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if ((keyCode == 515 || keyCode == 523) && event.getRepeatCount() == 0) {
            if (isRfid) {
                if (RFIDSDKManager.getInstance().getRfidManager() != null) {
                    RFIDSDKManager.getInstance().getRfidManager().stopInventory();
                }
            }
            //扫码出库 抬起 停止扫码
            if (isScan) {
                App.mScanManager.stopDecode();
            }
            mBinding.tvStatus.setText("");
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * RFID识别盘点 回调
     */
    class ScanCallback implements IRfidCallback {
        @Override
        public void onInventoryTag(String EPC, final String TID, final String strRSSI) {
            Log.e("xxx", "onInventoryTag:............... epc:" + EPC + "    tid:" + TID);
            SoundTool.getInstance(App.getContext()).playBeep(1);
            mBinding.btnRfidOutbound.post(() -> {
                if (daoSession != null) {
                    //将查询到的任务中的check_status 改为 1
                    String rfidTag = "BQ001";
                    updateTaskStatus(rfidTag, true);
                }
            });
        }

        /**
         * 盘存结束回调(Inventory Command Operate End)
         */
        @Override
        public void onInventoryTagEnd() {
            Log.i("xxx", "onInventoryTagEnd()");
        }
    }

    /**
     * 更新任务状态
     */
    private void updateTaskStatus(String rfidOrScanTag, boolean isRfid) {
        WmsInventoryTaskDetailDao wmsInventoryTaskDetailDao = daoSession.getWmsInventoryTaskDetailDao();
        WmsInventoryTaskDetail taskDetail;
        if (isRfid) {
            taskDetail = wmsInventoryTaskDetailDao.queryBuilder().where(WmsInventoryTaskDetailDao.Properties.TaskId.eq(item.getTaskId())).where(WmsInventoryTaskDetailDao.Properties.RfidTag.eq(rfidOrScanTag)).build().unique();
        } else {
            taskDetail = wmsInventoryTaskDetailDao.queryBuilder().where(WmsInventoryTaskDetailDao.Properties.TaskId.eq(item.getTaskId())).where(WmsInventoryTaskDetailDao.Properties.BatchNo.eq(rfidOrScanTag)).build().unique();
        }
        if (taskDetail != null) {
            //CheckStatus=1 已盘过，不重复盘
            if (taskDetail.getCheckStatus().equals("1")) {
                //已盘过，不重复盘
                ToastUtil.showShort("该标签已盘过");
            } else {
                //盘存成功后，将盘存结果更新到任务详情中
                //更新盘存状态为已盘1
                taskDetail.setCheckStatus("1");
                //更新盘存结果中的盘存差异原因 wcy=无差异；py=盘盈；pk=盘亏
                taskDetail.setDiffReason("wcy");
                //更新盘点时间为当前时间 时间戳
                taskDetail.setCheckTime(new Date().getTime() + "");
                //更新盘存结果中的盘存数量
                wmsInventoryTaskDetailDao.update(taskDetail);
                L.i("task:" + new Gson().toJson(taskDetail));
                //根据item.getTaskId()查询任务结果，更新盘存数量
                WmsInventoryResultDao wmsInventoryResultDao = daoSession.getWmsInventoryResultDao();
                WmsInventoryResult wmsInventoryResult = wmsInventoryResultDao.queryBuilder().where(WmsInventoryResultDao.Properties.TaskId.eq(item.getTaskId())).unique();
                if (wmsInventoryResult != null) {
                    //盘存结果中的盘存数量+1,更新盘存结果
                    wmsInventoryResult.setCountedItems(wmsInventoryResult.getCountedItems() + 1);
                    //更新盘存结果
                    wmsInventoryResultDao.update(wmsInventoryResult);
                    L.i("result:" + new Gson().toJson(wmsInventoryResult));
                    //将任务列表WmsInventoryTask的盘点数+1
                    WmsInventoryTaskDao wmsInventoryTaskDao = daoSession.getWmsInventoryTaskDao();
                    WmsInventoryTask wmsInventoryTask = wmsInventoryTaskDao.queryBuilder().where(WmsInventoryTaskDao.Properties.TaskId.eq(item.getTaskId())).unique();
                    if (wmsInventoryTask != null) {
                        wmsInventoryTask.setCountedItems(wmsInventoryTask.getCountedItems() + 1);
                        //判断是否完成所有盘存任务,已盘数等于总盘点数,任务状态设置为2 已完成
                        if (wmsInventoryTask.getTotalItems() == wmsInventoryTask.getCountedItems()) {
                            wmsInventoryTask.setTaskStatus("2");//任务状态设置为2 已完成
                        }
                        //更新任务结果
                        wmsInventoryTaskDao.update(wmsInventoryTask);
                    }
                    //判断是否全部盘点完成 ：已盘数等于总盘点数，任务状态为2 已完成
                    if (wmsInventoryResult.getTotalItems() == wmsInventoryResult.getCountedItems() || wmsInventoryTask.getTaskStatus().equals("2")) {
                        new AlertDialogUtil(this).builder().setTitle("提示").setMsg("盘点已全部完成").setNegativeButton("我知道了", v -> {
                            closeMenu();
                        }).show();
                    }
                }
                //刷新页面数据
                initData();
            }
        } else {
            ToastUtil.showShort("盘盈");
            //盘盈（查询库存表）：在明细表中自增一条数据,根据rfidTag查询库存表WmsInventory数据
            WmsInventoryDao wmsInventoryDao = daoSession.getWmsInventoryDao();
            WmsInventory wmsInventory;
            if (isRfid) {
                wmsInventory = wmsInventoryDao.queryBuilder().where(WmsInventoryDao.Properties.RfidTag.eq(rfidOrScanTag)).unique();
            } else {
                wmsInventory = wmsInventoryDao.queryBuilder().where(WmsInventoryDao.Properties.BatchNo.eq(rfidOrScanTag)).unique();
            }
            if (wmsInventory != null) {
                L.i("rfidTag查询获取库存数据:" + new Gson().toJson(wmsInventory));
                //盘盈：在明细表中增加一条盘盈数据
                WmsInventoryTaskDetail wmsInventoryTaskDetail = new WmsInventoryTaskDetail();
                wmsInventoryTaskDetail.setInventoryId(wmsInventory.getInventoryId().intValue());//盘盈库存id
                wmsInventoryTaskDetail.setTaskId(item.getTaskId().intValue());//盘盈任务id
                wmsInventoryTaskDetail.setMaterialId(wmsInventory.getMaterialId());//盘盈物料id
                wmsInventoryTaskDetail.setWarehouseId(wmsInventory.getWarehouseId());//盘盈仓库id
                //根据wmsInventory.getWarehouseId()查询仓库表WmsWarehouse数据
                WmsWarehouseDao wmsWarehouseDao = daoSession.getWmsWarehouseDao();
                WmsWarehouse wmsWarehouse = wmsWarehouseDao.queryBuilder().where(WmsWarehouseDao.Properties.WarehouseId.eq(wmsInventory.getWarehouseId())).unique();
                if (wmsWarehouse != null) {
                    L.i("根据仓库id查询仓库数据:" + new Gson().toJson(wmsWarehouse));
                    wmsInventoryTaskDetail.setWarehouseName(wmsWarehouse.getWarehouseName());//盘盈仓库名称
                }
                wmsInventoryTaskDetail.setAreaId(wmsInventory.getAreaId());//盘盈库区id
                //根据wmsInventory.getAreaId()查询库区表WmsArea数据
                WmsAreaDao wmsAreaDao = daoSession.getWmsAreaDao();
                WmsArea wmsArea = wmsAreaDao.queryBuilder().where(WmsAreaDao.Properties.AreaId.eq(wmsInventory.getAreaId())).unique();
                if (wmsArea != null) {
                    L.i("根据库区id查询库区数据:" + new Gson().toJson(wmsArea));
                    wmsInventoryTaskDetail.setAreaName(wmsArea.getAreaName());//盘盈库区名称
                }
                wmsInventoryTaskDetail.setLocationId(wmsInventory.getLocationId());//盘盈库位id
                WmsLocationDao wmsLocationDao = daoSession.getWmsLocationDao();
                WmsLocation wmsLocation = wmsLocationDao.queryBuilder().where(WmsLocationDao.Properties.LocationId.eq(wmsInventory.getLocationId())).unique();
                if (wmsLocation != null) {
                    L.i("根据库位id查询库位数据:" + new Gson().toJson(wmsLocation));
                    wmsInventoryTaskDetail.setLocationName(wmsLocation.getLocationName());//盘盈库位名称
                }
                wmsInventoryTaskDetail.setBatchNo(wmsInventory.getBatchNo());//盘盈批次号
//                wmsInventoryTaskDetail.setSystemQty(wmsInventory.getSystemQty());//系统数量
//                wmsInventoryTaskDetail.setActualQty(wmsInventory.getActualQty());//盘盈数量
//                wmsInventoryTaskDetail.setDiffQty(wmsInventory.getDiffQty());//盘盈差异数量
                wmsInventoryTaskDetail.setCheckerId(null);//盘盈检查人id
                wmsInventoryTaskDetail.setCheckerName("扫码枪离线盘点");//盘盈检查人姓名
                wmsInventoryTaskDetail.setRfidTag(rfidOrScanTag);//盘盈算已盘点
                wmsInventoryTaskDetail.setCheckStatus("1");//盘点状态设置为已盘1
                wmsInventoryTaskDetail.setDiffReason("py");//盘存差异原因 wcy=无差异；py=盘盈；pk=盘亏
                wmsInventoryTaskDetail.setCheckTime(new Date().getTime() + "");//盘盈检查时间 时间戳
                wmsInventoryTaskDetail.setQualityStatus("0");//盘盈质量状态设置为1 正常
                wmsInventoryTaskDetail.setDelFlag("0");//删除标志设置为0 正常
                wmsInventoryTaskDetail.setCreateTime(new Date().getTime() + "");//创建时间 时间戳
                wmsInventoryTaskDetail.setUpdateTime(new Date().getTime() + "");//更新时间 时间戳
                wmsInventoryTaskDetailDao.insert(wmsInventoryTaskDetail);
                L.i("新增一条盘盈数据:" + new Gson().toJson(wmsInventoryTaskDetail));
                //根据item.getTaskId()查询任务结果，在结果表更新盘存数量================================================================================
                WmsInventoryResultDao wmsInventoryResultDao = daoSession.getWmsInventoryResultDao();
                WmsInventoryResult wmsInventoryResult = wmsInventoryResultDao.queryBuilder().where(WmsInventoryResultDao.Properties.TaskId.eq(item.getTaskId())).unique();
                if (wmsInventoryResult != null) {
                    //更新总数量+1
                    wmsInventoryResult.setTotalItems(wmsInventoryResult.getTotalItems() + 1);
                    //更新已盘数量+1
                    wmsInventoryResult.setCountedItems(wmsInventoryResult.getCountedItems() + 1);
                    //更新盘盈数量+1
                    wmsInventoryResult.setSurplusItems(wmsInventoryResult.getSurplusItems() + 1);
                    wmsInventoryResultDao.update(wmsInventoryResult);
                    L.i("更新盘存结果数据:" + new Gson().toJson(wmsInventoryResult));

                    //将WmsInventoryTask的盘点数+1
                    WmsInventoryTaskDao wmsInventoryTaskDao = daoSession.getWmsInventoryTaskDao();
                    WmsInventoryTask wmsInventoryTask = wmsInventoryTaskDao.queryBuilder().where(WmsInventoryTaskDao.Properties.TaskId.eq(item.getTaskId())).unique();
                    if (wmsInventoryTask != null) {
                        wmsInventoryTask.setTotalItems(wmsInventoryTask.getTotalItems() + 1);
                        wmsInventoryTask.setCountedItems(wmsInventoryTask.getCountedItems() + 1);
                        if (wmsInventoryTask.getTotalItems() == wmsInventoryTask.getCountedItems()) {
                            wmsInventoryTask.setTaskStatus("2");//任务状态设置为2 已完成
                        }
                        wmsInventoryTaskDao.update(wmsInventoryTask);
                    }
                    //判断是否全部盘点完成 ：已盘数等于总盘点数，任务状态为2 已完成
                    if (wmsInventoryResult.getTotalItems() == wmsInventoryResult.getCountedItems() || wmsInventoryTask.getTaskStatus().equals("2")) {
                        new AlertDialogUtil(this).builder().setTitle("提示").setMsg("盘点已全部完成").setNegativeButton("我知道了", v -> {
                            closeMenu();
                        }).show();
                    }
                }
                //刷新页面数据
                initData();
            } else {
                ToastUtil.showShort("盘盈不在库存中");
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (RFIDSDKManager.getInstance().getRfidManager() != null) {
            RFIDSDKManager.getInstance().getRfidManager().stopInventory();
        }
        registerReceiver(false);
    }

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

    /**
     * @param register , ture register , false unregister
     */
    private void registerReceiver(boolean register) {
        if (register) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(ScanManager.ACTION_DECODE);
            registerReceiver(mReceiver, filter);
        } else {
            unregisterReceiver(mReceiver);
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isScan) {
                String action = intent.getAction();
                if (action.equals(ScanManager.ACTION_DECODE)) {
                    String barcodeStr = intent.getStringExtra(ScanManager.BARCODE_STRING_TAG);
                    if (!TextUtils.isEmpty(barcodeStr)) {
                        byte scanType = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
                        int engineType = OEMSymbologyId.getSymbologyId(App.mScanManager.getOutputParameter(7));
                        String barcodeFormat = OEMSymbologyId.stringFromSymbologyType(engineType, scanType);
                        L.i("条码格式：" + barcodeFormat + "\n" + barcodeStr);
                        mBinding.btnRfidOutbound.post(() -> {
                            String rfidTag = "IN2025122613490303880036";
                            updateTaskStatus(rfidTag, false);
                        });
                    }
                }
            }
        }
    };

//    /**
//     * 执行盘点成功
//     * 扫描任务
//     */
//    @Override
//    public void reviewScanTaskCheckSuccess(ReviewRfidTaskCheckModel model) {
//        if (model != null && model.getData() != null) {
//            ReviewRfidTaskCheckModel.DataBean data = model.getData();
//            //判断是否全部盘点完成 ：已盘数等于总盘点数
//            if (data.getTotalItems() == data.getCountedItems() || data.getCheckStatus().equals("2") || data.getCheckStatus().equals("3")) {
//                new AlertDialogUtil(this).builder().setTitle("提示").setMsg("盘点已完成").setNegativeButton("我知道了", v -> {
//                    closeMenu();
//                }).show();
//            }
//        }
//        //刷新数据
//        mPresenter.doReviewDetailList(this, item.getTaskId());
//        mPresenter.doReviewDetail(this, item.getTaskId());
//        mPresenter.doReviewResult(this, item.getTaskId());
//    }
//
//    /**
//     * 执行盘点成功
//     * RFID任务
//     */
//    @Override
//    public void reviewRfidTaskCheckSuccess(ReviewRfidTaskCheckModel model) {
//        if (model != null && model.getData() != null) {
//            ReviewRfidTaskCheckModel.DataBean data = model.getData();
//            //判断是否全部盘点完成 ：已盘数等于总盘点数||状态为已完成
//            if (data.getTotalItems() == data.getCountedItems() || data.getCheckStatus().equals("2") || data.getCheckStatus().equals("3")) {
//                new AlertDialogUtil(this).builder().setTitle("提示").setMsg("盘点已完成").setNegativeButton("我知道了", v -> {
//                    closeMenu();
//                }).show();
//            }
//        }
//        //刷新数据
//        mPresenter.doReviewDetailList(this, item.getTaskId());
//        mPresenter.doReviewDetail(this, item.getTaskId());
//        mPresenter.doReviewResult(this, item.getTaskId());
//    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (daoSession != null) {
            try {
                daoSession.clear();
                GreenDaoManager.getInstance().closeConnection();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
