package com.erp.tenant.controller.goods;

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.goods.GoodsPageResponse;
import com.erp.tenant.dto.goods.GoodsPageResponse.GoodsItemDTO;
import com.erp.tenant.entity.goods.Goods;
import com.erp.tenant.service.goods.GoodsService;
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/goods")
@RequiredArgsConstructor
public class GoodsController {

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

    /**
     * 商品列表
     * GET /api/tenant/goods
     */
    @GetMapping
    public ApiResponse<PageResponse<GoodsItemDTO>> getGoodsList(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Long brandId,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

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

        IPage<Goods> goodsPage = goodsService.getGoodsPage(
                tenantId, keyword, categoryId, brandId, status, page, pageSize);

        var items = goodsPage.getRecords().stream()
                .map(this::toGoodsItemDTO)
                .collect(Collectors.toList());

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

        return ApiResponse.success(response);
    }

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

        Goods goods = goodsService.getGoodsDetail(tenantId, id);
        if (goods == null) {
            return ApiResponse.error(404, "商品不存在");
        }
        return ApiResponse.success(toGoodsItemDTO(goods));
    }

    /**
     * 上架商品
     * POST /api/tenant/goods/{id}/put-on-sale
     */
    @PostMapping("/{id}/put-on-sale")
    public ApiResponse<?> putOnSale(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();
        boolean success = goodsService.putOnSale(tenantId, id);
        if (!success) {
            return ApiResponse.error(404, "商品不存在");
        }
        return ApiResponse.success("上架成功", null);
    }

    /**
     * 下架商品
     * POST /api/tenant/goods/{id}/put-off-sale
     */
    @PostMapping("/{id}/put-off-sale")
    public ApiResponse<?> putOffSale(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();
        boolean success = goodsService.putOffSale(tenantId, id);
        if (!success) {
            return ApiResponse.error(404, "商品不存在");
        }
        return ApiResponse.success("下架成功", null);
    }

    /**
     * 批量上架
     * POST /api/tenant/goods/batch-put-on-sale
     */
    @PostMapping("/batch-put-on-sale")
    public ApiResponse<?> batchPutOnSale(@RequestBody Map<String, java.util.List<Long>> body) {
        Long tenantId = TenantContext.getCurrentTenantId();
        java.util.List<Long> ids = body.get("ids");
        if (ids == null || ids.isEmpty()) {
            return ApiResponse.error(422, "请选择要上架的商品");
        }
        int count = goodsService.batchPutOnSale(tenantId, ids);
        return ApiResponse.success("上架成功 " + count + " 件", Map.of("count", count));
    }

    /**
     * 批量下架
     * POST /api/tenant/goods/batch-put-off-sale
     */
    @PostMapping("/batch-put-off-sale")
    public ApiResponse<?> batchPutOffSale(@RequestBody Map<String, java.util.List<Long>> body) {
        Long tenantId = TenantContext.getCurrentTenantId();
        java.util.List<Long> ids = body.get("ids");
        if (ids == null || ids.isEmpty()) {
            return ApiResponse.error(422, "请选择要下架的商品");
        }
        int count = goodsService.batchPutOffSale(tenantId, ids);
        return ApiResponse.success("下架成功 " + count + " 件", Map.of("count", count));
    }

    /**
     * 商品统计
     * GET /api/tenant/goods/stats
     */
    @GetMapping("/stats")
    public ApiResponse<?> getGoodsStats() {
        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }
        GoodsService.GoodsStats stats = goodsService.getGoodsStats(tenantId);
        return ApiResponse.success(Map.of(
                "total", stats.total,
                "onSale", stats.onSale,
                "offSale", stats.offSale
        ));
    }

    private GoodsItemDTO toGoodsItemDTO(Goods goods) {
        return GoodsItemDTO.builder()
                .id(goods.getId())
                .goodsCode(goods.getGoodsCode())
                .name(goods.getName())
                .alias(goods.getAlias())
                .barCode(goods.getBarCode())
                .categoryId(goods.getCategoryId())
                .categoryName(goods.getCategoryName())
                .brandId(goods.getBrandId())
                .brandName(goods.getBrandName())
                .salePrice(goods.getSalePrice())
                .costPrice(goods.getCostPrice())
                .unit(goods.getUnit())
                .weight(goods.getWeight())
                .safeStock(goods.getSafeStock())
                .warningThreshold(goods.getWarningThreshold())
                .status(goods.getStatus())
                .statusText(goods.getStatusText())
                .stockQuantity(goods.getStockQuantity() != null ? goods.getStockQuantity() : 0)
                .availableQuantity(goods.getAvailableQuantity() != null ? goods.getAvailableQuantity() : 0)
                .description(goods.getDescription())
                .images(goods.getImages())
                .remark(goods.getRemark())
                .createdAt(goods.getCreatedAt() != null ? goods.getCreatedAt().format(DT_FORMAT) : null)
                .updatedAt(goods.getUpdatedAt() != null ? goods.getUpdatedAt().format(DT_FORMAT) : null)
                .build();
    }
}
