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.exception.BusinessException;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Device;
import com.haha.entity.DeviceInventory;
import com.haha.entity.Replenisher;
import com.haha.entity.ReplenishmentOrder;
import com.haha.entity.ReplenishmentOrderItem;
import com.haha.entity.dto.ReplenishDTO;
import com.haha.service.DeviceInventoryService;
import com.haha.service.DeviceService;
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;

    /**
     * 获取当前补货员信息
     */
    @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() {
        Replenisher replenisher = getCurrentReplenisher();

        // 获取补货员绑定的设备ID列表
        List<String> deviceIds = replenisherService.getBoundDeviceIds(replenisher.getId());
        if (deviceIds.isEmpty()) {
            return Result.success("查询成功", new ArrayList<>());
        }

        // 查询设备详情
        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 lowStockCount = 0;
            int zeroStockCount = 0;
            for (Map<String, Object> inv : inventoryList) {
                Integer stock = inv.get("stock") != null ? ((Number) inv.get("stock")).intValue() : 0;
                Integer warningThreshold = inv.get("warning_threshold") != null ? ((Number) inv.get("warning_threshold")).intValue() : 0;
                totalStock += stock;
                if (stock == 0) {
                    zeroStockCount++;
                } else if (stock <= warningThreshold) {
                    lowStockCount++;
                }
            }
            deviceInfo.put("totalStock", totalStock);
            deviceInfo.put("lowStockCount", lowStockCount);
            deviceInfo.put("zeroStockCount", zeroStockCount);
            deviceInfo.put("productCount", inventoryList.size());
            deviceInfo.put("inventoryList", inventoryList);

            result.add(deviceInfo);
        }

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

    /**
     * 获取设备库存详情
     *
     * @param deviceId 设备SN号
     */
    @GetMapping("/device/inventory/{deviceId}")
    public Result<Map<String, Object>> getDeviceInventory(@PathVariable String deviceId) {
        // 验证当前登录用户是补货员
        Replenisher replenisher = getCurrentReplenisher();

        // 验证该设备是否绑定到此补货员
        List<String> boundDeviceIds = replenisherService.getBoundDeviceIds(replenisher.getId());
        if (!boundDeviceIds.contains(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);

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

        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 inventory = deviceInventoryService.increaseStock(
                        dto.getDeviceId(),
                        item.getProductId(),
                        item.getProductCode(),
                        item.getProductName(),
                        item.getQuantity(),
                        item.getShelfNum(),
                        item.getPosition(),
                        replenisher.getId(),
                        replenisher.getName(),
                        null
                );

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

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

    /**
     * 获取补货员关联的补货单列表
     */
    @GetMapping("/orders")
    public Result<PageResult<ReplenishmentOrder>> getOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer status) {
        Replenisher replenisher = getCurrentReplenisher();
        List<String> deviceIds = replenisherService.getBoundDeviceIds(replenisher.getId());

        if (deviceIds.isEmpty()) {
            return Result.success("查询成功", new PageResult<>());
        }

        LambdaQueryWrapper<ReplenishmentOrder> wrapper = new LambdaQueryWrapper<>();
        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) {
        Replenisher replenisher = getCurrentReplenisher();
        ReplenishmentOrder order = replenishmentOrderService.getDetailWithItems(id);
        if (order == null) {
            return Result.error(404, "补货单不存在");
        }

        // 验证该补货单关联的设备是否绑定到当前补货员
        List<String> deviceIds = replenisherService.getBoundDeviceIds(replenisher.getId());
        if (!deviceIds.contains(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 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;
    }

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