package com.erp.tenant.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.tenant.entity.Tenant;
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 java.time.LocalDateTime;
import java.util.List;

/**
 * 租户数据访问接口
 */
@Mapper
public interface TenantRepository extends BaseMapper<Tenant> {
    
    // ==================== 基础查询 ====================
    
    /**
     * 根据租户编码查询
     */
    @Select("SELECT * FROM tenants WHERE code = #{code} AND deleted_at IS NULL")
    Tenant findByCode(@Param("code") String code);
    
    /**
     * 根据域名查询
     */
    @Select("SELECT * FROM tenants WHERE domain = #{domain} AND deleted_at IS NULL")
    Tenant findByDomain(@Param("domain") String domain);
    
    /**
     * 查询正常状态的租户
     */
    @Select("SELECT * FROM tenants WHERE status = #{status} AND deleted_at IS NULL")
    List<Tenant> findByStatus(@Param("status") Integer status);
    
    // ==================== 分页查询 ====================
    
    /**
     * 分页查询租户列表（带搜索条件）
     */
    @Select("SELECT t.* FROM tenants t " +
           "LEFT JOIN packages p ON t.package_id = p.id " +
           "WHERE t.deleted_at IS NULL " +
           "AND (#{keyword} IS NULL OR t.name LIKE CONCAT('%', #{keyword}, '%') " +
           "     OR t.code LIKE CONCAT('%', #{keyword}, '%') " +
           "     OR t.admin_email LIKE CONCAT('%', #{keyword}, '%')) " +
           "AND (#{status} IS NULL OR t.status = #{status}) " +
           "ORDER BY t.created_at DESC")
    IPage<Tenant> findPage(Page<Tenant> page,
                          @Param("keyword") String keyword,
                          @Param("status") Integer status);
    
    /**
     * 查询已过期的租户
     */
    @Select("SELECT * FROM tenants WHERE expire_time < #{now} AND deleted_at IS NULL")
    List<Tenant> findExpired(@Param("now") LocalDateTime now);
    
    /**
     * 查询即将到期的租户（7天内）
     */
    @Select("SELECT * FROM tenants WHERE expire_time BETWEEN #{now} AND #{endTime} AND status = 1 AND deleted_at IS NULL")
    List<Tenant> findExpiringSoon(@Param("now") LocalDateTime now, @Param("endTime") LocalDateTime endTime);
    
    // ==================== 统计查询 ====================
    
    /**
     * 统计正常租户数量
     */
    @Select("SELECT COUNT(*) FROM tenants WHERE status = 1 AND deleted_at IS NULL")
    Long countActive();
    
    /**
     * 统计已过期租户数量
     */
    @Select("SELECT COUNT(*) FROM tenants WHERE expire_time < #{now} AND deleted_at IS NULL")
    Long countExpired(@Param("now") LocalDateTime now);
    
    /**
     * 统计套餐下的租户数量
     */
    @Select("SELECT COUNT(*) FROM tenants WHERE package_id = #{packageId} AND deleted_at IS NULL")
    Long countByPackageId(@Param("packageId") Long packageId);
    
    /**
     * 检查编码是否已存在
     */
    @Select("SELECT COUNT(*) > 0 FROM tenants WHERE code = #{code} AND deleted_at IS NULL")
    boolean existsByCode(@Param("code") String code);
    
    /**
     * 检查编码是否已存在（排除指定ID）
     */
    @Select("SELECT COUNT(*) > 0 FROM tenants WHERE code = #{code} AND id != #{excludeId} AND deleted_at IS NULL")
    boolean existsByCodeExclude(@Param("code") String code, @Param("excludeId") Long excludeId);
    
    // ==================== 更新操作 ====================
    
    /**
     * 更新租户状态
     */
    @Update("UPDATE tenants SET status = #{status}, updated_at = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status);
    
    /**
     * 批量更新租户状态
     */
    @Update("<script>" +
            "UPDATE tenants SET status = #{status}, updated_at = NOW() " +
            "WHERE id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach>" +
            "</script>")
    int batchUpdateStatus(@Param("ids") List<Long> ids, @Param("status") Integer status);
    
    // ==================== 关联查询 ====================
    
    /**
     * 查询租户详情（带套餐信息）
     */
    @Select("SELECT t.*, p.name as package_name, p.code as package_code " +
           "FROM tenants t " +
           "LEFT JOIN packages p ON t.package_id = p.id " +
           "WHERE t.id = #{id} AND t.deleted_at IS NULL")
    Tenant findDetailById(@Param("id") Long id);
}
