package com.erp.warehouse.controller;

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

/**
 * 出库管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/outbound")
@RequiredArgsConstructor
public class OutboundController {

    private final OutboundService outboundService;

    /**
     * 创建出库单
     * POST /api/outbound
     */
    @PostMapping
    public ApiResponse<OutboundOrderVO> createOutboundOrder(@Valid @RequestBody CreateRequest request,
                                                            @RequestHeader(value = "X-Operator-Id", required = false) Long operatorId) {
        try {
            OutboundOrder order = outboundService.createOutboundOrder(request, operatorId);
            return ApiResponse.success(toVO(order), "创建成功", 201);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ApiResponse.error(422, e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 确认出库（实际扣减库存）
     * POST /api/outbound/{id}/ship
     */
    @PostMapping("/{id}/ship")
    public ApiResponse<OutboundOrderVO> confirmOutbound(@PathVariable Long id,
                                                          @Valid @RequestBody ShipRequest request) {
        try {
            OutboundOrder order = outboundService.confirmOutbound(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/outbound/{id}
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> cancelOutbound(@PathVariable Long id) {
        try {
            outboundService.cancelOutbound(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/outbound/list
     */
    @GetMapping("/list")
    public ApiResponse<IPage<OutboundOrder>> listOutboundOrders(
            @RequestParam(required = false) String outboundType,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int limit) {

        IPage<OutboundOrder> result = outboundService.listOutboundOrders(outboundType, warehouseId, status, page, limit);
        return ApiResponse.success(result);
    }

    /**
     * 出库单详情
     * GET /api/outbound/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<OutboundOrderVO> getOutboundOrder(@PathVariable Long id) {
        OutboundOrder order = outboundService.getOutboundOrder(id);
        if (order == null) {
            return ApiResponse.error(404, "出库单不存在");
        }
        return ApiResponse.success(toVO(order));
    }

    private OutboundOrderVO toVO(OutboundOrder order) {
        return OutboundOrderVO.builder()
                .id(order.getId())
                .outboundNo(order.getOutboundNo())
                .outboundType(order.getOutboundType())
                .outboundTypeLabel(getOutboundTypeLabel(order.getOutboundType()))
                .warehouseId(order.getWarehouseId())
                .targetWarehouseId(order.getTargetWarehouseId())
                .relatedNo(order.getRelatedNo())
                .customerId(order.getCustomerId())
                .customerName(order.getCustomerName())
                .status(order.getStatus())
                .statusLabel(getStatusLabel(order.getStatus()))
                .logisticsCompany(order.getLogisticsCompany())
                .trackingNo(order.getTrackingNo())
                .remark(order.getRemark())
                .outboundTime(order.getOutboundTime())
                .createTime(order.getCreateTime())
                .build();
    }

    private String getOutboundTypeLabel(String type) {
        return switch (type) {
            case "sale" -> "销售出库";
            case "transfer" -> "调拨出库";
            default -> type;
        };
    }

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