const Sequelize = require('sequelize');
const settings=require("../../../config/settings")
const fs=require("fs")
const path=require("path");
class DbFactory{
  constructor(){
    const dbConfig=settings.database();
    const dbConfighb=settings.databasehb();
    this.db=new Sequelize(dbConfig.dbname,
                          dbConfig.user,
                          dbConfig.password,
                          dbConfig.config);
    this.dbhb=new Sequelize(dbConfighb.dbname,
                          dbConfighb.user,
                          dbConfighb.password,
                          dbConfighb.config);
    this.dbhb.Sequelize=Sequelize;
    this.dbhb.Op=Sequelize.Op;
    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.belongsTo(this.db.models.account,{constraints: false,});
    this.db.models.account.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.product.belongsTo(this.db.models.app,{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.product.belongsToMany(this.db.models.role,{as:"Roles",through: 'p_roleproduct',constraints: false,});
    this.db.models.role.belongsToMany(this.db.models.product, {as:"Products",through: 'p_roleproduct',constraints: false,});

    /*店铺上架和服务项目之间的关系*/
    this.db.models.shop.belongsToMany(this.db.models.servicesitem, {as:"ServicesitemList",through: this.db.models.shopserviceitem,constraints: false,});
    this.db.models.servicesitem.belongsToMany(this.db.models.shop, {as:"ShopList",through: this.db.models.shopserviceitem,constraints: false,});

    /*用户和渠道之间的关系表p_user_channel*/
    this.db.models.user.belongsToMany(this.db.models.channel, {as:"Channels",through: 'p_user_channel',constraints: false,});
    this.db.models.channel.belongsToMany(this.db.models.user, {as:"Users",through: 'p_user_channel',constraints: false,});

    /*角色和渠道之间的关系表p_role_channel*/
    this.db.models.role.belongsToMany(this.db.models.channel, {as:"Channels",through: 'p_role_channel',constraints: false,});
    this.db.models.channel.belongsToMany(this.db.models.role, {as:"Roles",through: 'p_role_channel',constraints: false,});

    /*渠道和服务项目之间的关系*/
    this.db.models.servicesitem.belongsTo(this.db.models.channel,{constraints: false,})
    this.db.models.channel.hasMany(this.db.models.servicesitem,{constraints: false,});

    //一个账户可以转换为企业用户，关联一个企业
    /*账户和公司之间的关系*/
    this.db.models.company.belongsTo(this.db.models.account,{constraints: false,})
    this.db.models.account.hasOne(this.db.models.company,{constraints: false,});
    /*建立交易和账户和产品之间的关系*/
    this.db.models.trade.belongsTo(this.db.models.account,{constraints: false,});
    this.db.models.trade.belongsTo(this.db.models.product,{constraints: false,});
    this.db.models.trade.belongsTo(this.db.models.user,{constraints: false,});
    /*建立附件和交易之间的关系*/
    this.db.models.attachment.belongsTo(this.db.models.trade,{constraints: false,});

    /*建立镜像和代码之间的关系*/
   this.db.models.mirrorinfo.belongsTo(this.db.models.code,{constraints: false,});
   this.db.models.code.hasMany(this.db.models.mirrorinfo,{as:"Mirrors",constraints: false,});

   /*建立容器和镜像、机器之间的关系*/
  this.db.models.container.belongsTo(this.db.models.mirrorinfo,{constraints: false,});
  this.db.models.mirrorinfo.hasMany(this.db.models.container,{constraints: false,});
  this.db.models.container.belongsTo(this.db.models.machine,{constraints: false,});
  this.db.models.machine.hasMany(this.db.models.container,{constraints: false,});

      /*建立频道和文章之间的关系*/
      this.db.models.article.belongsTo(this.db.models.newschannel,{constraints: false,});
      this.db.models.newschannel.hasMany(this.db.models.article,{constraints: false,});
      this.db.models.newschannel.belongsTo(this.db.models.app,{constraints: false,});
      this.db.models.article.belongsTo(this.db.models.app,{constraints: false,});
      //  console.log("init relations....");


      this.db.models.calculateprice.belongsTo(this.db.models.order,{constraints: false,});
      this.db.models.order.hasMany(this.db.models.calculateprice,{constraints: false,});
      this.db.models.tmcustomerinfo.belongsTo(this.db.models.order,{constraints: false,});
      this.db.models.order.hasOne(this.db.models.tmcustomerinfo,{constraints: false,});

      /*建立用户和合伙人信息之间的关系，user存在于partnerinfo并且是以外键user_id方式存在partnerinfo中*/
      this.db.models.partnerinfo.belongsTo(this.db.models.user,{constraints: false,});
      this.db.models.user.hasOne(this.db.models.partnerinfo,{constraints: false,});

      /*建立应用和合伙人信息之间的关系*/
      this.db.models.partnerinfo.belongsTo(this.db.models.app,{constraints: false,});
      this.db.models.app.hasMany(this.db.models.partnerinfo,{constraints: false,});

      /*建立api调用日志和api之间的关系*/
      this.db.models.apitrade.belongsTo(this.db.models.app,{constraints: false,});

      this.db.models.etemplate.belongsTo(this.db.models.ecompany,{constraints: false,});
      this.db.models.ecompany.hasMany(this.db.models.etemplate,{constraints: false,});

      this.db.models.econtract.belongsTo(this.db.models.etemplate,{constraints: false,});
      this.db.models.etemplate.hasMany(this.db.models.econtract,{constraints: false,});

      this.db.models.econtract.belongsTo(this.db.models.user,{constraints: false,});
      this.db.models.econtract.belongsTo(this.db.models.usereaccount,{constraints: false,});
      this.db.models.user.hasMany(this.db.models.econtract,{constraints: false,});

      this.db.models.econtract.belongsTo(this.db.models.ecompany,{constraints: false,});
      this.db.models.ecompany.hasMany(this.db.models.econtract,{constraints: false,});

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

      this.db.models.businessallot.belongsTo(this.db.models.channelmanageallot,{constraints: false,});
      this.db.models.businessallot.belongsTo(this.db.models.businesschance,{constraints: false,});
      this.db.models.businessallot.belongsTo(this.db.models.user,{constraints: false,});

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

      /*渠道和服务类型之间的关系*/
      this.db.models.servicetype.belongsTo(this.db.models.channel,{constraints: false,})
      this.db.models.channel.hasMany(this.db.models.servicetype,{constraints: false,});

      /*渠道和营业执照表之间的关系*/
      this.db.models.businesslicense.belongsTo(this.db.models.channel,{constraints: false,})
      this.db.models.channel.hasMany(this.db.models.businesslicense,{constraints: false,});
      /*渠道和购买营业执照表之间的关系*/
      this.db.models.buybusinesslicense.belongsTo(this.db.models.channel,{constraints: false,})
      this.db.models.channel.hasMany(this.db.models.buybusinesslicense,{constraints: false,});

      // channel_id           int comment '渠道id',  自动生成
      // user_id   自动生成


    /*
       初次注册，赠送宝币10000个
               平台账户宝币余额-10000,
               交易类型是赠送，price=0,baoAmount=10000,renAmount=0
               注册账户的宝币余额+10000
       消费
              交易类型是消费,price=xx,baoAmount=-xxxx,renAmount=0
              注册账户的宝币余额+10000-xxx
              平台账户宝币余额-10000+xxx
       充值购买
              交易类型是充值，price=yy,baoAmount=yy,renAmount=yyren
              注册账户的宝币余额+10000-xxx+yy
              平台的宝币余额 -yy
              平台的收入余额 +yyren
    */

  }
    //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;
  }
  getConhb(){
   var that=this;
   if(settings.env=="dev"){
   }
   return this.dbhb;
 }
}
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);
//   });
