import { Configuration, App, Inject, MidwayDecoratorService } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import { join } from 'path';
import * as staticFile from '@midwayjs/static-file';
// import * as sequelize from '@midwayjs/sequelize';
import * as upload from '@midwayjs/upload';
import { ErrorDefaultFilter } from './librarys/ErrorDefaultFilter';
import * as crossDomain from '@midwayjs/cross-domain';
import * as cache from '@midwayjs/cache';
import { COMO_VALIDATE_RULE_DECORATOR, GET_USER_IP } from './librarys/AppDecorators';
// import * as redis from '@midwayjs/redis';

@Configuration({
    imports: [
        koa,
        validate,
        //静态文件
        staticFile,
        //数据库
        // sequelize,
        //文件上传
        upload,
        //缓存类
        cache,
        //redis处理
        // redis,
        //跨域处理
        crossDomain,
        {
            component: info,
            enabledEnvironment: ['local'],
        },
    ],
    importConfigs: [join(__dirname, './config')],
})
export class MainConfiguration {
    
    @App('koa')
    app: koa.Application;

    @Inject()
    decoratorService: MidwayDecoratorService;
    /**
     * 项目初始化
     */
    async onReady() {
        //自定义获取ip
        this.GetUserIPDecoratorImplements();
        //数据验证
        this.ComoRuleDecoratorImplements();
        // 添加过滤器
        this.app.useFilter([ErrorDefaultFilter]);
    }
    /**
     * 实现UserIp装饰器
     */
    GetUserIPDecoratorImplements() {
        this.decoratorService.registerParameterHandler(GET_USER_IP,(options) => {
            const req = options.originArgs[0];
            return  req?.get('X-Real-IP') || req?.get('X-Forwarded-For') || req?.ip;
        });
    }
    /**
     * 实现验证类装饰器
     */
    ComoRuleDecoratorImplements() {
        this.decoratorService.registerPropertyHandler(COMO_VALIDATE_RULE_DECORATOR,(propertyName, meta) => {
            return {key:propertyName,rule:meta['curRule']};
        })
    }

}
