import { systemConfig } from "../../config/serverConfig";
import { BizError } from "../../util/bizError";
import { createMySqlConnect } from "./mysqlConnect";

let mysqlDB;
export function initMysqlDB() {
    // mysqlDB = createMySqlConnect(dbConfig.mysqlHost, dbConfig.mysqlPort, dbConfig.mysqlUser, dbConfig.mysqlPwd, dbConfig.dataBase);
    mysqlDB.connect(handleError);
    mysqlDB.on('error', handleError);
    //自定义方法
    bindSqlFunc();

    console.log("mysqlDB init success");
}

//断线重连
function handleError(err) {
    if (err) {
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            initMysqlDB();
        } else {
            console.error(err.stack || err);
        }
    }
}

//绑定方法
function bindSqlFunc() {
    mysqlDB.selectData = function(sql, ...param) {
        let _this = this;
        let paramList = [];
        param.forEach(thisStr => {
            paramList.push(thisStr);
        });
        return new Promise( (resolve, reject) => {
            _this.query(sql, paramList, (err, results, fields) => {
                if (err) throw new BizError(err); //todo要把数据库异常捕捉，并且输出: 逻辑错误
                else resolve(results);
            });
        });
    };

    mysqlDB.createData = function(table:string, param:object) {
        let _this = this;
        let sql = `insert into ${table} SET ?`;
        return new Promise( (resolve, reject) => {
            _this.query(sql, param, (err, results, fields) => {
                if (err) throw new BizError(err); //todo要把数据库异常捕捉，并且输出: 逻辑错误
                else resolve(results);
            });
        });
    }

    mysqlDB.updateData = function(table:string, param:object, contition:object) {
        let _this = this;
        let sql = `update ${table} set `;
        let valueList = [];
        let index = 1;
        let length = Object.keys(param).length;
        for (let key in param) {
            sql += ` ${key} = ? `;
            if ( index < length ) sql += `,`;
            index += 1;
            valueList.push(param[key]);
        }

        length = Object.keys(contition).length;
        if (length) {
            sql += ` where `;
            index = 1;
            
            for (let key in contition) {
                sql += ` ${key} = ? `;
                if ( index < length ) sql += `and`;
                index += 1;
                valueList.push(contition[key]);
            }
        }
 
        return new Promise( (resolve, reject) => {
            _this.query(sql, valueList, (err, results, fields) => {
                if (err) throw new BizError(err); //todo要把数据库异常捕捉，并且输出: 逻辑错误
                else resolve(results);
            });
        });
    }

    mysqlDB.findOne = function(sql, ...param) {
        let _this = this;
        let paramList = [];
        param.forEach(thisStr => {
            paramList.push(thisStr);
        });
        return new Promise( (resolve, reject) => {
            _this.query(sql, paramList, (err, results, fields) => {
                if (err) throw new BizError(err); //todo要把数据库异常捕捉，并且输出: 逻辑错误
                else resolve(results[0]);
            });
        });
    };

    mysqlDB.deleteData = function(tableName, paramaterInfo) {
        let _this = this;
        let sql = `DELETE FROM ${tableName} WHERE `;

        let index = 1;
        let paramList = [];
        let length = Object.keys(paramaterInfo).length;
        for (let key in paramaterInfo) {
            sql += ` ${key} = ? `;
            if ( index < length ) sql += `,`;
            index += 1;
            paramList.push(paramaterInfo[key]);
        }


        return new Promise( (resolve, reject) => {
            _this.query(sql, paramList, (err, results, fields) => {
                if (err) throw new BizError(err); //todo要把数据库异常捕捉，并且输出: 逻辑错误
                else resolve(results[0]);
            });
        });
    };
}


export {mysqlDB}