package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haha.common.enums.ReplenishmentOrderStatusEnum;
import com.haha.common.exception.BusinessException;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.common.enums.StockRecordStatus;
import com.haha.entity.Device;
import com.haha.entity.DeviceInventory;
import com.haha.entity.InventoryLog;
import com.haha.entity.Replenisher;
import com.haha.entity.ReplenishmentOrder;
import com.haha.entity.ReplenishmentOrderItem;
import com.haha.entity.StockRecord;
import com.haha.entity.StockRecordItem;
import com.haha.entity.dto.ReplenishDTO;
import com.haha.mapper.ReplenishmentOrderItemMapper;
import com.haha.mapper.StockRecordItemMapper;
import com.haha.mapper.StockRecordMapper;
import com.haha.service.DeviceInventoryService;
import com.haha.service.DeviceService;
import com.haha.service.InventoryLogService;
import com.haha.service.LayerTemplateService;
import com.haha.service.ReplenisherService;
import com.haha.service.ReplenishmentOrderService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 补货员操作控制器
 * 提供补货员的设备查询、库存查看、补货操作等接口
 */
@Slf4j
@RestController
@RequestMapping("/replenisher")
@RequiredArgsConstructor
public class ReplenisherOperationController {

    private final ReplenisherService replenisherService;
    private final DeviceInventoryService deviceInventoryService;
    private final DeviceService deviceService;
    private final ReplenishmentOrderService replenishmentOrderService;
    private final LayerTemplateService layerTemplateService;
    private final InventoryLogService inventoryLogService;
    private final ReplenishmentOrderItemMapper orderItemMapper;
    private final StockRecordMapper stockRecordMapper;
    private final StockRecordItemMapper stockRecordItemMapper;

    /**
     * 获取当前补货员信息
     */
    @GetMapping("/my-info")
    public Result<Replenisher> getMyInfo() {
        // 验证当前登录用户是补货员
        Replenisher replenisher = getCurrentReplenisher();
        replenisher = replenisherService.getReplenisherDetail(replenisher.getId());
        if (replenisher == null) {
            return Result.error(404, "补货员不存在");
        }
        return Result.success("查询成功", replenisher);
    }

    /**
     * 获取补货员绑定的设备列表（含库存概览）
     */
    @GetMapping("/device/list")
    public Result<List<Map<String, Object>>> getDeviceList() {
        List<String> deviceIds = getAccessibleDeviceIds();
        if (deviceIds.isEmpty()) {
            return Result.success("查询成功", new ArrayList<>());
        }

        boolean isAdmin = isAdmin();
        Long operatorId = null;
        if (!isAdmin) {
            operatorId = getCurrentReplenisher().getId();
        }

        // 批量统计各设备补货单数量
        Map<String, Long> pendingOrderCountMap = new java.util.HashMap<>();
        Map<String, Long> submittedOrderCountMap = new java.util.HashMap<>();
        if (!deviceIds.isEmpty()) {
            var qwAll = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ReplenishmentOrder>()
                .select("device_id", "status", "COUNT(*) as cnt")
                .in("device_id", deviceIds)
                .in("status", 0, 1, 2)
                .groupBy("device_id", "status");
            List<Map<String, Object>> rows = replenishmentOrderService.listMaps(qwAll);
            for (Map<String, Object> row : rows) {
                String did = (String) row.get("device_id");
                Number cnt = (Number) row.get("cnt");
                Integer st = (Integer) row.get("status");
                if (did == null || cnt == null) continue;
                pendingOrderCountMap.merge(did, cnt.longValue(), Long::sum);
                if (st != null && (st == 1 || st == 2)) {
                    submittedOrderCountMap.merge(did, cnt.longValue(), Long::sum);
                }
            }
        }

        // 批量查询各设备首个待处理补货单（用于一键补货跳转）
        Map<String, Long> firstOrderIdMap = new java.util.HashMap<>();
        Map<String, String> firstOrderNoMap = new java.util.HashMap<>();
        if (!deviceIds.isEmpty()) {
            var firstOrderQw = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ReplenishmentOrder>()
                .select("device_id", "MAX(id) as order_id")
                .in("device_id", deviceIds)
                .in("status", 0, 1, 2)
                .groupBy("device_id");
            List<Map<String, Object>> firstRows = replenishmentOrderService.listMaps(firstOrderQw);
            for (Map<String, Object> row : firstRows) {
                String did = (String) row.get("device_id");
                Number oid = (Number) row.get("order_id");
                if (did != null && oid != null) firstOrderIdMap.put(did, oid.longValue());
            }
            // 补充查询订单号
            if (!firstOrderIdMap.isEmpty()) {
                var noQw = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ReplenishmentOrder>()
                    .select("id", "order_no")
                    .in("id", firstOrderIdMap.values());
                List<ReplenishmentOrder> orders = replenishmentOrderService.list(noQw);
                for (ReplenishmentOrder o : orders) {
                    firstOrderNoMap.put(String.valueOf(o.getId()), o.getOrderNo());
                }
            }
        }

        // 批量统计今日已补货设备
        java.time.LocalDate today = java.time.LocalDate.now();
        Map<String, Boolean> todayRestockedMap = new java.util.HashMap<>();
        if (!deviceIds.isEmpty() && !isAdmin) {
            var logQw = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<InventoryLog>()
                .select("DISTINCT device_id")
                .in("device_id", deviceIds)
                .eq("change_type", InventoryLog.TYPE_RESTOCK)
                .eq("operator_id", operatorId)
                .ge("create_time", today.atStartOfDay())
                .lt("create_time", today.plusDays(1).atStartOfDay());
            List<Map<String, Object>> logRows = inventoryLogService.listMaps(logQw);
            for (Map<String, Object> row : logRows) {
                String did = (String) row.get("device_id");
                if (did != null) todayRestockedMap.put(did, true);
            }
        }

        // 查询设备详情
        List<Map<String, Object>> result = new ArrayList<>();
        for (String deviceId : deviceIds) {
            Device device = deviceService.getDeviceBySn(deviceId);
            if (device == null) {
                continue;
            }

            Map<String, Object> deviceInfo = new HashMap<>();
            deviceInfo.put("deviceId", device.getDeviceId());
            deviceInfo.put("name", device.getName());
            deviceInfo.put("shopId", device.getShopId() != null ? device.getShopId().toString() : null);
            deviceInfo.put("status", device.getStatus());
            deviceInfo.put("statusLabel", getDeviceStatusLabel(device.getStatus()));
            deviceInfo.put("address", device.getAddress());

            // 查询该设备的库存概览
            List<Map<String, Object>> inventoryList = deviceInventoryService.getInventoryWithProduct(deviceId);
            int totalStock = 0;
            int standardStock = 0;
            int lowStockCount = 0;
            int zeroStockCount = 0;
            for (Map<String, Object> inv : inventoryList) {
                Integer stock = inv.get("stock") != null ? ((Number) inv.get("stock")).intValue() : 0;
                Integer invStandardStock = inv.get("standard_stock") != null ? ((Number) inv.get("standard_stock")).intValue() : 0;
                totalStock += stock;
                standardStock += invStandardStock;
                if (stock == 0) {
                    zeroStockCount++;
                } else if (invStandardStock > 0 && stock < invStandardStock) {
                    lowStockCount++;
                }
            }
            deviceInfo.put("totalStock", totalStock);
            deviceInfo.put("remainingStock", totalStock);
            deviceInfo.put("standardStock", standardStock);
            int inventoryPercent = standardStock > 0 ? (int) ((double) totalStock / standardStock * 100) : 0;
            deviceInfo.put("inventoryPercent", inventoryPercent);
            deviceInfo.put("lowStockCount", lowStockCount);
            deviceInfo.put("zeroStockCount", zeroStockCount);
            deviceInfo.put("productCount", inventoryList.size());
            deviceInfo.put("inventoryList", inventoryList);
            deviceInfo.put("pendingOrderCount", pendingOrderCountMap.getOrDefault(deviceId, 0L));
            deviceInfo.put("submittedOrderCount", submittedOrderCountMap.getOrDefault(deviceId, 0L));
            deviceInfo.put("todayReplenished", todayRestockedMap.containsKey(deviceId));
            deviceInfo.put("replenishOrderGenerated", pendingOrderCountMap.getOrDefault(deviceId, 0L) > 0);
            if (firstOrderIdMap.containsKey(deviceId)) {
                Long fid = firstOrderIdMap.get(deviceId);
                deviceInfo.put("pendingOrderId", fid);
                deviceInfo.put("pendingOrderNo", firstOrderNoMap.getOrDefault(String.valueOf(fid), ""));
            }

            result.add(deviceInfo);
        }

        return Result.success("查询成功", result);
    }

    /**
     * 获取设备待处理补货单列表（用于补货单切换）
     */
    @GetMapping("/device/{deviceId}/pending-orders")
    public Result<List<Map<String, Object>>> getDevicePendingOrders(@PathVariable String deviceId) {
        if (!canAccessDevice(deviceId)) {
            return Result.error(403, "您无权查看此设备");
        }

        var wrapper = new LambdaQueryWrapper<ReplenishmentOrder>()
            .eq(ReplenishmentOrder::getDeviceId, deviceId)
            .in(ReplenishmentOrder::getStatus, 0, 1, 2)
            .orderByDesc(ReplenishmentOrder::getCreateTime);
        List<ReplenishmentOrder> orders = replenishmentOrderService.list(wrapper);

        List<Map<String, Object>> result = new ArrayList<>();
        for (ReplenishmentOrder o : orders) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", o.getId());
            item.put("orderNo", o.getOrderNo());
            item.put("status", o.getStatus());
            item.put("statusLabel", ReplenishmentOrderStatusEnum.getLabelByCode(o.getStatus()).getLabel());
            item.put("createTime", o.getCreateTime() != null ? o.getCreateTime().toString() : null);
            result.add(item);
        }
        return Result.success("查询成功", result);
    }

    /**
     * 补货员远程开门
     */
    @PostMapping("/device/{deviceId}/open")
    public Result<Void> openDoor(@PathVariable String deviceId) {
        Replenisher replenisher = getCurrentReplenisher();
        List<String> boundIds = replenisherService.getBoundDeviceIds(replenisher.getId());
        if (!boundIds.contains(deviceId)) {
            return Result.error(403, "您无权操作此设备");
        }
        Device device = deviceService.getDeviceBySn(deviceId);
        if (device == null) {
            return Result.error(404, "设备不存在");
        }
        boolean success = deviceService.openDoor(device.getId(), "A");
        return success ? Result.success("开门指令已发送", null) : Result.error(500, "开门失败");
    }

    /**
     * 查询设备门状态（轻量轮询用）
     */
    @GetMapping("/device/{deviceId}/status")
    public Result<Map<String, Object>> getDeviceDoorStatus(@PathVariable String deviceId) {
        if (!canAccessDevice(deviceId)) {
            return Result.error(403, "您无权查看此设备");
        }
        Device device = deviceService.getDeviceBySn(deviceId);
        if (device == null) {
            return Result.error(404, "设备不存在");
        }
        String doorStatus = device.getDoorStatus();
        // OPENED=门已开, CLOSED=门已关, 其余视为未知
        boolean isOpen = "OPENED".equalsIgnoreCase(doorStatus);
        Map<String, Object> result = new HashMap<>();
        result.put("status", isOpen ? 1 : 0);
        result.put("statusLabel", isOpen ? "门已开" : "门已关");
        result.put("doorStatus", doorStatus);
        return Result.success("查询成功", result);
    }

    /**
     * 获取设备库存详情
     *
     * @param deviceId 设备SN号
     */
    @GetMapping("/device/inventory/{deviceId}")
    public Result<Map<String, Object>> getDeviceInventory(@PathVariable String deviceId) {
        if (!canAccessDevice(deviceId)) {
            return Result.error(403, "您无权查看此设备的库存");
        }

        // 查询设备信息
        Device device = deviceService.getDeviceBySn(deviceId);
        if (device == null) {
            return Result.error(404, "设备不存在");
        }

        // 查询库存详情
        List<Map<String, Object>> inventoryList = deviceInventoryService.getInventoryWithProduct(deviceId);

        // 构建库存索引：productCode → { productId, stock, standardStock }
        Map<String, Map<String, Object>> invMap = new HashMap<>();
        for (Map<String, Object> inv : inventoryList) {
            String code = String.valueOf(inv.getOrDefault("productCode", "")).trim();
            if (!code.isEmpty()) {
                invMap.put(code, inv);
            }
        }

        // 获取设备层模版，合并库存数据到楼层结构
        List<Map<String, Object>> floors = new ArrayList<>();
        try {
            Map<String, Object> config = layerTemplateService.getProductConfig(deviceId);
            if (config != null && config.get("floors") != null) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> templateFloors = (List<Map<String, Object>>) config.get("floors");
                for (Map<String, Object> floor : templateFloors) {
                    Map<String, Object> mergedFloor = new HashMap<>(floor);
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> slots = (List<Map<String, Object>>) floor.get("slots");
                    List<Map<String, Object>> mergedSlots = new ArrayList<>();

                    if (slots != null) {
                        for (Map<String, Object> slot : slots) {
                            Map<String, Object> mergedSlot = new HashMap<>();
                            String productCode = String.valueOf(slot.getOrDefault("productId", "")).trim();
                            mergedSlot.put("slotId", slot.get("slotId"));
                            mergedSlot.put("productCode", productCode);
                            mergedSlot.put("productName", slot.getOrDefault("productName", productCode));
                            mergedSlot.put("productImage", slot.getOrDefault("productImage", ""));

                            // 从模板取标准库存
                            Object templateStock = slot.get("stock");
                            mergedSlot.put("standardStock", templateStock != null ? templateStock : 0);

                            // 从库存记录取实际数据
                            Map<String, Object> inv = invMap.get(productCode);
                            if (inv != null) {
                                mergedSlot.put("currentStock", inv.getOrDefault("stock", 0));
                                mergedSlot.put("inventoryProductId", inv.getOrDefault("productId", null));
                                // 库存记录的 standardStock 优先（更准确）
                                if (inv.get("standardStock") != null) {
                                    mergedSlot.put("standardStock", inv.get("standardStock"));
                                }
                            } else {
                                mergedSlot.put("currentStock", 0);
                                mergedSlot.put("inventoryProductId", null);
                            }
                            mergedSlots.add(mergedSlot);
                        }
                    }
                    mergedFloor.put("slots", mergedSlots);
                    floors.add(mergedFloor);
                }
            }
        } catch (Exception e) {
            log.warn("获取设备层模版失败, deviceId={}", deviceId, e);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("deviceId", device.getDeviceId());
        result.put("name", device.getName());
        result.put("address", device.getAddress());
        result.put("inventoryList", inventoryList);
        result.put("floors", floors);

        return Result.success("查询成功", result);
    }

    /**
     * 执行补货操作
     *
     * @param dto 补货参数
     */
    @PostMapping("/stock/replenish")
    public Result<Object> replenishStock(@Valid @RequestBody ReplenishDTO dto) {
        Replenisher replenisher = getCurrentReplenisher();

        // 验证该设备是否绑定到此补货员
        List<String> boundDeviceIds = replenisherService.getBoundDeviceIds(replenisher.getId());
        if (!boundDeviceIds.contains(dto.getDeviceId())) {
            return Result.error(403, "您无权对此设备进行补货操作");
        }

        int successCount = 0;
        List<Map<String, Object>> results = new ArrayList<>();

        for (ReplenishDTO.ReplenishItem item : dto.getItems()) {
            try {
                // 补货前获取当前库存
                DeviceInventory beforeInv = deviceInventoryService.getByDeviceAndProduct(dto.getDeviceId(), item.getProductId());
                int beforeStock = beforeInv != null ? beforeInv.getStock() : 0;

                DeviceInventory inventory = deviceInventoryService.increaseStock(
                        dto.getDeviceId(),
                        item.getProductId(),
                        item.getProductCode(),
                        item.getProductName(),
                        item.getQuantity(),
                        item.getShelfNum(),
                        item.getPosition(),
                        replenisher.getId(),
                        replenisher.getName(),
                        null
                );

                // 回写订单明细：实际补货数量、补货前/后库存
                if (dto.getOrderId() != null) {
                    ReplenishmentOrderItem orderItem = orderItemMapper.selectOne(
                            new LambdaQueryWrapper<ReplenishmentOrderItem>()
                                    .eq(ReplenishmentOrderItem::getOrderId, dto.getOrderId())
                                    .eq(ReplenishmentOrderItem::getProductCode, item.getProductCode()));
                    if (orderItem != null) {
                        orderItem.setActualQuantity(item.getQuantity());
                        orderItem.setBeforeStock(beforeStock);
                        orderItem.setAfterStock(inventory.getStock());
                        orderItemMapper.updateById(orderItem);
                    }
                }

                successCount++;
                Map<String, Object> itemResult = new HashMap<>();
                itemResult.put("productId", item.getProductId());
                itemResult.put("productName", item.getProductName());
                itemResult.put("quantity", item.getQuantity());
                itemResult.put("afterStock", inventory.getStock());
                itemResult.put("success", true);
                results.add(itemResult);

                log.info("[补货操作] 补货成功: deviceId={}, productId={}, quantity={}, afterStock={}",
                        dto.getDeviceId(), item.getProductId(), item.getQuantity(), inventory.getStock());
            } catch (Exception e) {
                log.error("[补货操作] 补货失败: deviceId={}, productId={}, quantity={}, error={}",
                        dto.getDeviceId(), item.getProductId(), item.getQuantity(), e.getMessage());
                Map<String, Object> itemResult = new HashMap<>();
                itemResult.put("productId", item.getProductId());
                itemResult.put("productName", item.getProductName());
                itemResult.put("quantity", item.getQuantity());
                itemResult.put("success", false);
                itemResult.put("error", e.getMessage());
                results.add(itemResult);
            }
        }

        // 创建上货记录
        if (successCount > 0) {
            try {
                StockRecord record = new StockRecord();
                record.setDeviceId(dto.getDeviceId());
                record.setStockType(2); // 补货
                record.setStockerId(replenisher.getId());
                record.setStockerName(replenisher.getName());
                record.setStockerPhone(replenisher.getPhone());
                record.setStatus(StockRecordStatus.COMPLETED.getCode());
                record.setTotalItems(successCount);
                record.setTotalQuantity(results.stream()
                        .filter(r -> Boolean.TRUE.equals(r.get("success")))
                        .mapToInt(r -> ((Number) r.get("quantity")).intValue()).sum());
                record.setStartTime(java.time.LocalDateTime.now());
                record.setEndTime(java.time.LocalDateTime.now());
                record.setCreateTime(java.time.LocalDateTime.now());
                record.setUpdateTime(java.time.LocalDateTime.now());
                stockRecordMapper.insert(record);

                // 创建明细
                for (Map<String, Object> r : results) {
                    if (!Boolean.TRUE.equals(r.get("success"))) continue;
                    StockRecordItem item = new StockRecordItem();
                    item.setRecordId(record.getId());
                    item.setDeviceId(dto.getDeviceId());
                    item.setProductId(((Number) r.get("productId")).longValue());
                    item.setProductName((String) r.get("productName"));
                    item.setQuantity(((Number) r.get("quantity")).intValue());
                    item.setAfterStock(((Number) r.get("afterStock")).intValue());
                    item.setCreateTime(java.time.LocalDateTime.now());
                    stockRecordItemMapper.insert(item);
                }

                log.info("[补货操作] 上货记录创建成功: recordId={}, items={}", record.getId(), successCount);
            } catch (Exception e) {
                log.error("[补货操作] 创建上货记录失败: deviceId={}, error={}", dto.getDeviceId(), e.getMessage());
            }
        }

        // 如果关联了补货单，自动完成
        if (dto.getOrderId() != null && successCount > 0) {
            try {
                ReplenishmentOrder order = replenishmentOrderService.getById(dto.getOrderId());
                if (order != null && order.getStatus() != 3 && order.getStatus() != 4) {
                    order.setStatus(3);
                    order.setUpdateTime(java.time.LocalDateTime.now());
                    replenishmentOrderService.updateById(order);
                    log.info("[补货操作] 自动完成补货单: orderId={}", dto.getOrderId());
                }
            } catch (Exception e) {
                log.warn("[补货操作] 自动完成补货单失败: orderId={}, error={}", dto.getOrderId(), e.getMessage());
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total", dto.getItems().size());
        result.put("success", successCount);
        result.put("details", results);

        return Result.success(String.format("补货完成，成功%d项，失败%d项", successCount, dto.getItems().size() - successCount), result);
    }

    /**
     * 补货员盘点修正库存
     * 直接设置指定商品的库存为 newStock
     */
    @PostMapping("/stock/adjust")
    public Result<DeviceInventory> adjustStock(@RequestBody Map<String, Object> body) {
        Replenisher replenisher = getCurrentReplenisher();

        String deviceId = (String) body.get("deviceId");
        Object productIdObj = body.get("productId");
        Object newStockObj = body.get("newStock");
        String remark = (String) body.getOrDefault("remark", "补货员盘点修正");

        if (deviceId == null || productIdObj == null || newStockObj == null) {
            return Result.error(400, "deviceId, productId, newStock 不能为空");
        }

        if (!canAccessDevice(deviceId)) {
            return Result.error(403, "您无权对此设备进行操作");
        }

        // 兼容前端传 String（雪花ID过长JS自动转字符串）或 Number
        Long productId = toLong(productIdObj);
        Integer newStock = toInt(newStockObj);
        if (productId == null || newStock == null) {
            return Result.error(400, "productId, newStock 格式不正确");
        }

        DeviceInventory inventory = deviceInventoryService.adjustStock(
                deviceId, productId, newStock, remark,
                replenisher.getId(), replenisher.getName());

        return Result.success("库存修正成功", inventory);
    }

    /**
     * 获取补货员关联的补货单列表
     */
    @GetMapping("/orders")
    public Result<PageResult<ReplenishmentOrder>> getOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<ReplenishmentOrder> wrapper = new LambdaQueryWrapper<>();
        if (!isAdmin()) {
            Replenisher replenisher = getCurrentReplenisher();
            List<String> deviceIds = replenisherService.getBoundDeviceIds(replenisher.getId());
            if (deviceIds.isEmpty()) return Result.success("查询成功", new PageResult<>());
            wrapper.in(ReplenishmentOrder::getDeviceId, deviceIds);
        }
        if (status != null) {
            wrapper.eq(ReplenishmentOrder::getStatus, status);
        }
        wrapper.orderByDesc(ReplenishmentOrder::getCreateTime);

        Page<ReplenishmentOrder> pageObj = new Page<>(page, pageSize);
        IPage<ReplenishmentOrder> result = replenishmentOrderService.page(pageObj, wrapper);

        // 填充状态标签和设备名称
        for (ReplenishmentOrder order : result.getRecords()) {
            var statusLabel = com.haha.common.enums.ReplenishmentOrderStatusEnum.getLabelByCode(order.getStatus());
            order.setStatusLabel(statusLabel.getLabel());
            order.setStatusColor(statusLabel.getColor());
            // 查设备名称
            Device dev = deviceService.getDeviceBySn(order.getDeviceId());
            if (dev != null) {
                order.setDeviceName(dev.getName());
            }
        }

        return Result.success("查询成功", PageResult.of(result));
    }

    /**
     * 获取补货单详情（含商品明细和图片）
     */
    @GetMapping("/orders/{id}")
    public Result<Map<String, Object>> getOrderDetail(@PathVariable Long id) {
        ReplenishmentOrder order = replenishmentOrderService.getDetailWithItems(id);
        if (order == null) {
            return Result.error(404, "补货单不存在");
        }

        if (!isAdmin() && !canAccessDevice(order.getDeviceId())) {
            return Result.error(403, "您无权查看此补货单");
        }

        List<ReplenishmentOrderItem> items = replenishmentOrderService.getItems(id);

        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("items", items);
        return Result.success("查询成功", result);
    }

    private boolean isAdmin() {
        String userType = StpUtil.getTokenSession().getString("userType");
        return !"REPLENISHER".equals(userType);
    }

    /**
     * 获取当前登录的补货员（仅补货员可调用，运营人员返回null）
     */
    private Replenisher getCurrentReplenisher() {
        String userType = StpUtil.getTokenSession().getString("userType");
        if (!"REPLENISHER".equals(userType)) {
            log.warn("非补货员用户尝试访问补货员专用接口");
            throw new BusinessException(403, "仅补货员可执行此操作");
        }
        String loginId = StpUtil.getLoginIdAsString();
        Replenisher replenisher = replenisherService.getById(loginId);
        if (replenisher == null) {
            throw new BusinessException(404, "补货员不存在");
        }
        return replenisher;
    }

    /**
     * 获取补货员绑定的设备ID列表，运营人员返回全部设备ID
     */
    private List<String> getAccessibleDeviceIds() {
        if (isAdmin()) {
            return deviceService.list().stream()
                .map(Device::getDeviceId)
                .filter(id -> id != null && !id.isEmpty())
                .collect(Collectors.toList());
        }
        Replenisher replenisher = getCurrentReplenisher();
        return replenisherService.getBoundDeviceIds(replenisher.getId());
    }

    /**
     * 验证设备访问权限（运营人员可访问全部，补货员仅可访问已绑定设备）
     */
    private boolean canAccessDevice(String deviceId) {
        if (isAdmin()) return true;
        Replenisher replenisher = getCurrentReplenisher();
        return replenisherService.getBoundDeviceIds(replenisher.getId()).contains(deviceId);
    }

    /**
     * 获取设备状态标签
     */
    private String getDeviceStatusLabel(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "在线";
            case 0: return "离线";
            case 2: return "故障";
            default: return "未知";
        }
    }

    /**
     * 安全转 Long，兼容前端传 String（雪花ID过长JS自动转字符串）或 Number
     */
    private Long toLong(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Number) return ((Number) obj).longValue();
        if (obj instanceof String) {
            try {
                return Long.parseLong((String) obj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 安全转 Integer，兼容前端传 String 或 Number
     */
    private Integer toInt(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Number) return ((Number) obj).intValue();
        if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }
}
