yangyin
2024-05-20 4871d8eaa2f06e5a044ea0435e8e2b962358e384
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { ElMessage } from 'element-plus';
import { AxiosInstance, AxiosResponse } from 'axios';
import { Ref, unref } from 'vue';
import request from '/@/utils/request';
 
/**
 * 获取检查唯一性的 validator,用于 formRules
 * @param GetIsExist 检查唯一性接口
 * @param initialValue 初始值 Ref
 * @param keyword 检查的是什么(中文)
 * @param targetKey 检查的是什么(英文)
 * @param extraParams 检查唯一性接口时额外传送的参数,默认没有额外参数(传参 value 值可能需要 Ref,检查时需要动态获取该值)
 * @param isNullable 该字段是否可以为空,默认不能为空,可以不传
 * @param req 使用的 req,默认为 request
 * @returns
 */
export const useValidateUniqueness = (
    GetIsExist: (parameter: any, req?: AxiosInstance) => Promise<AxiosResponse<any, any>>,
    initialValue: Ref<any>,
    keyword: string,
    targetKey: string,
    extraParams: Record<string, any> = {},
    isNullable = false,
    req:any = request
) => {
    const getIsExist = async (targetValue, req) => {
        const rawExtraParams = {};
        for (let key in extraParams) {
            rawExtraParams[key] = unref(extraParams[key]);
        }
        const params = {
            [targetKey]: targetValue,
            ...rawExtraParams,
        };
        const res = await GetIsExist(params, req);
        if (res?.Code === 0) {
            if (res.Data) {
                return res.Data;
            }
        } else {
            ElMessage.error(`检查${keyword}唯一性失败` + (res?.Message ? `,${JSON.stringify(res.Message)}` : ''));
        }
    };
    const uniquenessValidator = async (rule, value, callback) => {
        if (value === '' && !isNullable) {
            callback(`请输入${keyword}`);
        }
        if (value !== initialValue.value) {
            if (value === '') {
                callback();
            } else {
                const isExist = await getIsExist(value, req);
                if (!isExist) {
                    callback();
                } else {
                    callback(`${keyword}已存在`);
                }
            }
        }
 
        callback();
    };
 
    return {
        uniquenessValidator,
    };
};