/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.platform.jdbc.log;

import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.domain.common.jdbc.BaseNPJdbcTemplate;
import com.crunii.micro.domain.common.jdbc.DomainUtil;
import com.crunii.micro.domain.entitysql.main.TSqlLogS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 田平 create 2017年8月11日下午12:44:04
 */
@Slf4j
@Repository
public class SqlLogJdbcDao {

	@Resource(name = "mainJT")
	protected BaseJdbcTemplate JT;

	@Resource(name = "mainNPJT")
	protected BaseNPJdbcTemplate NPJT;

	private static final String sqlLogCountSql = "select count(*) from t_sql_log where id=? ";

	private static final String sqlLogBatchCountSql = "select id from t_sql_log where id in(:ids) ";

	public int insertTSqlLog(TSqlLogS sqlLog) {

		int size = JT.queryForInt(sqlLogCountSql, sqlLog.getId());
		if (size > 0) {
			log.info(sqlLog + " already insert t_sql_log!");
			return 0;
		} else {
			return DomainUtil.createDomain(NPJT, sqlLog);
		}
	}

	public int insertTSqlLogs(List<TSqlLogS> sqlLogs) {
		int size = 0;
		if (!sqlLogs.isEmpty()) {
			Map<String, Object> map = new HashMap<>();
			map.put("ids", sqlLogs.stream().map(TSqlLogS::getId).collect(Collectors.toList()));
			List<Long> existsIds = NPJT.queryForRawObjects(Long.class, sqlLogBatchCountSql, map);
			List<TSqlLogS> curr = null;
			if (existsIds.size() > 0) {
				log.info("{} already insert t_sql_log!", existsIds);
				curr = sqlLogs.stream().filter(log -> !existsIds.contains(log.getId())).collect(Collectors.toList());
			} else {
				curr = sqlLogs;
			}
			DomainUtil.createDomains(NPJT, curr, true);
			size = curr.size();
		}
		return size;
	}

}
