package com.erp.skumatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.common.core.exception.BusinessException;
import com.erp.skumatch.dto.*;
import com.erp.skumatch.entity.*;
import com.erp.skumatch.repository.*;
import com.erp.skumatch.service.SkuMatchService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class SkuMatchServiceImpl implements SkuMatchService {
    
    private final PlatformSkuRepository platformSkuRepository;
    private final PlatformSpuRepository platformSpuRepository;
    private final ErpSkuRepository erpSkuRepository;
    private final SkuMatchRecordRepository matchRecordRepository;
    private final SkuMatchRuleRepository ruleRepository;
    private final AiMatchConfigRepository aiConfigRepository;
    private final ShopRepository shopRepository;
    private final PlatformInfoRepository platformInfoRepository;
    private final SkuMatchTaskRepository taskRepository;
    private final StringRedisTemplate redisTemplate;
    private final ObjectMapper objectMapper;
    
    @Value("${sku-match.ai-queue:erp:queue:jarvis}")
    private String aiQueueName;
    
    @Value("${sku-match.default-page-size:20}")
    private int defaultPageSize;
    
    // ==================== 匹配记录 ====================
    
    @Override
    public IPage<SkuMatchRecord> getMatchList(MatchListRequest request) {
        int page = request.getPage() != null ? request.getPage() : 1;
        int pageSize = request.getLimit() != null ? request.getLimit() : defaultPageSize;
        Page<SkuMatchRecord> pageParam = new Page<>(page, pageSize);
        return matchRecordRepository.selectMatchList(pageParam, request.getPlatform(), request.getMatchType(), request.getKeyword());
    }
    
    @Override
    public IPage<PlatformSku> getUnmatchedList(UnmatchedRequest request) {
        int page = request.getPage() != null ? request.getPage() : 1;
        int pageSize = request.getLimit() != null ? request.getLimit() : defaultPageSize;
        Page<PlatformSku> pageParam = new Page<>(page, pageSize);
        Long shopId = null;
        if (request.getShopId() != null && !request.getShopId().isEmpty()) {
            shopId = Long.parseLong(request.getShopId());
        }
        return platformSkuRepository.selectUnmatchedByCondition(pageParam, request.getPlatform(), shopId, request.getKeyword());
    }
    
    @Override
    public IPage<ErpSku> getErpSkuList(String keyword, Integer page, Integer limit) {
        int p = page != null ? page : 1;
        int size = limit != null ? limit : defaultPageSize;
        Page<ErpSku> pageParam = new Page<>(p, size);
        return erpSkuRepository.selectPageByKeyword(pageParam, keyword);
    }
    
    // ==================== 手动匹配 ====================
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void manualMatch(ManualMatchRequest request) {
        PlatformSku platformSku = platformSkuRepository.selectById(request.getPlatformSkuId());
        if (platformSku == null) {
            throw new BusinessException("平台SKU不存在");
        }
        ErpSku erpSku = erpSkuRepository.selectById(request.getErpSkuId());
        if (erpSku == null) {
            throw new BusinessException("ERP SKU不存在");
        }
        
        // 解绑旧的匹配记录
        unbindPlatformSku(request.getPlatformSkuId());
        
        // 更新平台SKU绑定信息
        platformSku.setErpSkuId(erpSku.getId());
        platformSku.setErpSkuCode(erpSku.getSkuCode());
        platformSku.setErpSkuName(erpSku.getSkuName());
        platformSku.setMatchType("manual");
        platformSku.setMatchTime(LocalDateTime.now());
        platformSku.setMatchedRuleId(null);
        platformSkuRepository.updateById(platformSku);
        
        // 记录匹配历史
        saveMatchRecord(platformSku, erpSku, "manual", null, null);
        
        log.info("手动匹配成功 - platformSkuId:{}, erpSkuId:{}", request.getPlatformSkuId(), request.getErpSkuId());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unmatch(Long platformSkuId) {
        PlatformSku platformSku = platformSkuRepository.selectById(platformSkuId);
        if (platformSku == null) {
            throw new BusinessException("平台SKU不存在");
        }
        
        unbindPlatformSku(platformSkuId);
        
        platformSku.setErpSkuId(null);
        platformSku.setErpSkuCode(null);
        platformSku.setErpSkuName(null);
        platformSku.setMatchType(null);
        platformSku.setMatchTime(null);
        platformSku.setMatchedRuleId(null);
        platformSkuRepository.updateById(platformSku);
        
        log.info("取消匹配成功 - platformSkuId:{}", platformSkuId);
    }
    
    private void unbindPlatformSku(Long platformSkuId) {
        // 将之前的匹配记录标记为未匹配
        LambdaQueryWrapper<SkuMatchRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SkuMatchRecord::getPlatformSkuId, platformSkuId)
               .eq(SkuMatchRecord::getMatched, 1);
        List<SkuMatchRecord> records = matchRecordRepository.selectList(wrapper);
        for (SkuMatchRecord record : records) {
            record.setMatched(0);
            record.setUpdatedAt(LocalDateTime.now());
            matchRecordRepository.updateById(record);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchMatch(BatchMatchRequest request) {
        ErpSku erpSku = erpSkuRepository.selectById(request.getErpSkuId());
        if (erpSku == null) {
            throw new BusinessException("ERP SKU不存在");
        }
        
        for (Long platformSkuId : request.getPlatformSkuIds()) {
            ManualMatchRequest manualRequest = new ManualMatchRequest();
            manualRequest.setPlatformSkuId(platformSkuId);
            manualRequest.setErpSkuId(request.getErpSkuId());
            try {
                manualMatch(manualRequest);
            } catch (Exception e) {
                log.warn("批量匹配失败 - platformSkuId:{}, error:{}", platformSkuId, e.getMessage());
            }
        }
        log.info("批量匹配完成 - count:{}, erpSkuId:{}", request.getPlatformSkuIds().size(), request.getErpSkuId());
    }
    
    // ==================== 规则匹配 ====================
    
    @Override
    public List<SkuMatchRule> getMatchRules(String platform) {
        return ruleRepository.selectEnabledRules(platform);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SkuMatchRule createRule(RuleRequest request) {
        SkuMatchRule rule = new SkuMatchRule();
        rule.setName(request.getName());
        rule.setPriority(request.getPriority() != null ? request.getPriority() : 0);
        rule.setPlatform(request.getPlatform());
        rule.setField(request.getField());
        rule.setPattern(request.getPattern());
        rule.setReplacePattern(request.getReplacePattern());
        rule.setMatchType(request.getMatchType());
        rule.setEnabled(request.getEnabled() != null ? request.getEnabled() : 1);
        rule.setMatchCount(0);
        rule.setSuccessCount(0);
        rule.setCreatedAt(LocalDateTime.now());
        rule.setUpdatedAt(LocalDateTime.now());
        ruleRepository.insert(rule);
        return rule;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRule(Long id, RuleRequest request) {
        SkuMatchRule rule = ruleRepository.selectById(id);
        if (rule == null) {
            throw new BusinessException("规则不存在");
        }
        if (request.getName() != null) rule.setName(request.getName());
        if (request.getPriority() != null) rule.setPriority(request.getPriority());
        if (request.getPlatform() != null) rule.setPlatform(request.getPlatform());
        if (request.getField() != null) rule.setField(request.getField());
        if (request.getPattern() != null) rule.setPattern(request.getPattern());
        if (request.getReplacePattern() != null) rule.setReplacePattern(request.getReplacePattern());
        if (request.getMatchType() != null) rule.setMatchType(request.getMatchType());
        if (request.getEnabled() != null) rule.setEnabled(request.getEnabled());
        rule.setUpdatedAt(LocalDateTime.now());
        ruleRepository.updateById(rule);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRule(Long id) {
        ruleRepository.deleteById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SkuMatchRule toggleRuleEnabled(Long id, Boolean enabled) {
        SkuMatchRule rule = ruleRepository.selectById(id);
        if (rule == null) {
            throw new BusinessException("规则不存在");
        }
        rule.setEnabled(enabled ? 1 : 0);
        rule.setUpdatedAt(LocalDateTime.now());
        ruleRepository.updateById(rule);
        return rule;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExecuteResult executeRuleMatch(String platform) {
        List<SkuMatchRule> rules = ruleRepository.selectEnabledRules(platform);
        if (rules.isEmpty()) {
            rules = ruleRepository.selectAllEnabled();
        }
        
        LambdaQueryWrapper<PlatformSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformSku::getErpSkuId, null)
               .eq(PlatformSku::getStatus, "onsale");
        if (platform != null && !platform.isEmpty()) {
            wrapper.eq(PlatformSku::getPlatformCode, platform);
        }
        List<PlatformSku> unmatchedSkus = platformSkuRepository.selectList(wrapper);
        
        int matched = 0;
        for (PlatformSku platformSku : unmatchedSkus) {
            ErpSku bestMatch = applyMatchRules(platformSku, rules);
            if (bestMatch != null) {
                // 解绑旧记录
                unbindPlatformSku(platformSku.getId());
                
                // 更新平台SKU
                platformSku.setErpSkuId(bestMatch.getId());
                platformSku.setErpSkuCode(bestMatch.getSkuCode());
                platformSku.setErpSkuName(bestMatch.getSkuName());
                platformSku.setMatchType("rule");
                platformSku.setMatchTime(LocalDateTime.now());
                platformSkuRepository.updateById(platformSku);
                
                // 记录匹配历史
                saveMatchRecord(platformSku, bestMatch, "rule", null, null);
                matched++;
            }
        }
        
        log.info("规则匹配执行完成 - matched:{}, total:{}", matched, unmatchedSkus.size());
        return new ExecuteResult(matched, unmatchedSkus.size());
    }
    
    private ErpSku applyMatchRules(PlatformSku platformSku, List<SkuMatchRule> rules) {
        List<ErpSku> allErpSkus = erpSkuRepository.selectList(null);
        
        for (SkuMatchRule rule : rules) {
            // 检查平台匹配
            if (rule.getPlatform() != null && !rule.getPlatform().isEmpty() 
                    && !rule.getPlatform().equals(platformSku.getPlatformCode())) {
                continue;
            }
            
            for (ErpSku erpSku : allErpSkus) {
                String matchedValue = getFieldValue(platformSku, rule.getField());
                String erpValue = getErpFieldValue(erpSku, rule.getField());
                
                if (matchedValue == null || erpValue == null) continue;
                
                boolean isMatch = match(matchedValue, erpValue, rule.getPattern(), rule.getMatchType());
                if (isMatch) {
                    // 更新规则统计
                    rule.setMatchCount(rule.getMatchCount() + 1);
                    rule.setSuccessCount(rule.getSuccessCount() + 1);
                    rule.setUpdatedAt(LocalDateTime.now());
                    ruleRepository.updateById(rule);
                    return erpSku;
                }
            }
        }
        return null;
    }
    
    private String getFieldValue(PlatformSku sku, String field) {
        return switch (field) {
            case "name" -> sku.getSkuName();
            case "code" -> sku.getSkuCode();
            default -> sku.getSkuName();
        };
    }
    
    private String getErpFieldValue(ErpSku erpSku, String field) {
        return switch (field) {
            case "name" -> erpSku.getSkuName();
            case "code" -> erpSku.getSkuCode();
            case "barcode" -> erpSku.getBarcode();
            default -> erpSku.getSkuName();
        };
    }
    
    private boolean match(String source, String target, String pattern, String matchType) {
        if (source == null || target == null) return false;
        source = source.toLowerCase();
        target = target.toLowerCase();
        pattern = pattern.toLowerCase();
        
        return switch (matchType) {
            case "exact" -> source.equals(target) || source.equals(pattern);
            case "contains" -> source.contains(target) || target.contains(source) 
                    || source.contains(pattern) || target.contains(pattern);
            case "regex" -> {
                try {
                    yield source.matches(pattern) || target.matches(pattern);
                } catch (Exception e) {
                    yield false;
                }
            }
            default -> false;
        };
    }
    
    // ==================== AI匹配 ====================
    
    @Override
    public AiMatchConfig getAiMatchConfig() {
        AiMatchConfig config = aiConfigRepository.selectById(1L);
        if (config == null) {
            config = new AiMatchConfig();
            config.setId(1L);
            config.setEnabled(0);
            config.setModel("gpt-4");
            config.setThreshold(new BigDecimal("0.8000"));
            config.setAutoMatch(0);
            config.setSimilarityField("name");
            aiConfigRepository.insert(config);
        }
        return config;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AiMatchConfig saveAiMatchConfig(AiMatchConfig config) {
        config.setId(1L);
        config.setUpdatedAt(LocalDateTime.now());
        aiConfigRepository.updateById(config);
        return config;
    }
    
    @Override
    public ExecuteResult executeAiMatch(ExecuteAiRequest request) {
        AiMatchConfig aiConfig = getAiMatchConfig();
        if (aiConfig.getEnabled() == null || aiConfig.getEnabled() == 0) {
            throw new BusinessException("AI匹配未启用，请先在配置中启用");
        }
        
        // 查询待匹配的SKU
        LambdaQueryWrapper<PlatformSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformSku::getErpSkuId, null)
               .eq(PlatformSku::getStatus, "onsale");
        if (request.getPlatform() != null && !request.getPlatform().isEmpty()) {
            wrapper.eq(PlatformSku::getPlatformCode, request.getPlatform());
        }
        List<PlatformSku> unmatchedSkus = platformSkuRepository.selectList(wrapper);
        
        if (unmatchedSkus.isEmpty()) {
            return new ExecuteResult(0, 0);
        }
        
        // 生成任务ID，投递到Redis队列
        String taskId = "ai_match_" + UUID.randomUUID().toString().replace("-", "");
        
        SkuMatchTask task = new SkuMatchTask();
        task.setTaskId(taskId);
        task.setTaskType("ai");
        task.setPlatform(request.getPlatform());
        task.setStatus("pending");
        task.setTotalCount(unmatchedSkus.size());
        task.setCreatedAt(LocalDateTime.now());
        taskRepository.insert(task);
        
        // 投递任务到Redis队列
        Map<String, Object> taskData = new HashMap<>();
        taskData.put("task_id", taskId);
        taskData.put("type", "ai_sku_match");
        taskData.put("platform_sku_ids", unmatchedSkus.stream().map(PlatformSku::getId).collect(Collectors.toList()));
        taskData.put("threshold", request.getThreshold() != null ? request.getThreshold() : aiConfig.getThreshold().doubleValue());
        taskData.put("similarity_field", aiConfig.getSimilarityField());
        taskData.put("auto_match", aiConfig.getAutoMatch() == 1);
        
        try {
            redisTemplate.opsForList().leftPush(aiQueueName, objectMapper.writeValueAsString(taskData));
            log.info("AI匹配任务已投递 - taskId:{}, totalSkus:{}", taskId, unmatchedSkus.size());
        } catch (Exception e) {
            log.error("Redis投递失败", e);
            throw new BusinessException("任务投递失败: " + e.getMessage());
        }
        
        return new ExecuteResult(0, unmatchedSkus.size());
    }
    
    // ==================== 平台商品 ====================
    
    @Override
    public List<PlatformShopTreeNode> getPlatformShopTree() {
        List<PlatformInfo> platforms = platformInfoRepository.selectList(
                new LambdaQueryWrapper<PlatformInfo>().eq(PlatformInfo::getStatus, 1).orderByAsc(PlatformInfo::getSortOrder)
        );
        
        List<PlatformShopTreeNode> result = new ArrayList<>();
        for (PlatformInfo platform : platforms) {
            PlatformShopTreeNode platformNode = new PlatformShopTreeNode();
            platformNode.setId("platform-" + platform.getPlatformCode());
            platformNode.setLabel(platform.getPlatformName());
            platformNode.setType("platform");
            platformNode.setPlatform(platform.getPlatformCode());
            
            List<Shop> shops = shopRepository.selectList(
                    new LambdaQueryWrapper<Shop>()
                            .eq(Shop::getPlatformCode, platform.getPlatformCode())
                            .eq(Shop::getAuthStatus, 1)
            );
            
            List<PlatformShopTreeNode> shopNodes = shops.stream().map(shop -> {
                PlatformShopTreeNode node = new PlatformShopTreeNode();
                node.setId("shop-" + shop.getShopId());
                node.setLabel(shop.getShopName());
                node.setType("shop");
                node.setPlatform(platform.getPlatformCode());
                node.setShopId(shop.getShopId());
                return node;
            }).collect(Collectors.toList());
            
            platformNode.setChildren(shopNodes);
            result.add(platformNode);
        }
        return result;
    }
    
    @Override
    public List<Shop> getShopsByPlatform(String platform) {
        return shopRepository.selectList(
                new LambdaQueryWrapper<Shop>()
                        .eq(Shop::getPlatformCode, platform)
                        .eq(Shop::getAuthStatus, 1)
        );
    }
    
    @Override
    public String downloadPlatformGoods(DownloadGoodsRequest request) {
        // 查找店铺
        LambdaQueryWrapper<Shop> shopWrapper = new LambdaQueryWrapper<>();
        shopWrapper.eq(Shop::getPlatformCode, request.getPlatform())
                   .eq(Shop::getShopId, request.getShopId());
        Shop shop = shopRepository.selectOne(shopWrapper);
        if (shop == null) {
            throw new BusinessException("店铺不存在或未授权");
        }
        
        // TODO: 调用各平台API下载商品
        // 这里应该根据platform调用对应的平台API获取商品数据
        // 模拟返回任务ID
        String taskId = "download_" + System.currentTimeMillis();
        
        SkuMatchTask task = new SkuMatchTask();
        task.setTaskId(taskId);
        task.setTaskType("download");
        task.setPlatform(request.getPlatform());
        task.setStatus("pending");
        task.setCreatedAt(LocalDateTime.now());
        taskRepository.insert(task);
        
        log.info("商品下载任务已创建 - platform:{}, shopId:{}, taskId:{}", request.getPlatform(), request.getShopId(), taskId);
        return taskId;
    }
    
    @Override
    public List<PlatformGoodsDTO> getPlatformGoodsList(Long shopId) {
        Shop shop = shopRepository.selectById(shopId);
        if (shop == null) {
            throw new BusinessException("店铺不存在");
        }
        
        // 查询该店铺下的SPU
        LambdaQueryWrapper<PlatformSpu> spuWrapper = new LambdaQueryWrapper<>();
        spuWrapper.eq(PlatformSpu::getShopId, shopId);
        List<PlatformSpu> spus = platformSpuRepository.selectList(spuWrapper);
        
        // 查询该店铺下的SKU
        LambdaQueryWrapper<PlatformSku> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(PlatformSku::getShopId, shopId);
        List<PlatformSku> skus = platformSkuRepository.selectList(skuWrapper);
        
        // 按SPU分组
        Map<Long, List<PlatformSku>> skuMap = skus.stream()
                .collect(Collectors.groupingBy(PlatformSku::getSpuId));
        
        return spus.stream().map(spu -> {
            PlatformGoodsDTO dto = new PlatformGoodsDTO();
            dto.setId(spu.getId());
            dto.setType("spu");
            dto.setName(spu.getSpuName());
            dto.setCode(spu.getSpuCode());
            dto.setPrice(spu.getPrice());
            dto.setStatus(spu.getStatus());
            dto.setBound(false);
            
            List<PlatformSkuDTO> skuDTOs = skuMap.getOrDefault(spu.getId(), Collections.emptyList())
                    .stream().map(sku -> {
                        PlatformSkuDTO skuDto = new PlatformSkuDTO();
                        skuDto.setId(sku.getId());
                        skuDto.setSpuId(sku.getSpuId());
                        skuDto.setType("sku");
                        skuDto.setName(sku.getSkuName());
                        skuDto.setCode(sku.getSkuCode());
                        skuDto.setPrice(sku.getPrice());
                        skuDto.setStatus(sku.getStatus());
                        skuDto.setBound(sku.getErpSkuId() != null);
                        return skuDto;
                    }).collect(Collectors.toList());
            
            dto.setSkus(skuDTOs);
            return dto;
        }).collect(Collectors.toList());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindErpSku(BindErpSkuRequest request) {
        Long skuId = Long.parseLong(request.getSkuId());
        Long erpGoodsId = Long.parseLong(request.getErpGoodsId());
        
        PlatformSku platformSku = platformSkuRepository.selectById(skuId);
        if (platformSku == null) {
            throw new BusinessException("平台SKU不存在");
        }
        ErpSku erpSku = erpSkuRepository.selectById(erpGoodsId);
        if (erpSku == null) {
            throw new BusinessException("ERP商品不存在");
        }
        
        // 解绑旧记录
        unbindPlatformSku(skuId);
        
        // 更新绑定
        platformSku.setErpSkuId(erpGoodsId);
        platformSku.setErpSkuCode(erpSku.getSkuCode());
        platformSku.setErpSkuName(erpSku.getSkuName());
        platformSku.setMatchType("manual");
        platformSku.setMatchTime(LocalDateTime.now());
        platformSkuRepository.updateById(platformSku);
        
        // 记录历史
        saveMatchRecord(platformSku, erpSku, "manual", null, null);
    }
    
    // ==================== 导出 ====================
    
    @Override
    public byte[] exportMatchRecords(String platform) {
        LambdaQueryWrapper<SkuMatchRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SkuMatchRecord::getMatched, 1);
        if (platform != null && !platform.isEmpty()) {
            wrapper.inSql(SkuMatchRecord::getPlatformSkuId,
                    "SELECT id FROM platform_sku WHERE platform_code = '" + platform + "'");
        }
        wrapper.orderByDesc(SkuMatchRecord::getCreatedAt);
        List<SkuMatchRecord> records = matchRecordRepository.selectList(wrapper);
        
        StringBuilder csv = new StringBuilder();
        csv.append("平台SKU ID,平台SKU编码,平台SKU名称,ERP SKU ID,ERP SKU编码,ERP SKU名称,匹配类型,匹配时间\n");
        for (SkuMatchRecord record : records) {
            csv.append(String.format("%s,%s,%s,%s,%s,%s,%s,%s\n",
                    record.getPlatformSkuId(),
                    record.getPlatformSkuCode(),
                    record.getPlatformSkuName(),
                    record.getErpSkuId(),
                    record.getErpSkuCode(),
                    record.getErpSkuName(),
                    record.getMatchType(),
                    record.getCreatedAt()));
        }
        return csv.toString().getBytes(StandardCharsets.UTF_8);
    }
    
    // ==================== 内部方法 ====================
    
    private void saveMatchRecord(PlatformSku platformSku, ErpSku erpSku, String matchType, Long ruleId, BigDecimal confidence) {
        SkuMatchRecord record = new SkuMatchRecord();
        record.setPlatformSkuId(platformSku.getId());
        record.setPlatformSkuCode(platformSku.getSkuCode());
        record.setPlatformSkuName(platformSku.getSkuName());
        record.setErpSkuId(erpSku.getId());
        record.setErpSkuCode(erpSku.getSkuCode());
        record.setErpSkuName(erpSku.getSkuName());
        record.setMatchType(matchType);
        record.setMatchRuleId(ruleId);
        record.setConfidence(confidence);
        record.setMatched(1);
        record.setCreatedAt(LocalDateTime.now());
        record.setUpdatedAt(LocalDateTime.now());
        matchRecordRepository.insert(record);
    }
}
