const Sequelize = require('sequelize');
const settings = require("../../../../config/settings")
const fs = require("fs")
const path = require("path");
var glob = require("glob");
const Op = Sequelize.Op
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 = Sequelize.Op;
    this.initModels();
    this.initRelations();
  }
  async initModels() {
    var self = this;
    var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
    var models = glob.sync(modelpath + "/**/*.js");
    console.log(models.length);
    models.forEach(function (m) {
      console.log(m);
      self.db.import(m);
    });
    console.log("init models....");
  }
  async initRelations() {
    this.db.models.dataauth.belongsTo(this.db.models.user, { constraints: false, });
    /*建立用户和角色之间的关系*/
    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.org.belongsTo(this.db.models.org,{constraints: false,});
    //this.db.models.org.hasMany(this.db.models.org,{constraints: false,});

    //组织机构和角色是多对多关系，建立兼职岗位，给岗位赋予多个角色，从而同步修改用户的角色
    //通过岗位接口去修改用户的角色
    //this.db.models.role.belongsToMany(this.db.models.org,{through: this.db.models.orgrole,constraints: false,});
    //this.db.models.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,});

    //组织机构和用户是1对多，
    //  this.db.models.user.belongsTo(this.db.models.org,{constraints: false,});
    //  this.db.models.org.hasMany(this.db.models.user,{constraints: false,});

    this.db.models.user.belongsTo(this.db.models.app, { constraints: false, });
    this.db.models.role.belongsTo(this.db.models.app, { constraints: false, });


    this.db.models.auth.belongsTo(this.db.models.app, { constraints: false, });
    this.db.models.auth.belongsTo(this.db.models.company, { constraints: false, });
    this.db.models.auth.belongsTo(this.db.models.role, { constraints: false, });

    this.db.models.app.belongsTo(this.db.models.user, { as: "creator", constraints: false, });


    this.db.models.user.belongsTo(this.db.models.company, { constraints: false, });

    this.db.models.company.hasMany(this.db.models.user, { as: 'us', constraints: false, });

    this.db.models.role.belongsTo(this.db.models.company, { constraints: false, });
    //  this.db.models.org.belongsTo(this.db.models.company,{constraints: false,});


    this.db.models.route.belongsTo(this.db.models.app, { constraints: false, });
    this.db.models.plugin.belongsTo(this.db.models.app, { constraints: false, });

    //渠道和渠道路径方法映射
    this.db.models.pathtomethod.belongsTo(this.db.models.channel, { constraints: false, });
    this.db.models.channel.hasMany(this.db.models.pathtomethod, { as: "pts", constraints: false, });

    //产品相关
    this.db.models.productprice.belongsTo(this.db.models.product, { constraints: false, });
    this.db.models.product.hasMany(this.db.models.productprice, { as: "skus", constraints: false, });

    this.db.models.product.belongsTo(this.db.models.company, { constraints: false, });
    //产品价格引用定价策略
    this.db.models.productprice.belongsTo(this.db.models.pricestrategy, { constraints: false, });
    this.db.models.productprice.belongsTo(this.db.models.company, { constraints: false, });
    //成本项目属于productprice
    this.db.models.productcost.belongsTo(this.db.models.productprice, { constraints: false, });
    this.db.models.productprice.hasMany(this.db.models.productcost, { as: "costs", constraints: false, });

    // 消息 ->  用户消息关联  1：n
    this.db.models.msg.hasMany(this.db.models.msguser, { constraints: false });
    this.db.models.msguser.belongsTo(this.db.models.msg, { 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") {

      //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;
//  const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
//   //console.log(db);
//   // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
//   // .then(function(user){
//   //   var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
//   //   acc.save().then(a=>{
//   //       user.setAccount(a);
//   //   });
//   //   console.log(user);
//   // });
//   // db.models.user.findAll().then(function(rs){
//   //   console.log("xxxxyyyyyyyyyyyyyyyyy");
//   //   console.log(rs);
//   // })
// });
// const User = db.define('user', {
//     firstName: {
//       type: Sequelize.STRING
//     },
//     lastName: {
//       type: Sequelize.STRING
//     }
// });
// db
//   .authenticate()
//   .then(() => {
//       console.log('Co+nnection has been established successfully.');
//
//       User.sync(/*{force: true}*/).then(() => {
//         // Table created
//         return User.create({
//           firstName: 'John',
//           lastName: 'Hancock'
//         });
//       });
//
//   })
//   .catch(err => {
//     console.error('Unable to connect to the database:', err);
//   });
//
//   User.findAll().then((rows)=>{
//     console.log(rows[0].firstName);
//   });
