import mongoose = require('mongoose');
import { initMongoModel, initMysqlModel } from '../models/modelInit';
import { ERRORENUM } from '../../config/errorEnum';
import { systemConfig } from '../../config/serverConfig';
import { BizError } from '../../util/bizError';
const Sequelize = require('sequelize');


/**
 * 初始化数据库
 */
export async function initDataBaseModel() {
    if (systemConfig.specifyDB == 'mongo') {
        await toMongo();
    } else if (systemConfig.specifyDB == 'mysql') {
        await toMysql();
    } else if (systemConfig.specifyDB == 'all') {
        await toMongo();
        await toMysql();
    } else {
        console.log(`this service does not use a database`);
    }
}

async function toMysql() {
    let {dataBase, user, pwd, host, port} = systemConfig.mysqldb;
    let mysqlDB = new Sequelize(dataBase, user, pwd,{
        host:host,
        port:port,
        dialect:'mysql',   //数据库类型
        pool:{  //数据库连接池
            max:20,  //最大连接对象的个数
            min:5,  //最小连接对象的个数
            idle:1000  //最长等待时间，单位为毫秒
        },
        timezone: '+08:00', //东八时区
        dialectOptions: {
            dateStrings: true,
            typeCast: true
        },
    }); 
    await initMysqlModel(mysqlDB);
    console.log(`mysql connection success, connection config:${host}:${port}/${dataBase}`);
}

async function toMongo() {
    const DefaultOptions = {
        useNewUrlParser:true,
        auto_reconnect:true,
        // reconnectTries:1000,
        // reconnectInterval:3000,
        keepAlive: true,
        connectTimeoutMS: 3000,
        useCreateIndex: true,
        useUnifiedTopology: true
    };

    //如果配置了mongoServerConstVal 才会连接mongo
    if (systemConfig.mongodbStr) {
        console.log(systemConfig.mongodbStr);
        let dataBase = await mongoose.createConnection(systemConfig.mongodbStr, DefaultOptions).catch(
            (err)=>{
            throw err
        });
        await initMongoModel(dataBase);
        console.log(`mongodb connection success, connection config:${systemConfig.mongodbStr}`);
    } else {
        throw new BizError(ERRORENUM.系统错误, "xml中未配置mongo连接字符串 无法连接到mongodb");
    }
}