package com.lingyue.extract.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.extract.entity.ExtractResult;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 提取结果 Repository
 * 
 * @author lingyue
 * @since 2026-01-22
 */
@Mapper
public interface ExtractResultRepository extends BaseMapper<ExtractResult> {
    
    /**
     * 根据规则ID查询结果列表
     */
    @Select("SELECT * FROM extract_results WHERE rule_id = #{ruleId} ORDER BY create_time DESC")
    List<ExtractResult> findByRuleId(@Param("ruleId") String ruleId);
    
    /**
     * 根据规则ID查询最新结果
     */
    @Select("SELECT * FROM extract_results WHERE rule_id = #{ruleId} ORDER BY create_time DESC LIMIT 1")
    ExtractResult findLatestByRuleId(@Param("ruleId") String ruleId);
    
    /**
     * 根据项目ID查询所有结果
     */
    @Select("SELECT * FROM extract_results WHERE project_id = #{projectId} ORDER BY create_time DESC")
    List<ExtractResult> findByProjectId(@Param("projectId") String projectId);
    
    /**
     * 根据状态查询结果
     */
    @Select("SELECT * FROM extract_results WHERE project_id = #{projectId} AND status = #{status} ORDER BY create_time DESC")
    List<ExtractResult> findByProjectIdAndStatus(@Param("projectId") String projectId, @Param("status") String status);
    
    /**
     * 删除规则的所有结果
     */
    @Delete("DELETE FROM extract_results WHERE rule_id = #{ruleId}")
    int deleteByRuleId(@Param("ruleId") String ruleId);
    
    /**
     * 删除项目的所有结果
     */
    @Delete("DELETE FROM extract_results WHERE project_id = #{projectId}")
    int deleteByProjectId(@Param("projectId") String projectId);
    
    /**
     * 统计项目结果数量
     */
    @Select("SELECT COUNT(*) FROM extract_results WHERE project_id = #{projectId}")
    int countByProjectId(@Param("projectId") String projectId);
    
    /**
     * 按状态统计项目结果数量
     */
    @Select("SELECT status, COUNT(*) as count FROM extract_results WHERE project_id = #{projectId} GROUP BY status")
    List<java.util.Map<String, Object>> countByProjectIdGroupByStatus(@Param("projectId") String projectId);
    
    /**
     * 查询待确认的结果
     */
    @Select("SELECT * FROM extract_results WHERE project_id = #{projectId} AND status = 'extracted' ORDER BY create_time")
    List<ExtractResult> findPendingConfirmByProjectId(@Param("projectId") String projectId);
}
