package com.erp.report.export.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.report.export.dto.ExportStatus;
import com.erp.report.export.dto.ExportType;
import com.erp.report.export.entity.DataExportEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;

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

/**
 * 数据导出记录Mapper
 */
@Mapper
public interface DataExportRepository extends BaseMapper<DataExportEntity> {

    /**
     * 根据租户ID和状态查询导出记录
     */
    @Select("SELECT * FROM data_exports WHERE tenant_id = #{tenantId} AND status = #{status} ORDER BY created_at DESC")
    List<DataExportEntity> findByTenantIdAndStatus(@Param("tenantId") Long tenantId, @Param("status") ExportStatus status);

    /**
     * 根据租户ID和类型查询导出记录（分页）
     */
    @Select("SELECT * FROM data_exports WHERE tenant_id = #{tenantId} AND type = #{type} ORDER BY created_at DESC LIMIT #{limit} OFFSET #{offset}")
    List<DataExportEntity> findByTenantIdAndType(@Param("tenantId") Long tenantId, @Param("type") ExportType type, @Param("limit") int limit, @Param("offset") int offset);

    /**
     * 统计租户导出记录总数
     */
    @Select("SELECT COUNT(*) FROM data_exports WHERE tenant_id = #{tenantId}")
    int countByTenantId(@Param("tenantId") Long tenantId);

    /**
     * 更新导出状态
     */
    @Update("UPDATE data_exports SET status = #{status}, updated_at = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") ExportStatus status);

    /**
     * 标记导出完成
     */
    @Update("UPDATE data_exports SET status = 'completed', file_path = #{filePath}, file_size = #{fileSize}, row_count = #{rowCount}, updated_at = NOW() WHERE id = #{id}")
    int markCompleted(@Param("id") Long id, @Param("filePath") String filePath, @Param("fileSize") long fileSize, @Param("rowCount") int rowCount);

    /**
     * 标记导出失败
     */
    @Update("UPDATE data_exports SET status = 'failed', error_msg = #{errorMsg}, updated_at = NOW() WHERE id = #{id}")
    int markFailed(@Param("id") Long id, @Param("errorMsg") String errorMsg);

    /**
     * 删除过期导出记录（超过指定天数的）
     */
    @Delete("DELETE FROM data_exports WHERE created_at < #{cutoffDate}")
    int deleteExpiredRecords(@Param("cutoffDate") LocalDateTime cutoffDate);

    /**
     * 插入新导出记录
     */
    @Insert("INSERT INTO data_exports (tenant_id, user_id, type, format, filename, status, filters_json, created_at, updated_at) " +
            "VALUES (#{tenantId}, #{userId}, #{type}, #{format}, #{filename}, #{status}, #{filtersJson}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertExport(DataExportEntity entity);

    /**
     * 根据ID查询导出记录
     */
    @Select("SELECT * FROM data_exports WHERE id = #{id} AND tenant_id = #{tenantId}")
    DataExportEntity findByIdAndTenantId(@Param("id") Long id, @Param("tenantId") Long tenantId);
}
