/**
 * mysql 数据层
 */

import { TablesConfig } from "../config/tableConfig";
import { mysqlDB } from "../db/mysqlInit";

let mysqlModelMap = {};

export async function initMysqlModel() {

    /**初始化表 */
    for (let i =0; i < TablesConfig.length; i++) {
        let { tableName, schema }  = TablesConfig[i];

        let schemaConf = {
            freezeTableName:true, //true表示使用给定的表名，false表示模型名后加s作为表名
            timestamps:false  //true表示给模型加上时间戳属性(createAt updateAt),false表示不带时间戳属性
        };

        let model = mysqlDB.define( tableName, schema, schemaConf);
        
        mysqlModelMap[tableName] = await model.sync({}).then();
        
    }

    /**初始化表关联 */
    for (let i =0; i < TablesConfig.length; i++) {
        let { tableName, association }  = TablesConfig[i];
        association.forEach( (item:any) => {
            if (item) {
                let {type, check, foreignKey} = item;
                if (type == "hasOne") {
                    mysqlModelMap[check].hasOne(mysqlModelMap[tableName]);
                } else if (type == "hasMany") {
                    mysqlModelMap[tableName].hasMany(mysqlModelMap[check], {foreignKey});
                }
                mysqlModelMap[check].belongsTo(mysqlModelMap[tableName], {foreignKey});
                console.log("---->", mysqlModelMap[tableName].getTableName());
                console.log("====>", mysqlModelMap[check].getTableName());
            }
        });
        
    }


}

export { mysqlModelMap };

    
    
    
    
    
    