package com.sxyz.rfid.ui.out;

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

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

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.ActivityOutboundBinding;
import com.sxyz.rfid.presenter.IOutBoundPresenter;
import com.sxyz.rfid.presenter.imp.OutBoundPresenterImpl;
import com.sxyz.rfid.presenter.model.OperatorBean;
import com.sxyz.rfid.presenter.model.OutBoundDetailModel;
import com.sxyz.rfid.presenter.model.OutboundFlowingWaterModel;
import com.sxyz.rfid.presenter.model.OutboundFridModel;
import com.sxyz.rfid.presenter.model.OutboundModel;
import com.sxyz.rfid.presenter.view.IOutBoundView;
import com.sxyz.rfid.ui.out.adapter.OutBoundDetailsAdapter;
import com.sxyz.rfid.ui.out.adapter.OutBoundMeauAdapter;
import com.sxyz.rfid.utils.L;
import com.sxyz.rfid.utils.LocalUtils;
import com.sxyz.rfid.utils.ToastUtil;
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;
import java.util.Set;
import java.util.stream.Collectors;

import sql.com.yz.db.DaoSession;

/**
 * 主要功能: 出库
 *
 * @Description: 出库
 * @Project: rfid-app
 * @Package: com.sxyz.rfid.ui.ui.out
 * @author: chunyuanwu
 * @date: 2025年12月27日 16:40
 * @version: 1.0.0
 */
public class OutboundActivity extends BaseActivity<ActivityOutboundBinding> implements IOutBoundView {
    private DaoSession daoSession;
    private OutBoundDetailsAdapter mOutBoundAdapter;
    private List<OutBoundDetailModel.RowsBean> list = new ArrayList<>();
    private List<OutboundFridModel.RowsBean> outBoundFridList = new ArrayList<>();
    private OutboundModel.RowsBean item;
    private IOutBoundPresenter mPresenter;
    private boolean isMenuOpen = false;
    private OutBoundMeauAdapter mOutBoundMeauAdapter;
    private boolean isScan = false;
    private boolean isRfid = false;
    private ScanCallback callback = new ScanCallback();

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

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

    @Override
    protected void initView() {
        initToolBarTitle("出库单明细");
        findViewById(R.id.iv_back).setOnClickListener(v -> {
            if (isMenuOpen) {
                closeMenu();
            } else {
                onBackPressed();
            }
        });
        mPresenter = new OutBoundPresenterImpl(this);
        mPresenter.doOutBoundDetailList(this, item.getOrderId());
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mOutBoundAdapter = new OutBoundDetailsAdapter(R.layout.item_outbound_details, list);
        mBinding.recyclerView.setAdapter(mOutBoundAdapter);
        //出库单-RFID列表
        mBinding.rvOutBoundFrid.setLayoutManager(new LinearLayoutManager(mActivity));
        mOutBoundMeauAdapter = new OutBoundMeauAdapter(R.layout.item_pop, outBoundFridList);
        mBinding.rvOutBoundFrid.setAdapter(mOutBoundMeauAdapter);

//        Out model = new Out();
//        model.setName("111");
//        daoSession = GreenDaoManager.getInstance().getDaoSession();
//        daoSession.insert(model);
    }

    @Override
    protected void setListener() {
        if (RFIDSDKManager.getInstance().getRfidManager() != null) {
            //注册rfid回调
            RFIDSDKManager.getInstance().getRfidManager().registerCallback(callback);
        }
        //如果菜单打开，点击空白区域关闭菜单
        mBinding.ivClose.setOnClickListener(v -> {
            if (isMenuOpen) {
                closeMenu();
            }
        });
        //点击出库明细-查询流量表
        mOutBoundAdapter.setOnItemClickListener(new OutBoundDetailsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, OutBoundDetailModel.RowsBean item) {
                IOutBoundPresenter presenter = new OutBoundPresenterImpl(new IOutBoundView() {
                    @Override
                    public void outBoundSuccess(OutboundModel model) {

                    }

                    @Override
                    public void outBoundLoadMoreSuccess(OutboundModel model) {

                    }

                    @Override
                    public void outBoundDetailSuccess(OutBoundDetailModel model) {

                    }

                    @Override
                    public void outBoundFlowingWaterSuccess(OutboundFlowingWaterModel model) {
                        item.setDetailList(model.getRows());
                        mOutBoundAdapter.notifyItemChanged(position);
                    }

                    @Override
                    public void outBoundCancelSuccess() {

                    }

                    @Override
                    public void outBoundDetailCancelSuccess() {

                    }

                    @Override
                    public void outBoundFridSuccess(OutboundFridModel model) {

                    }

                    @Override
                    public void outSubmitBoundFridSuccess() {

                    }
                });
                presenter.doOutBoundFlowingWaterList(OutboundActivity.this, item.getItemId());
            }

            /**
             * 出库明细-撤销操作
             *
             * @param position 出库明细位置
             * @param item 出库明细
             */
            @Override
            public void onItemCancelClick(int position, OutBoundDetailModel.RowsBean item) {
                //弹窗
                new AlertDialog.Builder(OutboundActivity.this).setTitle("确认撤销吗？").setPositiveButton("确认", (dialog, which) -> {
                    mPresenter.doOutBoundDetailCancel(OutboundActivity.this, item.getItemId());
                }).setNegativeButton("取消", null).show();
            }

            /**
             * 出库流水-撤销操作
             *
             * @param position 出库流水位置
             * @param item 出库流水
             */
            @Override
            public void onItemCancelChildClick(int position, OutboundFlowingWaterModel.RowsBean item) {
                //弹窗
                new AlertDialog.Builder(OutboundActivity.this).setTitle("确认撤销吗？").setPositiveButton("确认", (dialog, which) -> {
                    mPresenter.doOutBoundCancel(OutboundActivity.this, item.getRelationId());
                }).setNegativeButton("取消", null).show();
            }
        });
        //rfid出库
        mBinding.btnRfidOutbound.setOnClickListener(v -> {
            if (!isMenuOpen) {
                mBinding.tvTitle.setText("RFID出库");
                mBinding.tvTitle2.setText("请识别 RFID 进行出库");
                mBinding.tvNoData.setText("请识别 RFID 进行出库");
                isRfid = true;
                isScan = false;
                openMenu();
            }
        });

        //扫码出库
        mBinding.btnScanOutbound.setOnClickListener(v -> {
            if (!isMenuOpen) {
                mBinding.tvTitle.setText("扫码出库");
                mBinding.tvTitle2.setText("请扫描商品二维码进行出库");
                mBinding.tvNoData.setText("请扫描商品二维码进行出库");
                isScan = true;
                isRfid = false;
                openMenu();
            }
        });
        //rfid出库-点击确认出库
        mOutBoundMeauAdapter.setOnItemClickListener(new OutBoundMeauAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, OutboundFridModel.RowsBean item) {

            }

            @Override
            public void onConfirmOutClick(int layoutPosition, OutboundFridModel.RowsBean dataBean, String inputNum) {
                outPosition = layoutPosition;
                //弹窗确认出库
                new AlertDialog.Builder(OutboundActivity.this).setTitle("确认出库吗？").setPositiveButton("确认", (dialog, which) -> {
                    OperatorBean operatorBean = new OperatorBean();
                    operatorBean.setNum(inputNum);//设置出库数量
                    operatorBean.setOperatorId(LocalUtils.getUserId());//设置用户ID
                    operatorBean.setOrderId(dataBean.getOrderId());//设置订单ID
                    operatorBean.setRfidTag(dataBean.getRfidTag());//设置RFID标签
                    L.i("rfidTag:" + new Gson().toJson(operatorBean));
                    mPresenter.doOutBoundFrid(OutboundActivity.this, operatorBean);
                }).setNegativeButton("取消", null).show();
            }

            @Override
            public void onCancelOutClick(int layoutPosition, OutboundFridModel.RowsBean dataBean) {
                //弹窗确认撤销
                new AlertDialog.Builder(OutboundActivity.this).setTitle("确认取消出库吗？").setPositiveButton("确认", (dialog, which) -> {
                    outBoundFridList.remove(layoutPosition);
                    mOutBoundMeauAdapter.notifyItemRemoved(layoutPosition);
                    mBinding.llNothing.setVisibility(outBoundFridList.isEmpty() ? View.VISIBLE : View.GONE);
                }).setNegativeButton("取消", null).show();
            }
        });
    }

    private int outPosition = -1;

    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;
        //关闭扫码
        App.mScanManager.stopDecode();
        App.mScanManager.closeScanner();
        //关闭rfid
        if (RFIDSDKManager.getInstance().getRfidManager() != null) {
            RFIDSDKManager.getInstance().getRfidManager().stopInventory();
        }
        isScan = false;
        isRfid = false;
    }

    /**
     * 按键按下 开启扫描
     **/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == 515 || keyCode == 523) && event.getRepeatCount() == 0) {
            //RFID识别盘点
            if (isRfid) {
                RFIDSDKManager.getInstance().getRfidManager().inventorySingle();//单次盘点
            }
            //二维码扫描
            if (isScan) {
                App.mScanManager.startDecode();
            }
        }
        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();
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 回调
     */
    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(() -> {
                mPresenter.doGetOutBoundFridList(OutboundActivity.this, "BQ005");
            });
        }

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


    @Override
    protected void initData() {

    }

    @Override
    public void outBoundSuccess(OutboundModel model) {

    }

    @Override
    public void outBoundLoadMoreSuccess(OutboundModel model) {

    }

    @Override
    public void outBoundDetailSuccess(OutBoundDetailModel model) {
        list.clear();
        mOutBoundAdapter.setList(model.getRows());
    }

    @Override
    public void outBoundFlowingWaterSuccess(OutboundFlowingWaterModel model) {
    }

    @Override
    public void outBoundCancelSuccess() {
        ToastUtil.showShort("撤销成功");
        mPresenter.doOutBoundDetailList(this, item.getOrderId());
    }

    @Override
    public void outBoundDetailCancelSuccess() {
        ToastUtil.showShort("撤销成功");
        mPresenter.doOutBoundDetailList(this, item.getOrderId());
    }

    @Override
    public void outBoundFridSuccess(OutboundFridModel model) {
        List<OutboundFridModel.RowsBean> addFridList = model.getRows();

        // 检查标签列表是否为空
        if (addFridList == null || addFridList.isEmpty()) {
            ToastUtil.showShort("识别标签返回数据为空");
            mBinding.llNothing.setVisibility(outBoundFridList.isEmpty() ? View.VISIBLE : View.GONE);
            return;
        }
        // 检查出库单列表是否为空
        if (list == null || list.isEmpty()) {
            ToastUtil.showShort("出库单为空");
            mBinding.llNothing.setVisibility(outBoundFridList.isEmpty() ? View.VISIBLE : View.GONE);
            return;
        }
        // 检查addFridList中是否有materialId存在于出库单中
        boolean isAnyMaterialExist = addFridList.stream().anyMatch(item -> list.stream().anyMatch(item2 -> item2.getMaterialId() == item.getMaterialId()));
        if (!isAnyMaterialExist) {
            ToastUtil.showShort("标签不在出库单中");
            mBinding.llNothing.setVisibility(outBoundFridList.isEmpty() ? View.VISIBLE : View.GONE);
            return;
        }

        if (outBoundFridList.isEmpty()) {
            // 直接添加识别的标签
            outBoundFridList.addAll(addFridList);
        } else {
            //根据outBoundFridList内的materialId去重、使用Set快速去重
            Set<Integer> existingMaterialIds = outBoundFridList.stream().map(OutboundFridModel.RowsBean::getMaterialId).collect(Collectors.toSet());
            // 只添加不存在的materialId
            List<OutboundFridModel.RowsBean> newItems = addFridList.stream().filter(item -> !existingMaterialIds.contains(item.getMaterialId())).collect(Collectors.toList());
            if (!newItems.isEmpty()) {
                outBoundFridList.addAll(newItems);
                mOutBoundMeauAdapter.notify();
            }
        }
        //将outBoundFridList中的materialId与list中的materialId进行匹配，将list中的数据赋值给outBoundFridList
        for (OutboundFridModel.RowsBean item : outBoundFridList) {
            for (OutBoundDetailModel.RowsBean item2 : list) {
                if (item.getMaterialId() == item2.getMaterialId()) {
                    item.setPlanQuantity(item2.getPlanQuantity());
                    item.setActualQuantity(item2.getActualQuantity());
                    item.setOrderId(item2.getOrderId());
                    break;
                }
            }
        }
        // 刷新列表显示
        mOutBoundMeauAdapter.setList(outBoundFridList);
        mBinding.llNothing.setVisibility(!outBoundFridList.isEmpty() ? View.GONE : View.VISIBLE);
    }

    @Override
    public void outSubmitBoundFridSuccess() {
        ToastUtil.showShort("拣货成功");
        outBoundFridList.remove(outPosition);
        mOutBoundMeauAdapter.notifyItemRemoved(outPosition);
        mBinding.llNothing.setVisibility(outBoundFridList.isEmpty() ? View.VISIBLE : View.GONE);
        //刷新出库单详情
        mPresenter.doOutBoundDetailList(this, item.getOrderId());
    }

    @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);
//                        SoundTool.getInstance(App.getContext()).playBeep(1);
                        L.i("条码格式：" + barcodeFormat + "\n" + barcodeStr);
                        mBinding.btnRfidOutbound.post(() -> {
                            mPresenter.doGetOutBoundFridList(OutboundActivity.this, "BQ005");
                        });
                    }
                }
            }

        }
    };
}
