package com.hys.app.util;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hys.app.framework.util.StringUtil;
import lombok.experimental.UtilityClass;

/**
 * 校验工具类
 *
 * @author 张崧
 * @since 2023-12-11
 */
@UtilityClass
public class ValidateUtil {

    /**
     * 校验数据重复
     *
     * @param mapper       mybatis mapper
     * @param field        要校验的字段
     * @param fieldValue   字段值
     * @param idField      id字段
     * @param idFieldValue id字段值
     * @return true：存在重复数据
     */
    public <T> boolean checkRepeat(BaseMapper<T> mapper, SFunction<T, ?> field, Object fieldValue, SFunction<T, ?> idField, String idFieldValue) {
        if (fieldValue == null) {
            return false;
        }
        if (fieldValue instanceof String && StringUtil.isEmpty((String) fieldValue)) {
            return false;
        }
        Long count = new LambdaQueryChainWrapper<>(mapper)
                .eq(field, fieldValue)
                .ne(idFieldValue != null, idField, idFieldValue)
                .last("limit 1")
                .count();

        return count != 0;
    }

}
