package com.erp.inventory.controller;

import com.erp.inventory.dto.*;
import com.erp.inventory.entity.Stock;
import com.erp.inventory.service.StockCheckService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;

/**
 * 库存盘点控制器
 * 对应PHP StockController
 * 
 * API Endpoints:
 * - GET  /stocks              - 库存列表（分页，支持搜索、仓库筛选、预警筛选）
 * - GET  /stocks/show         - 库存详情（按仓库+SKU）
 * - POST /stocks/inbound      - 手动入库
 * - POST /stocks/outbound     - 手动出库
 * - POST /stocks/adjust       - 库存盘点校准
 * - POST /stocks/defective-inbound - 残次品入库
 * - GET  /stocks/logs        - 库存流水列表
 * - PUT  /stocks/threshold   - 更新预警阈值
 * - GET  /stocks/warning     - 库存预警列表
 * 
 * @author ERP Migration
 */
@Slf4j
@RestController
@RequestMapping("/api/stocks")
@RequiredArgsConstructor
public class StockController {

    private final StockCheckService stockCheckService;

    // ==================== 库存查询 ====================

    /**
     * 库存列表（分页，支持搜索、仓库筛选、预警筛选）
     * 对应PHP StockController::index
     * 
     * GET /stocks?sku_code=xxx&sku_name=xxx&warehouse_id=1&low_stock=true&page=1&limit=15
     */
    @GetMapping
    public ApiResponse<PageResponse<StockListItemDTO>> listStocks(StockQueryDTO query) {
        try {
            PageResponse<StockListItemDTO> result = stockCheckService.listStocks(query);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存列表失败", e);
            return ApiResponse.<PageResponse<StockListItemDTO>>error(e.getMessage());
        }
    }

    /**
     * 库存详情（按仓库+SKU）
     * 对应PHP StockController::show
     * 
     * GET /stocks/show?sku_code=xxx&warehouse_id=1
     */
    @GetMapping("/show")
    public ApiResponse<StockDetailDTO> getStockDetail(
            @RequestParam String skuCode,
            @RequestParam Long warehouseId) {
        try {
            StockDetailDTO result = stockCheckService.getStockDetail(skuCode, warehouseId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存详情失败: skuCode={}, warehouseId={}", skuCode, warehouseId, e);
            if (e.getMessage().contains("不存在")) {
                return ApiResponse.notFound(e.getMessage());
            }
            return ApiResponse.<StockDetailDTO>error(e.getMessage());
        }
    }

    // ==================== 库存盘点调整 ====================

    /**
     * 库存盘点校准（手动调整库存）
     * 对应PHP StockController::adjust
     * 
     * POST /stocks/adjust
     * Body: { "sku_code": "xxx", "warehouse_id": 1, "quantity": 100, "remark": "xxx" }
     */
    @PostMapping("/adjust")
    public ApiResponse<StockAdjustResponse> adjustStock(@Valid @RequestBody StockAdjustRequest request) {
        try {
            StockAdjustResponse result = stockCheckService.adjustStock(request);
            return ApiResponse.success("调整成功", result);
        } catch (Exception e) {
            log.error("库存调整失败: skuCode={}, warehouseId={}", request.getSkuCode(), request.getWarehouseId(), e);
            return ApiResponse.<StockAdjustResponse>error(e.getMessage());
        }
    }

    // ==================== 手动入库/出库 ====================

    /**
     * 手动入库
     * 对应PHP StockController::manualInbound
     * 
     * POST /stocks/inbound
     * Body: { "sku_code": "xxx", "warehouse_id": 1, "quantity": 100, "related_no": "xxx", "remark": "xxx" }
     */
    @PostMapping("/inbound")
    public ApiResponse<StockListItemDTO> manualInbound(@Valid @RequestBody StockInboundRequest request) {
        try {
            Stock stock = stockCheckService.adjustForInbound(request);
            StockListItemDTO dto = StockListItemDTO.builder()
                    .skuCode(stock.getSkuCode())
                    .warehouseId(stock.getWarehouseId())
                    .quantity(stock.getQuantity())
                    .lockedQuantity(stock.getLockedQuantity())
                    .availableQuantity(stock.getAvailableQuantity())
                    .build();
            return ApiResponse.success("入库成功", dto);
        } catch (Exception e) {
            log.error("手动入库失败: skuCode={}, warehouseId={}", request.getSkuCode(), request.getWarehouseId(), e);
            return ApiResponse.<StockListItemDTO>error(e.getMessage());
        }
    }

    /**
     * 手动出库
     * 对应PHP StockController::manualOutbound
     * 
     * POST /stocks/outbound
     * Body: { "sku_code": "xxx", "warehouse_id": 1, "quantity": 100, "related_no": "xxx", "remark": "xxx" }
     */
    @PostMapping("/outbound")
    public ApiResponse<StockListItemDTO> manualOutbound(@Valid @RequestBody StockOutboundRequest request) {
        try {
            Stock stock = stockCheckService.adjustForOutbound(request);
            StockListItemDTO dto = StockListItemDTO.builder()
                    .skuCode(stock.getSkuCode())
                    .warehouseId(stock.getWarehouseId())
                    .quantity(stock.getQuantity())
                    .lockedQuantity(stock.getLockedQuantity())
                    .availableQuantity(stock.getAvailableQuantity())
                    .build();
            return ApiResponse.success("出库成功", dto);
        } catch (Exception e) {
            log.error("手动出库失败: skuCode={}, warehouseId={}", request.getSkuCode(), request.getWarehouseId(), e);
            return ApiResponse.<StockListItemDTO>error(e.getMessage());
        }
    }

    /**
     * 残次品入库
     * 对应PHP StockController::defectiveInbound
     * 
     * POST /stocks/defective-inbound
     * Body: { "sku_code": "xxx", "warehouse_id": 1, "quantity": 100, "order_id": 1, "related_no": "xxx", "remark": "xxx" }
     */
    @PostMapping("/defective-inbound")
    public ApiResponse<Void> defectiveInbound(@Valid @RequestBody DefectiveInboundRequest request) {
        try {
            stockCheckService.defectiveInbound(request);
            return ApiResponse.<Void>success("残次品入库成功", null);
        } catch (Exception e) {
            log.error("残次品入库失败: skuCode={}, warehouseId={}", request.getSkuCode(), request.getWarehouseId(), e);
            return ApiResponse.<Void>error(e.getMessage());
        }
    }

    // ==================== 库存流水 ====================

    /**
     * 库存流水列表
     * 对应PHP StockController::logs
     * 
     * GET /stocks/logs?sku_code=xxx&warehouse_id=1&type=inbound&start_date=2024-01-01&end_date=2024-01-31&page=1&limit=15
     */
    @GetMapping("/logs")
    public ApiResponse<PageResponse<StockLogDTO>> listStockLogs(StockLogQueryDTO query) {
        try {
            PageResponse<StockLogDTO> result = stockCheckService.listStockLogs(query);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存流水列表失败", e);
            return ApiResponse.<PageResponse<StockLogDTO>>error(e.getMessage());
        }
    }

    // ==================== 预警管理 ====================

    /**
     * 更新库存预警阈值
     * 对应PHP StockController::updateThreshold
     * 
     * PUT /stocks/threshold
     * Body: { "sku_code": "xxx", "warehouse_id": 1, "warning_threshold": 10 }
     */
    @PutMapping("/threshold")
    public ApiResponse<Stock> updateThreshold(@Valid @RequestBody UpdateThresholdRequest request) {
        try {
            Stock stock = stockCheckService.updateThreshold(request);
            return ApiResponse.success("更新成功", stock);
        } catch (Exception e) {
            log.error("更新预警阈值失败: skuCode={}, warehouseId={}", request.getSkuCode(), request.getWarehouseId(), e);
            return ApiResponse.<Stock>error(e.getMessage());
        }
    }

    /**
     * 库存预警列表
     * 对应PHP StockController::warning
     * 
     * GET /stocks/warning?warehouse_id=1&page=1&limit=15
     */
    @GetMapping("/warning")
    public ApiResponse<PageResponse<StockWarningDTO>> listStockWarnings(
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer limit) {
        try {
            PageResponse<StockWarningDTO> result = stockCheckService.listStockWarnings(warehouseId, page, limit);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存预警列表失败", e);
            return ApiResponse.<PageResponse<StockWarningDTO>>error(e.getMessage());
        }
    }

    // ==================== 数据一致性检查 ====================

    /**
     * 库存数据一致性检查与修复
     * 对应PHP DataConsistencyService::checkAndFixStockConsistency
     * 
     * POST /stocks/check-consistency
     */
    @PostMapping("/check-consistency")
    public ApiResponse<Map<String, Object>> checkAndFixStockConsistency() {
        try {
            StockCheckService.ConsistencyCheckResult result = stockCheckService.checkAndFixStockConsistency();
            return ApiResponse.success(Map.of(
                    "checked", result.checked(),
                    "fixed", result.fixed(),
                    "errors", result.errors()
            ));
        } catch (Exception e) {
            log.error("库存一致性检查失败", e);
            return ApiResponse.<Map<String, Object>>error(e.getMessage());
        }
    }
}
