import { ERRORENUM } from "../config/errorEnum";
import { BizError } from "../util/bizError";

/**
 * 根据conf配置校验请求参数
 * @param conf 配置
 * @param param 表单
 * @param skipKeys []不必填的字段
 */
export function eccReqParamater(conf:object, param, skipKeys?) {
    skipKeys = skipKeys || [];
    for (let key in conf) {
        let type = conf[key];
        let value = param[key];

        let isError = false; //校验是否异常
        let errorStr = "";//异常说明

        if ( (typeof value != 'boolean') && !value ) {
            if (skipKeys.indexOf(key) < 0 ) {
                isError = true;
                errorStr = `缺少 ${key} 字段`;
            }
        } else if(param[key]) {
            let paramType = typeof param[key];
            switch(conf[key]) {
                case 'Number':
                    if ( paramType != 'number' )  isError = true;
                break;
                case 'String':
                    if ( paramType != 'string' ) isError = true;
                break;
                case 'Boolean':
                    if ( paramType != 'boolean' ) isError = true;
                break;
                case '[Number]':
                    if ( !Array.isArray(param[key]) ) isError = true;
                    for (let i =0; i <  param[key].length; i++) {
                        let item = param[key][i];
                        if ( typeof item != 'number' ) {
                            isError = true;
                            errorStr = `${key}应是number型数组其中下标${i}是${typeof item}`;
                        }
                    }
                break;
                case '[Object]':
                    if ( !Array.isArray(param[key]) ) isError = true;
                    for (let i =0; i <  param[key].length; i++) {
                        let item = param[key][i];
                        if ( typeof item != 'object' ) {
                            isError = true;
                            errorStr = `${key}应是object型数组其中下标${i}是${typeof item}`;
                        }
                    }
                break;
            }
            errorStr = isError && errorStr == "" ? `${key}应该是${type}型 而不是${paramType}`: errorStr;
        }

        if (isError) throw new BizError(ERRORENUM.参数错误, errorStr);
        
    }
    for (let key in param) {
        if (!conf[key]) throw new BizError(ERRORENUM.参数错误, `多余${key}字段`);
    }
    return param;
}
