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.Package;
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.util.List;

/**
 * 套餐数据访问接口
 */
@Mapper
public interface PackageRepository extends BaseMapper<Package> {
    
    // ==================== 基础查询 ====================
    
    /**
     * 根据套餐编码查询
     */
    @Select("SELECT * FROM packages WHERE code = #{code} AND deleted_at IS NULL")
    Package findByCode(@Param("code") String code);
    
    /**
     * 查询启用的套餐列表
     */
    @Select("SELECT * FROM packages WHERE status = 1 AND deleted_at IS NULL ORDER BY sort ASC, id ASC")
    List<Package> findActive();
    
    /**
     * 查询默认套餐
     */
    @Select("SELECT * FROM packages WHERE is_default = 1 AND status = 1 AND deleted_at IS NULL LIMIT 1")
    Package findDefault();
    
    // ==================== 分页查询 ====================
    
    /**
     * 分页查询套餐列表
     */
    @Select("SELECT * FROM packages WHERE deleted_at IS NULL ORDER BY sort ASC, id ASC")
    IPage<Package> findPage(Page<Package> page);
    
    // ==================== 统计查询 ====================
    
    /**
     * 统计启用套餐数量
     */
    @Select("SELECT COUNT(*) FROM packages WHERE status = 1 AND deleted_at IS NULL")
    Long countActive();
    
    /**
     * 检查编码是否已存在
     */
    @Select("SELECT COUNT(*) > 0 FROM packages WHERE code = #{code} AND deleted_at IS NULL")
    boolean existsByCode(@Param("code") String code);
    
    /**
     * 检查编码是否已存在（排除指定ID）
     */
    @Select("SELECT COUNT(*) > 0 FROM packages WHERE code = #{code} AND id != #{excludeId} AND deleted_at IS NULL")
    boolean existsByCodeExclude(@Param("code") String code, @Param("excludeId") Long excludeId);
    
    // ==================== 更新操作 ====================
    
    /**
     * 清除所有默认标识
     */
    @Update("UPDATE packages SET is_default = 0 WHERE is_default = 1")
    void clearDefaultFlag();
    
    /**
     * 设置默认套餐
     */
    @Update("UPDATE packages SET is_default = 1 WHERE id = #{id}")
    int setDefault(@Param("id") Long id);
}
