package com.ycwl.basic.product.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.pricing.enums.ProductCategory;
import com.ycwl.basic.product.capability.DuplicateCheckStrategy;
import com.ycwl.basic.product.capability.PricingMode;
import com.ycwl.basic.product.capability.ProductTypeCapability;
import com.ycwl.basic.product.dto.EnumOptionResponse;
import com.ycwl.basic.product.dto.ProductTypeCapabilityRequest;
import com.ycwl.basic.product.dto.ProductTypeCapabilityResponse;
import com.ycwl.basic.product.service.IProductTypeCapabilityManagementService;
import com.ycwl.basic.product.service.IProductTypeCapabilityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品类型能力配置管理控制器
 * 提供管理端的配置管理功能
 */
@Slf4j
@RestController
@RequestMapping("/api/product/admin/capability")
@RequiredArgsConstructor
public class ProductTypeCapabilityController {

    private final IProductTypeCapabilityManagementService managementService;
    private final IProductTypeCapabilityService capabilityService;

    /**
     * 分页查询商品类型能力配置
     */
    @GetMapping("/page")
    public ApiResponse<Page<ProductTypeCapabilityResponse>> queryByPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String productType,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Boolean isActive) {

        Page<ProductTypeCapability> page = managementService.queryByPage(
                pageNum, pageSize, productType, category, isActive);

        // 转换为响应DTO
        Page<ProductTypeCapabilityResponse> responsePage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<ProductTypeCapabilityResponse> responseList = page.getRecords().stream()
                .map(ProductTypeCapabilityResponse::fromEntity)
                .collect(Collectors.toList());
        responsePage.setRecords(responseList);

        return ApiResponse.success(responsePage);
    }

    /**
     * 查询所有商品类型能力配置
     */
    @GetMapping("/list")
    public ApiResponse<List<ProductTypeCapabilityResponse>> queryAll(
            @RequestParam(defaultValue = "false") boolean includeInactive) {

        List<ProductTypeCapability> capabilities = managementService.queryAll(includeInactive);
        List<ProductTypeCapabilityResponse> responseList = capabilities.stream()
                .map(ProductTypeCapabilityResponse::fromEntity)
                .collect(Collectors.toList());

        return ApiResponse.success(responseList);
    }

    /**
     * 根据分类查询商品类型能力配置
     */
    @GetMapping("/category/{category}")
    public ApiResponse<List<ProductTypeCapabilityResponse>> queryByCategory(
            @PathVariable String category) {

        List<ProductTypeCapability> capabilities = managementService.queryByCategory(category);
        List<ProductTypeCapabilityResponse> responseList = capabilities.stream()
                .map(ProductTypeCapabilityResponse::fromEntity)
                .collect(Collectors.toList());

        return ApiResponse.success(responseList);
    }

    /**
     * 根据ID查询配置详情
     */
    @GetMapping("/{id}")
    public ApiResponse<ProductTypeCapabilityResponse> getById(
            @PathVariable Long id) {

        ProductTypeCapability capability = managementService.getById(id);
        return ApiResponse.success(ProductTypeCapabilityResponse.fromEntity(capability));
    }

    /**
     * 根据商品类型代码查询配置详情
     */
    @GetMapping("/product-type/{productType}")
    public ApiResponse<ProductTypeCapabilityResponse> getByProductType(
            @PathVariable String productType) {

        ProductTypeCapability capability = managementService.getByProductType(productType);
        return ApiResponse.success(ProductTypeCapabilityResponse.fromEntity(capability));
    }

    /**
     * 创建商品类型能力配置
     */
    @PostMapping
    public ApiResponse<ProductTypeCapabilityResponse> create(
            @RequestBody ProductTypeCapabilityRequest request) {

        ProductTypeCapability capability = managementService.create(request);
        return ApiResponse.success(ProductTypeCapabilityResponse.fromEntity(capability));
    }

    /**
     * 更新商品类型能力配置
     */
    @PutMapping("/{id}")
    public ApiResponse<ProductTypeCapabilityResponse> update(
            @PathVariable Long id,
            @RequestBody ProductTypeCapabilityRequest request) {

        ProductTypeCapability capability = managementService.update(id, request);
        return ApiResponse.success(ProductTypeCapabilityResponse.fromEntity(capability));
    }

    /**
     * 删除商品类型能力配置
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(
            @PathVariable Long id) {

        managementService.delete(id);
        return ApiResponse.success(null);
    }

    /**
     * 启用/禁用商品类型能力配置
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateStatus(
            @PathVariable Long id,
            @RequestParam Boolean isActive) {

        managementService.updateStatus(id, isActive);
        return ApiResponse.success(null);
    }

    /**
     * 批量初始化商品类型能力配置
     * 为所有已定义的商品类型创建默认配置
     */
    @PostMapping("/init-defaults")
    public ApiResponse<Integer> initializeDefaultCapabilities() {

        int count = managementService.initializeDefaultCapabilities();
        return ApiResponse.success(count);
    }

    /**
     * 刷新所有缓存
     */
    @PostMapping("/refresh-cache")
    public ApiResponse<Void> refreshCache() {

        capabilityService.refreshCache();
        return ApiResponse.success(null);
    }

    /**
     * 刷新指定商品类型的缓存
     */
    @PostMapping("/refresh-cache/{productType}")
    public ApiResponse<Void> refreshCacheByProductType(
            @PathVariable String productType) {

        capabilityService.refreshCache(productType);
        return ApiResponse.success(null);
    }

    // ========== 枚举选项接口 ==========

    /**
     * 获取定价模式枚举选项
     */
    @GetMapping("/enums/pricing-modes")
    public ApiResponse<List<EnumOptionResponse>> getPricingModes() {

        List<EnumOptionResponse> options = Arrays.stream(PricingMode.values())
                .map(mode -> new EnumOptionResponse(mode.getCode(), mode.getDescription()))
                .collect(Collectors.toList());

        return ApiResponse.success(options);
    }

    /**
     * 获取重复检查策略枚举选项
     */
    @GetMapping("/enums/duplicate-check-strategies")
    public ApiResponse<List<EnumOptionResponse>> getDuplicateCheckStrategies() {

        List<EnumOptionResponse> options = Arrays.stream(DuplicateCheckStrategy.values())
                .map(strategy -> new EnumOptionResponse(strategy.getCode(), strategy.getDescription()))
                .collect(Collectors.toList());

        return ApiResponse.success(options);
    }

    /**
     * 获取商品分类枚举选项
     */
    @GetMapping("/enums/categories")
    public ApiResponse<List<EnumOptionResponse>> getCategories() {

        List<EnumOptionResponse> options = Arrays.stream(ProductCategory.values())
                .map(category -> new EnumOptionResponse(category.getCode(), category.getDescription()))
                .collect(Collectors.toList());

        return ApiResponse.success(options);
    }
}
