package com.erp.skumatch.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.skumatch.dto.*;
import com.erp.skumatch.entity.*;
import com.erp.skumatch.service.SkuMatchService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Map;

/**
 * SKU匹配控制器
 */
@Slf4j
@RestController
@RequestMapping("/sku-match")
@RequiredArgsConstructor
public class SkuMatchController {
    
    private final SkuMatchService skuMatchService;
    
    // ==================== 匹配记录 ====================
    
    /**
     * 获取匹配列表
     */
    @GetMapping("/list")
    public ApiResponse<IPage<SkuMatchRecord>> getMatchList(MatchListRequest request) {
        return ApiResponse.success(skuMatchService.getMatchList(request));
    }
    
    /**
     * 获取未匹配商品
     */
    @GetMapping("/unmatched")
    public ApiResponse<IPage<PlatformSku>> getUnmatchedSkus(UnmatchedRequest request) {
        return ApiResponse.success(skuMatchService.getUnmatchedList(request));
    }
    
    /**
     * 获取ERP商品列表（用于手动匹配选择）
     */
    @GetMapping("/erp-skus")
    public ApiResponse<IPage<ErpSku>> getErpSkuList(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer limit) {
        return ApiResponse.success(skuMatchService.getErpSkuList(keyword, page, limit));
    }
    
    // ==================== 手动匹配 ====================
    
    /**
     * 手动匹配 - 关联平台SKU与ERP SKU
     */
    @PostMapping("/manual")
    public ApiResponse<Void> manualMatch(@Valid @RequestBody ManualMatchRequest request) {
        skuMatchService.manualMatch(request);
        return ApiResponse.success(null);
    }
    
    /**
     * 取消匹配
     */
    @DeleteMapping("/unmatch/{platformSkuId}")
    public ApiResponse<Void> unmatch(@PathVariable Long platformSkuId) {
        skuMatchService.unmatch(platformSkuId);
        return ApiResponse.success(null);
    }
    
    /**
     * 批量匹配
     */
    @PostMapping("/batch")
    public ApiResponse<Void> batchMatch(@Valid @RequestBody BatchMatchRequest request) {
        skuMatchService.batchMatch(request);
        return ApiResponse.success(null);
    }
    
    // ==================== 规则匹配 ====================
    
    /**
     * 获取匹配规则列表
     */
    @GetMapping("/rules")
    public ApiResponse<List<SkuMatchRule>> getMatchRules(@RequestParam(required = false) String platform) {
        return ApiResponse.success(skuMatchService.getMatchRules(platform));
    }
    
    /**
     * 创建匹配规则
     */
    @PostMapping("/rules")
    public ApiResponse<SkuMatchRule> createRule(@Valid @RequestBody RuleRequest request) {
        return ApiResponse.success(skuMatchService.createRule(request));
    }
    
    /**
     * 更新匹配规则
     */
    @PutMapping("/rules/{id}")
    public ApiResponse<Void> updateRule(@PathVariable Long id, @Valid @RequestBody RuleRequest request) {
        skuMatchService.updateRule(id, request);
        return ApiResponse.success(null);
    }
    
    /**
     * 删除匹配规则
     */
    @DeleteMapping("/rules/{id}")
    public ApiResponse<Void> deleteRule(@PathVariable Long id) {
        skuMatchService.deleteRule(id);
        return ApiResponse.success(null);
    }
    
    /**
     * 切换规则启用状态
     */
    @PutMapping("/rules/{id}/toggle")
    public ApiResponse<SkuMatchRule> toggleRuleEnabled(@PathVariable Long id, @RequestBody java.util.Map<String, Boolean> body) {
        return ApiResponse.success(skuMatchService.toggleRuleEnabled(id, body.get("enabled")));
    }
    
    /**
     * 执行规则匹配
     */
    @PostMapping("/rules/execute")
    public ApiResponse<SkuMatchService.ExecuteResult> executeRuleMatch(@RequestBody ExecuteRuleRequest request) {
        return ApiResponse.success(skuMatchService.executeRuleMatch(request.getPlatform()));
    }
    
    // ==================== AI匹配 ====================
    
    /**
     * 获取AI匹配配置
     */
    @GetMapping("/ai-config")
    public ApiResponse<AiMatchConfig> getAiMatchConfig() {
        return ApiResponse.success(skuMatchService.getAiMatchConfig());
    }
    
    /**
     * 保存AI匹配配置
     */
    @PutMapping("/ai-config")
    public ApiResponse<AiMatchConfig> saveAiMatchConfig(@RequestBody AiMatchConfig config) {
        return ApiResponse.success(skuMatchService.saveAiMatchConfig(config));
    }
    
    /**
     * 执行AI匹配
     */
    @PostMapping("/ai/execute")
    public ApiResponse<SkuMatchService.ExecuteResult> executeAiMatch(@RequestBody ExecuteAiRequest request) {
        return ApiResponse.success(skuMatchService.executeAiMatch(request));
    }
    
    // ==================== 导出 ====================
    
    /**
     * 导出匹配关系
     */
    @GetMapping("/export")
    public void exportMatchRecords(@RequestParam(required = false) String platform, HttpServletResponse response) {
        try {
            byte[] data = skuMatchService.exportMatchRecords(platform);
            response.setContentType("text/csv;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=sku_match_export.csv");
            response.getOutputStream().write(data);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("导出失败", e);
        }
    }
}
