
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/	
    
var mysql=require("mysql");

//mysql 初始化
/*-------------------------------------------------------------------------------------------*/	    
    
class db_mysql
{
	static async con() 
	{	
		const cdb=$DbMysql.$opt
        for (const key in cdb) 
        {
			let cur=cdb[key]
			$DbMysql.$con[key]=mysql.createPool(cur);
			if($DbMysql.$con[key])
			{
				console.info(`MYSQL进程：`+process.pid+`------初始化成功[${key}]`);
			}
			else
			{
				console.info(`MYSQL进程：`+process.pid+`------初始化错误[${key}]`);
			}
        }
	};

	static query(sql,key='main',tag,descript='')
	{
		if(!sql)return false;
		if($DbMysql.$info.sqlAble)console.info(`[sql-${descript?descript:'请求'}]\r\n`,sql.replace(/(\s*?)(\S.*?[\n|$])/g,'$2'));

		function cal(resolve,reject)
		{
			function my(e,con)
			{
				if(e)
				{
					if(con)
					{
						con.release();
					}
					reject(e);
				}
				else
				{	
					function bac(err,row)
					{
						if($DbMysql.$info.sqlBackAble)console.info(`[sql-${descript?descript:'请求'}]返回\r\n`,row);
						if(err)
						{
							con.release();
							reject(err);
						}
						else
						{
							if(!tag)
							{
								con.release();
								resolve(row);
							} 
							else
							{
								resolve({result:row,con:con});
							}
						}
					}
					con.query(sql,bac);
				}
			}
			$DbMysql.$con[key].getConnection(my);   		 		
		}
		return new Promise(cal);
	}

	static async lastid(con,tag)
	{
		if(!con)con=this;
		let result=await db_mysql.transactionQuery(con,'select @@IDENTITY as id');

		result=result.result;
		if(result)
		{
			return result[0]['id'];
		}
		if(tag)$Sys.err({message:"没发现id"});
		throw Error();
	}

	static async transactionQuery(con,sql,descript='')
	{
		if(!sql)
		{
			sql=con;
			con=this;
			if(!sql)return false;
			if($DbMysql.$info.sqlAble)console.info(`[sql-transaction-${descript?descript:'请求'}]\r\n`,sql.replace(/(\s*?)(\S.*?[\n|$])/g,'$2'));

			return new Promise
			(
				function(resolve,reject)
				{
					con.query
					(
						sql,
						function(err,row)
						{
							if(err)
							{
								reject(err);
							}
							else
							{
								if($DbMysql.$info.sqlBackAble)console.info(`[sql-transaction-${descript?descript:'请求'}]返回\r\n`,row);
								resolve(row);
							}
						},undefined,descript
					)
				}
			)
		}
		else
		{
			if($DbMysql.$info.sqlAble)console.info(`[sql-transaction-${descript?descript:'请求'}]\r\n`,sql.replace(/(\s*?)(\S.*?[\n|$])/g,'$2'));
			return new Promise
			(
				function(resolve,reject)
				{
					con.query
					(
						sql,
						function(err,row)
						{
							if(err)
							{
								reject(err);
							}
							else
							{
								if($DbMysql.$info.sqlBackAble)console.info(`[sql-transaction-${descript?descript:'请求'}]返回\r\n`,row);
								resolve({result:row,con:con});
							}
						},undefined,descript
					)
				}
			)
		}
	}


	static async transaction(fun,db='main')
	{
		var result=await db_mysql.query('begin',db,true)
		try 
		{
			result.con.querys=db_mysql.transactionQuery
			result.con.lastid=db_mysql.lastid
			let res=await fun(result.con)
			await db_mysql.transactionQuery(result.con,'commit');
			return (typeof res != 'undefined')?res:true;
		} 
		catch (error) 
		{
			await db_mysql.transactionQuery(result.con,'rollback');
			console.info('[mysql事物]出错：',error);
			$Sys.err(error);
			return false;
		}
		finally
		{
			result.con.release();
		}                 
	}
	
	static close(pool)
	{
		pool.end();
	}
}

module.exports=db_mysql;