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.PricePlan;
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 PricePlanRepository extends BaseMapper<PricePlan> {
    
    // ==================== 基础查询 ====================
    
    /**
     * 查询所有启用的价格方案
     */
    @Select("SELECT * FROM price_plans WHERE is_active = 1 ORDER BY sort_order ASC, id ASC")
    List<PricePlan> findActive();
    
    /**
     * 查询默认方案
     */
    @Select("SELECT * FROM price_plans WHERE is_default = 1 AND is_active = 1 LIMIT 1")
    PricePlan findDefault();
    
    /**
     * 根据ID查询
     */
    @Select("SELECT * FROM price_plans WHERE id = #{id}")
    PricePlan findById(@Param("id") Long id);
    
    // ==================== 分页查询 ====================
    
    /**
     * 分页查询价格方案列表
     */
    @Select("SELECT * FROM price_plans ORDER BY sort_order ASC, id ASC")
    IPage<PricePlan> findPage(Page<PricePlan> page);
    
    /**
     * 根据周期类型分页查询
     */
    @Select("SELECT * FROM price_plans WHERE period_type = #{periodType} ORDER BY sort_order ASC, id ASC")
    IPage<PricePlan> findPageByPeriodType(Page<PricePlan> page, @Param("periodType") String periodType);
    
    /**
     * 根据状态分页查询
     */
    @Select("SELECT * FROM price_plans WHERE is_active = #{isActive} ORDER BY sort_order ASC, id ASC")
    IPage<PricePlan> findPageByStatus(Page<PricePlan> page, @Param("isActive") Boolean isActive);
    
    // ==================== 统计查询 ====================
    
    /**
     * 统计启用方案数量
     */
    @Select("SELECT COUNT(*) FROM price_plans WHERE is_active = 1")
    Long countActive();
    
    /**
     * 检查名称是否已存在
     */
    @Select("SELECT COUNT(*) > 0 FROM price_plans WHERE name = #{name}")
    boolean existsByName(@Param("name") String name);
    
    /**
     * 检查名称是否已存在（排除指定ID）
     */
    @Select("SELECT COUNT(*) > 0 FROM price_plans WHERE name = #{name} AND id != #{excludeId}")
    boolean existsByNameExclude(@Param("name") String name, @Param("excludeId") Long excludeId);
    
    // ==================== 更新操作 ====================
    
    /**
     * 清除所有默认标识
     */
    @Update("UPDATE price_plans SET is_default = 0 WHERE is_default = 1")
    void clearDefaultFlag();
    
    /**
     * 设置默认方案
     */
    @Update("UPDATE price_plans SET is_default = 1 WHERE id = #{id}")
    int setDefault(@Param("id") Long id);
    
    /**
     * 切换状态
     */
    @Update("UPDATE price_plans SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END WHERE id = #{id}")
    int toggleStatus(@Param("id") Long id);
}
