package com.yhy.module.core.dal.mysql.quota;

import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.yhy.module.core.dal.dataobject.quota.QuotaRateItemDO;
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
 */
@Mapper
public interface QuotaRateItemMapper extends BaseMapperX<QuotaRateItemDO> {

    /**
     * 根据模式节点ID查询费率项列表
     */
    default List<QuotaRateItemDO> selectListByCatalogItemId(Long catalogItemId) {
        return selectList(new LambdaQueryWrapperX<QuotaRateItemDO>()
                .eq(QuotaRateItemDO::getCatalogItemId, catalogItemId)
                .orderByAsc(QuotaRateItemDO::getSortOrder));
    }

    /**
     * 根据父节点ID查询子节点列表
     */
    default List<QuotaRateItemDO> selectListByParentId(Long parentId) {
        return selectList(new LambdaQueryWrapperX<QuotaRateItemDO>()
                .eq(QuotaRateItemDO::getParentId, parentId)
                .orderByAsc(QuotaRateItemDO::getSortOrder));
    }

    /**
     * 查询根节点列表（parent_id 为空）
     */
    default List<QuotaRateItemDO> selectRootListByCatalogItemId(Long catalogItemId) {
        return selectList(new LambdaQueryWrapperX<QuotaRateItemDO>()
                .eq(QuotaRateItemDO::getCatalogItemId, catalogItemId)
                .isNull(QuotaRateItemDO::getParentId)
                .orderByAsc(QuotaRateItemDO::getSortOrder));
    }

    /**
     * 检查是否有子节点
     */
    default boolean hasChildren(Long id) {
        return selectCount(new LambdaQueryWrapperX<QuotaRateItemDO>()
                .eq(QuotaRateItemDO::getParentId, id)) > 0;
    }

    /**
     * 获取同级最大排序值
     */
    @Select("SELECT COALESCE(MAX(sort_order), 0) FROM yhy_quota_rate_item " +
            "WHERE catalog_item_id = #{catalogItemId} " +
            "AND (parent_id = #{parentId} OR (#{parentId} IS NULL AND parent_id IS NULL)) " +
            "AND deleted = false")
    Integer selectMaxSortOrder(@Param("catalogItemId") Long catalogItemId, @Param("parentId") Long parentId);

    /**
     * 批量更新排序
     */
    @Update("UPDATE yhy_quota_rate_item SET sort_order = #{sortOrder}, update_time = NOW() WHERE id = #{id}")
    int updateSortOrder(@Param("id") Long id, @Param("sortOrder") Integer sortOrder);

    /**
     * 统计模式下的费率项数量
     */
    default Long countByCatalogItemId(Long catalogItemId) {
        return selectCount(new LambdaQueryWrapperX<QuotaRateItemDO>()
                .eq(QuotaRateItemDO::getCatalogItemId, catalogItemId));
    }
}
