package com.erp.reconciliation.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.reconciliation.entity.ReconciliationTask;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 对账任务 Mapper
 * 
 * @author ERP Migration
 */
@Mapper
public interface ReconciliationTaskRepository extends BaseMapper<ReconciliationTask> {

    /**
     * 根据任务编号查询
     */
    @Select("SELECT * FROM reconciliation_task WHERE task_no = #{taskNo} AND deleted_at IS NULL LIMIT 1")
    ReconciliationTask findByTaskNo(@Param("taskNo") String taskNo);

    /**
     * 根据对账单号查询任务
     */
    @Select("SELECT * FROM reconciliation_task WHERE bill_no = #{billNo} AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1")
    ReconciliationTask findByBillNo(@Param("billNo") String billNo);

    /**
     * 分页查询任务
     */
    IPage<ReconciliationTask> selectPageByConditions(
            Page<ReconciliationTask> page,
            @Param("taskType") String taskType,
            @Param("taskStatus") String taskStatus,
            @Param("platform") String platform,
            @Param("shopId") Long shopId,
            @Param("startDate") LocalDateTime startDate,
            @Param("endDate") LocalDateTime endDate
    );

    /**
     * 查询正在执行的任务
     */
    @Select("SELECT * FROM reconciliation_task WHERE task_status = 'running' AND deleted_at IS NULL ORDER BY created_at DESC")
    List<ReconciliationTask> findRunningTasks();

    /**
     * 查询失败的任务（可重试）
     */
    @Select("SELECT * FROM reconciliation_task WHERE task_status = 'failed' AND deleted_at IS NULL ORDER BY created_at DESC LIMIT #{limit}")
    List<ReconciliationTask> findFailedTasks(@Param("limit") int limit);

    /**
     * 查询最近的任务记录
     */
    @Select("SELECT * FROM reconciliation_task WHERE deleted_at IS NULL ORDER BY created_at DESC LIMIT #{limit}")
    List<ReconciliationTask> findRecentTasks(@Param("limit") int limit);

    /**
     * 更新任务进度
     */
    @Select("UPDATE reconciliation_task SET progress = #{progress}, current_step = #{step}, updated_at = NOW() WHERE id = #{id}")
    int updateProgress(@Param("id") Long id, @Param("progress") Integer progress, @Param("step") String step);

    /**
     * 更新任务状态
     */
    @Select("UPDATE reconciliation_task SET task_status = #{status}, updated_at = NOW() WHERE id = #{id}")
    int updateTaskStatus(@Param("id") Long id, @Param("status") String status);
}
