const Sequelize = require('sequelize');
const settings = require('../../../../config/settings');
const { Op } = Sequelize;
const fs = require('fs');
const path = require('path');
const glob = require('glob');
class DbFactory {
  constructor() {
    const dbConfig = settings.database();
    this.db = new Sequelize(
      dbConfig.dbname,
      dbConfig.user,
      dbConfig.password,
      {
        ...dbConfig.config,
        operatorsAliases: {
          $eq: Op.eq,
          $ne: Op.ne,
          $gte: Op.gte,
          $gt: Op.gt,
          $lte: Op.lte,
          $lt: Op.lt,
          $not: Op.not,
          $in: Op.in,
          $notIn: Op.notIn,
          $is: Op.is,
          $like: Op.like,
          $notLike: Op.notLike,
          $iLike: Op.iLike,
          $notILike: Op.notILike,
          $regexp: Op.regexp,
          $notRegexp: Op.notRegexp,
          $iRegexp: Op.iRegexp,
          $notIRegexp: Op.notIRegexp,
          $between: Op.between,
          $notBetween: Op.notBetween,
          $overlap: Op.overlap,
          $contains: Op.contains,
          $contained: Op.contained,
          $adjacent: Op.adjacent,
          $strictLeft: Op.strictLeft,
          $strictRight: Op.strictRight,
          $noExtendRight: Op.noExtendRight,
          $noExtendLeft: Op.noExtendLeft,
          $and: Op.and,
          $or: Op.or,
          $any: Op.any,
          $all: Op.all,
          $values: Op.values,
          $col: Op.col,
        },
      },
    );
    this.db.Sequelize = Sequelize;
    this.db.Op = Op;
    this.initModels();
    this.initRelations();
  }
  async initModels() {
    const self = this;
    const modelpath = `${path.normalize(path.join(__dirname, '../..'))}/models/`;
    const models = glob.sync(`${modelpath}/**/*.js`);
    console.log(models.length);
    models.forEach((m) => {
      console.log(m);
      self.db.import(m);
    });
    console.log('init models....');
  }
  async initRelations() {


  }
  // async getCon(){,用于使用替换table模型内字段数据使用
  getCon() {
    const 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') {

      // console.log(pa);
      // pconfigObjs.forEach(p=>{
      //   console.log(p.get({plain:true}));
      // });
      // await this.db.models.user.create({
      // nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
      // .then(function(user){
      //   var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
      //   acc.save().then(a=>{
      //       user.setAccount(a);
      //   });
      // });
    }
    return this.db;
  }
}
module.exports = DbFactory;
