package com.erp.tenant.controller.order;

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.order.OrderDetailResponse;
import com.erp.tenant.dto.order.OrderPageResponse;
import com.erp.tenant.dto.order.OrderPageResponse.OrderItemDTO;
import com.erp.tenant.entity.order.Order;
import com.erp.tenant.service.order.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * 租户端订单管理控制器
 * 功能：订单列表/详情/审核/驳回/发货/物流轨迹
 */
@Slf4j
@RestController
@RequestMapping("/api/tenant/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

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

    /**
     * 订单列表
     * GET /api/tenant/orders
     */
    @GetMapping
    public ApiResponse<PageResponse<OrderItemDTO>> getOrderList(
            @RequestParam(required = false) String platform,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

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

        IPage<Order> orderPage = orderService.getOrderPage(
                tenantId, platform, status, warehouseId, keyword, startDate, endDate, page, pageSize);

        var items = orderPage.getRecords().stream()
                .map(this::toOrderItemDTO)
                .collect(Collectors.toList());

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

        return ApiResponse.success(response);
    }

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

        OrderDetailResponse detail = orderService.getOrderDetail(tenantId, id);
        if (detail == null) {
            return ApiResponse.error(404, "订单不存在");
        }
        return ApiResponse.success(detail);
    }

    /**
     * 审核订单（通过）
     * POST /api/tenant/orders/{id}/approve
     */
    @PostMapping("/{id}/approve")
    public ApiResponse<?> approveOrder(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();
        Long operatorId = 0L; // TODO: get from auth context

        boolean success = orderService.approveOrder(tenantId, id, operatorId);
        if (!success) {
            return ApiResponse.error(400, "审核失败，订单状态不允许审核或订单不存在");
        }
        return ApiResponse.success("审核通过，库存已预扣", null);
    }

    /**
     * 驳回订单
     * POST /api/tenant/orders/{id}/reject
     */
    @PostMapping("/{id}/reject")
    public ApiResponse<?> rejectOrder(@PathVariable Long id,
                                      @RequestBody java.util.Map<String, String> body) {
        Long tenantId = TenantContext.getCurrentTenantId();
        Long operatorId = 0L;
        String reason = body.get("reason");

        if (reason == null || reason.isBlank()) {
            return ApiResponse.error(422, "驳回原因不能为空");
        }

        boolean success = orderService.rejectOrder(tenantId, id, operatorId, reason);
        if (!success) {
            return ApiResponse.error(400, "驳回失败，订单状态不允许驳回或订单不存在");
        }
        return ApiResponse.success("订单已驳回", null);
    }

    /**
     * 推送云仓
     * POST /api/tenant/orders/{id}/push-warehouse
     */
    @PostMapping("/{id}/push-warehouse")
    public ApiResponse<?> pushToWarehouse(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();

        boolean success = orderService.pushToWarehouse(tenantId, id);
        if (!success) {
            return ApiResponse.error(400, "推送失败，订单未审核或状态不允许");
        }
        return ApiResponse.success("推送成功", null);
    }

    /**
     * 物流轨迹
     * GET /api/tenant/orders/{id}/tracking
     */
    @GetMapping("/{id}/tracking")
    public ApiResponse<?> getTracking(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();

        OrderDetailResponse detail = orderService.getOrderDetail(tenantId, id);
        if (detail == null) {
            return ApiResponse.error(404, "订单不存在");
        }

        var order = detail.getOrder();
        return ApiResponse.success(java.util.Map.of(
                "orderSn", order.getOrderSn() != null ? order.getOrderSn() : "",
                "logisticsCompany", order.getLogisticsCompany() != null ? order.getLogisticsCompany() : "",
                "logisticsNo", order.getLogisticsNo() != null ? order.getLogisticsNo() : "",
                "trace", order.getTracking() != null ? order.getTracking() : java.util.Collections.emptyList()
        ));
    }

    private OrderItemDTO toOrderItemDTO(Order order) {
        return OrderItemDTO.builder()
                .id(order.getId())
                .orderSn(order.getOrderSn())
                .platformOrderSn(order.getPlatformOrderSn())
                .platform(order.getPlatform())
                .erpStatus(order.getErpStatus())
                .erpStatusText(order.getErpStatusText())
                .receiverName(order.getReceiverName())
                .receiverPhone(orderService.maskPhone(order.getReceiverPhone()))
                .receiverAddress(order.getReceiverAddress())
                .warehouseId(order.getWarehouseId())
                .warehouseName(order.getWarehouseName())
                .totalAmount(order.getTotalAmount())
                .itemCount(order.getItems() != null ? order.getItems().size() : 0)
                .createdAt(order.getCreatedAt() != null ? order.getCreatedAt().format(DT_FORMAT) : null)
                .updatedAt(order.getUpdatedAt() != null ? order.getUpdatedAt().format(DT_FORMAT) : null)
                .build();
    }
}
