package com.sxyz.rfid.ui.review;

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 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.ActivityReviewTaskDetailBinding;
import com.sxyz.rfid.presenter.IReviewPresenter;
import com.sxyz.rfid.presenter.imp.ReviewPresenterImpl;
import com.sxyz.rfid.presenter.model.ReviewDetailListModel;
import com.sxyz.rfid.presenter.model.ReviewDetailModel;
import com.sxyz.rfid.presenter.model.ReviewModel;
import com.sxyz.rfid.presenter.model.ReviewResultModel;
import com.sxyz.rfid.presenter.model.ReviewRfidTaskCheckModel;
import com.sxyz.rfid.presenter.model.ReviewTaskCheck;
import com.sxyz.rfid.presenter.view.IReviewView;
import com.sxyz.rfid.ui.review.adapter.ReviewDetailAdapter;
import com.sxyz.rfid.utils.L;
import com.sxyz.rfid.utils.LocalUtils;
import com.sxyz.rfid.utils.StringUtil;
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.List;

/**
 * 主要功能:  盘点任务详情
 *
 * @Description: 盘点任务详情
 * @Project: rfid-app
 * @Package: com.sxyz.rfid.ui.review
 * @author: chunyuanwu
 * @date: 2025年12月29日 18:18
 * @version: 1.0.0
 */
public class ReviewTaskActivity extends BaseActivity<ActivityReviewTaskDetailBinding> implements IReviewView {
    private ReviewModel.RowsBean item;
    private ReviewDetailAdapter mAdapter;
    private List<ReviewDetailListModel.RowsBean> list = new ArrayList<>();
    private IReviewPresenter mPresenter;
    private boolean isMenuOpen = false;
    private boolean isScan = false;
    private boolean isRfid = false;
    private int inventoryFlag = 0;
    private ScanCallback callback = new ScanCallback();

    @Override
    public void initParms(Bundle mBundle) {
        item = (ReviewModel.RowsBean) mBundle.getSerializable("item");
    }

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

    @Override
    protected void initView() {
        initToolBar("执行盘点");
        findViewById(R.id.iv_back).setOnClickListener(v -> {
            if (isMenuOpen) {
                closeMenu();
            } else {
                onBackPressed();
            }
        });
        mPresenter = new ReviewPresenterImpl(this);
        mPresenter.doReviewDetailList(this, item.getTaskId());
        mPresenter.doReviewDetail(this, item.getTaskId());
        mPresenter.doReviewResult(this, item.getTaskId());
        mBinding.rvOutboundDetails.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter = new ReviewDetailAdapter(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 ReviewDetailAdapter.OnItemClickListener() {
            @Override
            public void onCopy1ItemClick(int position, ReviewDetailListModel.RowsBean item) {
                StringUtil.copyToClipboard(mActivity, item.getBatchNo());
            }

            @Override
            public void onCopy2ItemClick(int position, ReviewDetailListModel.RowsBean 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() {
    }

    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(() -> {
                ReviewTaskCheck reviewTaskCheck = new ReviewTaskCheck();
                reviewTaskCheck.setTaskId(item.getTaskId());
                reviewTaskCheck.setCheckerId(LocalUtils.getUserId());
                reviewTaskCheck.setCheckerName(LocalUtils.getUserName1());
                List<String> rfidList = new ArrayList<>();
                //BQ001 PTLBQ20251218
                rfidList.add("PTLBQ20251218");
                reviewTaskCheck.setRfidList(rfidList);
                mPresenter.doReviewRfidTaskCheck(ReviewTaskActivity.this, reviewTaskCheck);
            });
        }

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

    @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)) {
//                        SoundTool.getInstance(App.getContext()).playBeep(1);
                        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(() -> {
                            ReviewTaskCheck reviewTaskCheck = new ReviewTaskCheck();
                            reviewTaskCheck.setTaskId(item.getTaskId());
                            reviewTaskCheck.setCheckerId(LocalUtils.getUserId());
                            reviewTaskCheck.setCheckerName(LocalUtils.getUserName1());
                            List<String> batchNoList = new ArrayList<>();
                            batchNoList.add("IN2025122613490303880036");
                            reviewTaskCheck.setBatchNoList(batchNoList);
                            L.i("reviewTaskCheck------" + new Gson().toJson(reviewTaskCheck));
                            mPresenter.doReviewScanTaskCheck(ReviewTaskActivity.this, reviewTaskCheck);
                        });
                    }
                }
            }
        }
    };

    @Override
    public void reviewSuccess(ReviewModel model) {

    }

    @Override
    public void reviewLoadMoreSuccess(ReviewModel model) {

    }

    @Override
    public void reviewDetailSuccess(ReviewDetailModel model) {
        ReviewDetailModel.DataBean item = model.getData();
        //任务编号
        mBinding.tvTaskNo.setText(item.getTaskNo());
        switch (item.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(item.getTaskName()) ? item.getTaskName() : "-");
        //仓库名称
        mBinding.txtWarehouseName.setText(!StringUtils.isEmpty(item.getWarehouseName()) ? item.getWarehouseName() : "-");
        //已盘数
        mBinding.txtReviewNumber.setText(item.getCountedItems() + "");
        //总盘点数
        mBinding.txtTotalNumber.setText(item.getTotalItems() + "");
        //出库人
        mBinding.txtRemark.setText(!StringUtils.isEmpty(item.getRemark()) ? item.getRemark() : "-");
    }

    @Override
    public void reviewDetailListSuccess(ReviewDetailListModel model) {
        list.clear();
        mAdapter.setList(model.getRows());
    }

    /**
     * 盘点结果
     *
     * @param model
     */
    @Override
    public void reviewResultSuccess(ReviewResultModel model) {
        if (model == null) {
            return;
        }
        if (model.getRows().isEmpty()) {
            return;
        }
        ReviewResultModel.RowsBean item = model.getRows().get(0);
        if (item == null) {
            return;
        }
        //总盘点数
        mBinding.tvTotalItems.setText(item.getTotalItems() + "");
        //已盘数
        mBinding.tvCountedItems.setText(item.getCountedItems() + "");
        //盘盈数
        mBinding.tvSurplusItems.setText(item.getSurplusItems() + "");
        //盘亏数
        mBinding.tvDeficitItems.setText(item.getDeficitItems() + "");
        //盘点进度 已盘数/总盘点数*100%
        int progress = (int) (item.getCountedItems() * 100.0 / item.getTotalItems());
        mBinding.tvProgress.setText(progress + "%");
        //进度条
        mBinding.progressBar.setProgress(progress);
    }

    @Override
    public void deleteReviewTaskSuccess() {

    }

    /**
     * 执行盘点成功
     * 扫描任务
     */
    @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 void stopReviewTaskSuccess() {

    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
