'use strict';

import { ComoNestUtils } from "como-nestjs-utils";
// eslint-disable-next-line node/no-extraneous-import
import { ComoTsRuleUtil } from "como-ts-utils";
import { GlobalOjectType, WebFunction } from "../interface";
//工具类
export class BaseAppUtils extends ComoNestUtils {
    /**
     * 单例
     */
    static _instanceI:BaseAppUtils;
    /**
     * 获取实例
     * @returns
     */
    static get Ins() {
        if (!BaseAppUtils._instanceI) {
            BaseAppUtils._instanceI = new this;
        }
        return BaseAppUtils._instanceI;
    }
    /**
     * 字符串值不为空
     * @param name
     * @returns
     */
    RuleStringNotEmpty(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Rules();
    }
    /**
     * 字符串值不为空
     */
    RuleStringTrimNotEmpty(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Trim().Rules();
    }
    /**
     * 字符串长度规则器
     * @param name
     * @param min
     * @param max
     */
    RuleStringLenRule(name:string,min?:number,max?:number) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Trim().MinLength(min ?? 0).MaxLength(max ?? 100).Rules()
    }
    /**
     * 数字不能为空
     * @param name
     */
    RuleNumberNotEmpty(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().Number().NotEmpty().Rules();
    }
    /**
     * 默认数字
     * @param value
     */
    RuleDefaultNumber(value:number) {
        return ComoTsRuleUtil.Ins.DefaultValue(value).Number().Rules();
    }
    /**
     * 默认字符串
     * @param value
     */
    RuleDefaultString(value:string) {
        return ComoTsRuleUtil.Ins.DefaultValue(value).Required().Rules();
    }
    /**
     * 其它默认值
     * @param value
     */
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint
    RuleDefaultValue<T extends unknown>(value:T) {
        return ComoTsRuleUtil.Ins.DefaultValue(value).Required().Rules();
    }
    /**
     * 两次字段要保护一致
     * @param field
     */
    RuleRefStringNotEmpty(name:string,field:string) {
        return ComoTsRuleUtil.Ins.Name(name).Ref(field).Rules();
    }
    /**
     * 身份证号码验证规则
     * @param name 
     */
    RuleIdcardNo(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Trim().ExtendRule((_field:string,value:string,_row:GlobalOjectType) => {
            try {
                if(value.length > 15) {
                    ComoNestUtils.Ins.IsIdentityNumber(value);
                }
            } catch(err:any) {
                throw new Error(`${name}${err.message ?? '身份证号码有误'}`);
            }
        }).Rules();
    }

    /**
     * 手机号码验证器
     * @param name 
     */
    RuleIsPhone(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Trim().IsPhone().Rules();
    }
    /**
     * 验证是否url地址
     * @param name 
     */
    RuleIsURL(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Trim().IsURL().Rules();
    }
    /**
     * 中文去空数据验证规则
     * @param name 
     */
    RuleStringChineseTirmNotEmpty(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().IsChinese().MinLength(2).Rules();
    }
    /**
     * 确认两个字段是否一样
     * @param name 
     * @param reffield 
     */
    RuleStringRefRule(name:string,reffield:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().NotEmpty().Trim().Ref(reffield).Rules();
    }
    /**
     * 可为空验证转数字
     * @param name 
     */
    RuleNumberRequired(name:string) {
        return ComoTsRuleUtil.Ins.Name(name).Required().Number().Rules();
    }
    /**
     * 等待时间 默认毫秒
     * @param timeOut 
     */
    SleepTime(timeOut?:number) {
        timeOut = timeOut ?? 1000;
        return new Promise((reslove,reject) => {
            setTimeout(() => {
                reslove(true);
            },timeOut);
        });
    }

    /**
     * 字符串实现首字母大写
     * @param data 
     */
    CharFirstStr(data:string) {
        return data.charAt(0).toUpperCase() + data.slice(1);
    }
    /**
     * 字符串转换
     * @param str 
     */
    Camelize(str:string) {
        return str.replace(/(?:_|^)([a-z])/g, function(match, p1, p2) {
            return p1.toUpperCase();  
        }); 
    }
    /**
     * 转换成驼峰式
     * @param str 
     * @returns 
     */
    ToPascalCase(str:string) {
        return ComoNestUtils.Ins.Trim(this.Camelize(str.charAt(0).toLowerCase() + str.slice(1)).charAt(0).toUpperCase() + this.Camelize(str.charAt(0).toLowerCase() + str.slice(1)).slice(1));  
    }
    /**
     * 判断是否json格式
     * @param text 
     * @returns 
     */
    IsValidJSON(text:any) {
        try {
            JSON.parse(text);
            return true;
        } catch (error) {
            return false;
        }
    }
    /**
     * 默认每页条数
     * @returns 
     */
    PageSize() {
        return 20;
    }
    /**
     * 默认当前页
     */
    CurrentPage() {
        return 1;
    }
    /**
     * 获取注入函数
     * @param fn
     */
    GetFunction<T extends GlobalOjectType>(fn:WebFunction<T>,data?:GlobalOjectType) {
        data = data ?? {};
        let msg = fn.toString();
        const regex = /({{)(.*?)(}})/g;
        let content = msg;
        const tmpArr = msg.match(regex);
        if(tmpArr && tmpArr.length > 0) {
            for(let i = 0;i < tmpArr.length;i++) {
                const item = tmpArr[i];
                const field = item.replace("{{","").replace("}}","");
                let value = data[field] ?? '';
                if(field.includes('-')) {
                    value = this.ComoDecode(data[field.replace('-','')]);
                }
                content = content.replace(item,value || '');
            }
        }
        return content;
    }
}