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.QuotaRateFieldDO;
import com.yhy.module.core.dal.typehandler.PostgreSQLBigintArrayTypeHandler;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

/**
 * 定额费率字段绑定 Mapper
 */
@Mapper
public interface QuotaRateFieldMapper extends BaseMapperX<QuotaRateFieldDO> {

    /**
     * 根据费率模式节点ID查询字段列表
     * 使用 @Select 注解以确保 binding_ids 数组字段正确映射
     */
    @Select("SELECT * FROM yhy_quota_rate_field WHERE catalog_item_id = #{catalogItemId} AND deleted = 0 ORDER BY field_index ASC")
    @Results({
        @Result(column = "binding_ids", property = "bindingIds", typeHandler = PostgreSQLBigintArrayTypeHandler.class)
    })
    List<QuotaRateFieldDO> selectListByCatalogItemId(@Param("catalogItemId") Long catalogItemId);

    /**
     * 根据费率模式节点ID和字段索引查询
     */
    default QuotaRateFieldDO selectByCatalogItemIdAndFieldIndex(Long catalogItemId, Integer fieldIndex) {
        return selectOne(new LambdaQueryWrapperX<QuotaRateFieldDO>()
                .eq(QuotaRateFieldDO::getCatalogItemId, catalogItemId)
                .eq(QuotaRateFieldDO::getFieldIndex, fieldIndex));
    }

    /**
     * 删除费率模式节点的所有字段
     */
    default int deleteByCatalogItemId(Long catalogItemId) {
        return delete(new LambdaQueryWrapperX<QuotaRateFieldDO>()
                .eq(QuotaRateFieldDO::getCatalogItemId, catalogItemId));
    }

    /**
     * 批量插入
     */
    default void insertBatch(List<QuotaRateFieldDO> fields) {
        for (QuotaRateFieldDO field : fields) {
            insert(field);
        }
    }

    /**
     * 统计费率模式节点的字段数量
     */
    default Long countByCatalogItemId(Long catalogItemId) {
        return selectCount(new LambdaQueryWrapperX<QuotaRateFieldDO>()
                .eq(QuotaRateFieldDO::getCatalogItemId, catalogItemId));
    }

    /**
     * 查询所有包含指定绑定节点的字段（排除指定字段索引）
     * 用于检查节点是否已被其他虚拟字段绑定
     * 
     * @param catalogItemId 费率模式节点ID
     * @param bindingId 要检查的绑定节点ID
     * @param excludeFieldIndex 要排除的字段索引（当前正在更新的字段）
     * @return 包含该绑定节点的字段列表
     */
    @Select("SELECT * FROM yhy_quota_rate_field " +
            "WHERE catalog_item_id = #{catalogItemId} " +
            "AND field_index != #{excludeFieldIndex} " +
            "AND binding_ids @> ARRAY[#{bindingId}]::bigint[] " +
            "AND deleted = 0")
    List<QuotaRateFieldDO> selectByBindingIdExcludeFieldIndex(
            @Param("catalogItemId") Long catalogItemId,
            @Param("bindingId") Long bindingId,
            @Param("excludeFieldIndex") Integer excludeFieldIndex);
}
