import { createCustomParamDecorator, createCustomPropertyDecorator } from "@midwayjs/core";
import { ComoValidatorTimingType } from "../interface";
import { ComoRules } from "como-ts-utils";
import { ComoTableColumn } from "como-admin-web";
//获取用户IP装饰器常量定义
export const GetUserIpDecorator     = 'decorator:get_user_ip';
// 获取用户IP
export const GET_USER_IP            = GetUserIpDecorator;

// 验证装饰器
export const COMO_VALIDATE_RULE_DECORATOR    = 'decorator:como_validate_rule_decorator';
// 列字段展示
export const COMO_TABLE_COLUMN_DECORATOR     = 'decorator:como_table_column_decorator';

/**
 * 获取用户真实IP装饰器
 * @returns
 */
export function UserIp(): ParameterDecorator {
    return createCustomParamDecorator(GET_USER_IP, {});
}
/**
 * 数据验证装饰器
 * @param curRule 
 * @returns 
 */
export function ComoRule(curRule: ComoValidatorTimingType | ComoRules):PropertyDecorator  {
    return createCustomPropertyDecorator(COMO_VALIDATE_RULE_DECORATOR, {
        curRule
    });
}
/**
 * 生成列字段
 * @param column 
 */
export function TableColumn(column:ComoTableColumn,sort?:number) {
    return function (target: any, propertyKey: string) {
        // 将装饰器的值赋给目标对象的属性
        if(!target[propertyKey]) target[propertyKey] = {};
        target[propertyKey][COMO_TABLE_COLUMN_DECORATOR] = {
            column,
            sort:sort ?? 99
        };
    };
}
/**
 * 获取类被装饰器修改过的字段
 * @param className 
 */
export function GetPropertDecorator(className:any,ins:any,identity:string) {
    const decorators = Object.getOwnPropertyNames(className.prototype).filter(prop => {
        const descriptor = Object.getOwnPropertyDescriptor(className.prototype, prop);
        return descriptor && descriptor.value && descriptor.value[identity];
    }).map(item => {
        return {
            key:item,
            value:ins[item][identity]
        };
    })
    return decorators;
}
