package com.erp.tenant.controller.stock;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;
import com.erp.tenant.config.TenantContext;
import com.erp.tenant.dto.stock.StockPageResponse;
import com.erp.tenant.dto.stock.StockPageResponse.StockItemDTO;
import com.erp.tenant.entity.stock.Stock;
import com.erp.tenant.service.stock.StockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户端库存控制器
 * 功能：库存查看
 */
@Slf4j
@RestController
@RequestMapping("/api/tenant/stocks")
@RequiredArgsConstructor
public class StockController {

    private final StockService stockService;
    private static final DateTimeFormatter DT_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 库存列表
     * GET /api/tenant/stocks
     */
    @GetMapping
    public ApiResponse<PageResponse<StockItemDTO>> getStockList(
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        IPage<Stock> stockPage = stockService.getStockPage(tenantId, warehouseId, page, pageSize);

        var items = stockPage.getRecords().stream()
                .map(this::toStockItemDTO)
                .collect(Collectors.toList());

        PageResponse<StockItemDTO> response = PageResponse.<StockItemDTO>builder()
                .list(items)
                .total(stockPage.getTotal())
                .page(stockPage.getCurrent())
                .pageSize(stockPage.getSize())
                .totalPages(stockPage.getPages())
                .build();

        return ApiResponse.success(response);
    }

    /**
     * 库存预警列表
     * GET /api/tenant/stocks/alerts
     */
    @GetMapping("/alerts")
    public ApiResponse<PageResponse<StockItemDTO>> getAlertList(
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String alertLevel,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        IPage<Stock> alertPage = stockService.getAlertPage(
                tenantId, warehouseId, keyword, alertLevel, page, pageSize);

        var items = alertPage.getRecords().stream()
                .map(this::toStockItemDTO)
                .collect(Collectors.toList());

        PageResponse<StockItemDTO> response = PageResponse.<StockItemDTO>builder()
                .list(items)
                .total(alertPage.getTotal())
                .page(alertPage.getCurrent())
                .pageSize(alertPage.getSize())
                .totalPages(alertPage.getPages())
                .build();

        return ApiResponse.success(response);
    }

    /**
     * 预警摘要
     * GET /api/tenant/stocks/alerts/summary
     */
    @GetMapping("/alerts/summary")
    public ApiResponse<?> getAlertSummary() {
        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        StockService.StockAlertSummary summary = stockService.getAlertSummary(tenantId);
        return ApiResponse.success(Map.of(
                "critical", summary.critical,
                "warning", summary.warning,
                "total", summary.total,
                "globalThreshold", summary.globalThreshold
        ));
    }

    /**
     * 库存详情
     * GET /api/tenant/stocks/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<StockItemDTO> getStockDetail(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        Stock stock = stockService.getStockDetail(tenantId, id);
        if (stock == null) {
            return ApiResponse.error(404, "库存记录不存在");
        }
        return ApiResponse.success(toStockItemDTO(stock));
    }

    private StockItemDTO toStockItemDTO(Stock stock) {
        int available = stock.calcAvailable();
        int threshold = stock.getWarningThreshold() != null ? stock.getWarningThreshold() : 10;
        String alertLevel = available <= threshold * 0.5 ? "critical" : (available <= threshold ? "warning" : null);

        return StockItemDTO.builder()
                .id(stock.getId())
                .warehouseId(stock.getWarehouseId())
                .warehouseName(stock.getWarehouseName())
                .skuCode(stock.getSkuCode())
                .skuName(stock.getSkuName())
                .quantity(stock.getQuantity() != null ? stock.getQuantity() : 0)
                .lockedQuantity(stock.getLockedQuantity() != null ? stock.getLockedQuantity() : 0)
                .reservedQuantity(stock.getReservedQuantity() != null ? stock.getReservedQuantity() : 0)
                .defectiveQuantity(stock.getDefectiveQuantity() != null ? stock.getDefectiveQuantity() : 0)
                .availableQuantity(available)
                .warningThreshold(threshold)
                .alertLevel(alertLevel)
                .shortageCount(Math.max(0, threshold - available))
                .lastInboundAt(stock.getLastInboundAt() != null ? stock.getLastInboundAt().format(DT_FORMAT) : null)
                .lastOutboundAt(stock.getLastOutboundAt() != null ? stock.getLastOutboundAt().format(DT_FORMAT) : null)
                .updatedAt(stock.getUpdatedAt() != null ? stock.getUpdatedAt().format(DT_FORMAT) : null)
                .build();
    }
}
