'use strict';
import { ComoNestUtils } from "como-nestjs-utils";
import { AbstractDataType } from "sequelize";
import { Model, Repository } from "sequelize-typescript";
import { GlobalOjectType } from "../interface";
import { ComoValidatorError } from "./ErrorDefaultFilter";

export class ModelDefaultValue {
    /**
     * 当前实例
     */
    private _modelEntry:Repository<Model>;

    get CurDate() {
        return ComoNestUtils.Ins.Date('Y-m-d');
    }

    /**
     * 默认值
     */
    private readonly DefaultValues = {
        INTEGER:0,
        STRING:'',
        TINYINT:0,
        SMALLINT:0,
        TEXT:'',
        CHAR:'',
        FLOAT:0,
        DATEONLY:this.CurDate,
        DATE:new Date()
    };
    /**
     * 构造函数
     * @param model
     */
    constructor(model?:Repository<Model>) {
        this._modelEntry = model;
    }

    /**
     * 设置model
     * @param model
     */
    SetModel(model:Repository<Model>) {
        this._modelEntry = model;
        return this;
    }
    /**
     * 获取默认值
     */
    CreateDefaultValue<T extends GlobalOjectType>(data:T) {
        if(!this._modelEntry) throw new ComoValidatorError(`没有传入可操作的模型实例,请检查`);
        const attrs = this._modelEntry.getAttributes();
        const result:GlobalOjectType = data;
        for(const key in attrs) {
            const item = attrs[key];
            // eslint-disable-next-line no-prototype-builtins
            if(item.defaultValue || item.allowNull || item.autoIncrement || result.hasOwnProperty(key)) {
                continue;
            }
            result[item.field as string] = this.DefaultValues[(item.type as AbstractDataType).key];
        }
        return result as T;
    }
}