package com.erp.warehouse.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.warehouse.dto.InboundOrderDTO.*;
import com.erp.warehouse.entity.InboundOrder;
import com.erp.warehouse.service.InboundService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 入库管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/inbound")
@RequiredArgsConstructor
public class InboundController {

    private final InboundService inboundService;

    /**
     * 创建入库单
     * POST /api/inbound
     */
    @PostMapping
    public ApiResponse<InboundOrderVO> createInboundOrder(@Valid @RequestBody CreateRequest request,
                                                           @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {
        try {
            InboundOrder order = inboundService.createInboundOrder(request, operatorId);
            return ApiResponse.success(toVO(order), "创建成功", 201);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(422, e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 确认入库（实际增加库存）
     * POST /api/inbound/{id}/confirm
     */
    @PostMapping("/{id}/confirm")
    public ApiResponse<InboundOrderVO> confirmInbound(@PathVariable Long id,
                                                       @Valid @RequestBody ConfirmRequest request) {
        try {
            InboundOrder order = inboundService.confirmInbound(id, request);
            return ApiResponse.success("确认入库成功", toVO(order));
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 取消入库单
     * DELETE /api/inbound/{id}
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> cancelInbound(@PathVariable Long id) {
        try {
            inboundService.cancelInbound(id);
            return ApiResponse.success("取消成功", null);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 入库单列表（分页）
     * GET /api/inbound/list
     */
    @GetMapping("/list")
    public ApiResponse<IPage<InboundOrder>> listInboundOrders(
            @RequestParam(required = false) String inboundType,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int limit) {

        IPage<InboundOrder> result = inboundService.listInboundOrders(inboundType, warehouseId, status, page, limit);
        return ApiResponse.success(result);
    }

    /**
     * 入库单详情
     * GET /api/inbound/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<InboundOrderVO> getInboundOrder(@PathVariable Long id) {
        InboundOrder order = inboundService.getInboundOrder(id);
        if (order == null) {
            return ApiResponse.error(404, "入库单不存在");
        }
        return ApiResponse.success(toVO(order));
    }

    private InboundOrderVO toVO(InboundOrder order) {
        return InboundOrderVO.builder()
                .id(order.getId())
                .inboundNo(order.getInboundNo())
                .inboundType(order.getInboundType())
                .inboundTypeLabel(getInboundTypeLabel(order.getInboundType()))
                .warehouseId(order.getWarehouseId())
                .relatedNo(order.getRelatedNo())
                .supplierId(order.getSupplierId())
                .supplierName(order.getSupplierName())
                .status(order.getStatus())
                .statusLabel(getStatusLabel(order.getStatus()))
                .remark(order.getRemark())
                .expectedTime(order.getExpectedTime())
                .inboundTime(order.getInboundTime())
                .createTime(order.getCreateTime())
                .build();
    }

    private String getInboundTypeLabel(String type) {
        return switch (type) {
            case "purchase" -> "采购入库";
            case "return" -> "退货入库";
            case "transfer" -> "调拨入库";
            default -> type;
        };
    }

    private String getStatusLabel(String status) {
        return switch (status) {
            case "pending" -> "待入库";
            case "partial" -> "部分入库";
            case "completed" -> "已完成";
            case "cancelled" -> "已取消";
            default -> status;
        };
    }
}
