/**
 * 
 */
package com.platomix.userprofile.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platomix.userprofile.enums.DsEnum;
import com.platomix.userprofile.mapper.DynamicExecuteMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Service
public class DynamicExecuteService {

	@Autowired
	private DynamicExecuteMapper dynamicExecuteMapper;

	@Value("${dflow.run-execute}")
	private Boolean runExecute;


	/**
	 * 
	 * @param dsEnum
	 * @param sql
	 */
	@DS("#dsEnum.name")
	public void execute(DsEnum dsEnum, String sql, String logRemark) {
		long startTime = System.currentTimeMillis();
		if(runExecute==true){
			dynamicExecuteMapper.execute(sql);
		}
		log.info(String.format("%s|cost: %ss", logRemark, (System.currentTimeMillis() - startTime)/1000.0f));
	}
	
	/**
	 * 
	 * @param dsEnum
	 * @param sql
	 * @return
	 */
	@DS("#dsEnum.name")
	public List<JSONObject> list(DsEnum dsEnum, String sql){
		return dynamicExecuteMapper.list(sql);
	}
	
	/**
	 * 
	 * @param dsEnum
	 * @param page
	 * @param sql
	 * @return
	 */
	@DS("#dsEnum.name")
	public List<JSONObject> pageList(DsEnum dsEnum, IPage<?> page, String sql) {
		return dynamicExecuteMapper.pageList(page, sql);
	}
	
	/**
	 * 
	 * @param dsEnum
	 * @param sql
	 * @return
	 */
	@DS("#dsEnum.name")
	public JSONObject get(DsEnum dsEnum, String sql) {
		return dynamicExecuteMapper.get(sql);
	}
	
	/**
	 * 检测clickHouse数据库中是否存在表
	 * @param tableName
	 * @return
	 */
	@DS("clickhouse")
	public boolean checkTableExistsOfClickhouse(String tableName) {
		JSONObject jsonObject = dynamicExecuteMapper.get("exists table " + tableName);
		return jsonObject != null && jsonObject.getIntValue("result") == 1;
	}
	
	
}
