const Sequelize = require('sequelize');
const settings=require("../../../config/settings")
const fs=require("fs")
const path=require("path");
class DbFactory{
  constructor(){
    const dbConfig=settings.database();
    this.db=new Sequelize(dbConfig.dbname,
                          dbConfig.user,
                          dbConfig.password,
                          dbConfig.config);
    this.db.Sequelize=Sequelize;
    this.db.Op=Sequelize.Op;
    this.initModels();
    this.initRelations();
  }
  async initModels(){
    var self=this;
    var modelpath=path.normalize(path.join(__dirname, '..'))+"/models/";
    var models=fs.readdirSync(modelpath);
    models.forEach(function(m){
       self.db.import(modelpath+m);
    });
    console.log("init models....");
  }
  async initRelations(){
     /**
       一个账户对应多个登陆用户
       一个账户对应一个commany
       一个APP对应多个登陆用户
       一个APP有多个角色
       登陆用户和角色多对多
     **/
   
    /*建立用户和角色之间的关系*/
    this.db.models.user.belongsToMany(this.db.models.role, {as:"Roles",through: 'p_userrole',constraints: false,});
    this.db.models.role.belongsToMany(this.db.models.user, {as:"Users",through: 'p_userrole',constraints: false,});
     /*建立频道和文章之间的关系*/
     this.db.models.article.belongsTo(this.db.models.newschannel,{constraints: false,});
     this.db.models.newschannel.hasMany(this.db.models.article,{constraints: false,});
  }
    //async getCon(){,用于使用替换table模型内字段数据使用
   getCon(){
    var that=this;
    // await this.db.authenticate().then(()=>{
    //   console.log('Connection has been established successfully.');
    // }).catch(err => {
    //   console.error('Unable to connect to the database:', err);
    //   throw err;
    // });
    //同步模型
    if(settings.env=="dev"){
    }
    return this.db;
  }
}
module.exports=DbFactory;
