package com.erp.print.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.print.entity.PrintRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDateTime;

@Mapper
public interface PrintRecordRepository extends BaseMapper<PrintRecord> {

    @Select("SELECT * FROM print_record WHERE deleted = 0 ORDER BY created_at DESC")
    IPage<PrintRecord> selectPageList(Page<PrintRecord> page);

    @Select("SELECT * FROM print_record WHERE deleted = 0 AND record_no = #{recordNo}")
    PrintRecord selectByRecordNo(@Param("recordNo") String recordNo);

    @Select("<script>" +
            "SELECT * FROM print_record WHERE deleted = 0 " +
            "<if test='documentType != null'> AND document_type = #{documentType} </if>" +
            "<if test='documentNo != null'> AND document_no LIKE CONCAT('%', #{documentNo}, '%') </if>" +
            "<if test='printStatus != null'> AND print_status = #{printStatus} </if>" +
            "<if test='userId != null'> AND user_id = #{userId} </if>" +
            "<if test='startDate != null'> AND created_at &gt;= #{startDate} </if>" +
            "<if test='endDate != null'> AND created_at &lt;= #{endDate} </if>" +
            "ORDER BY created_at DESC" +
            "</script>")
    IPage<PrintRecord> selectRecordPage(Page<PrintRecord> page,
                                         @Param("documentType") String documentType,
                                         @Param("documentNo") String documentNo,
                                         @Param("printStatus") String printStatus,
                                         @Param("userId") Long userId,
                                         @Param("startDate") LocalDateTime startDate,
                                         @Param("endDate") LocalDateTime endDate);

    @Select("SELECT COUNT(*) FROM print_record WHERE deleted = 0 AND print_status = 'success' AND created_at >= #{startDate}")
    Long countSuccessByDate(@Param("startDate") LocalDateTime startDate);

    @Select("SELECT COUNT(*) FROM print_record WHERE deleted = 0 AND print_status = 'failed' AND created_at >= #{startDate}")
    Long countFailedByDate(@Param("startDate") LocalDateTime startDate);
}
