/**
 * 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.TBusiLogS;
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;

/**
 * <pre>
 * 主要用于平台启动或者平台通用管理的一些日志使用
 * </pre>
 *
 * @author 田平 create 2017年8月11日下午12:44:04
 */
@Slf4j
@Repository
public class BusiLogJdbcDao {

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

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

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

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

	/**
	 * <pre>支持幂等性插入，同一个id，可以反复调用，解决消息极端情况的重复消费</pre>
	 *
	 * @param busiLog
	 * @return
	 */
	public int insertTBusiLog(TBusiLogS busiLog) {
		int size = JT.queryForInt(callBusiCountSql, busiLog.getId());
		if (size > 0) {
			log.info(busiLog + " already insert t_busi_log!");
			return 0;
		} else {
			return DomainUtil.createDomain(NPJT, busiLog);
		}
	}

	/**
	 * <pre>支持幂等性，同一个id可以多次插入</pre>
	 *
	 * @param callLogs
	 * @return
	 */
	public int insertTBusiLogs(List<TBusiLogS> callLogs) {
		int size = 0;
		if (!callLogs.isEmpty()) {
			Map<String, Object> map = new HashMap<>();
			map.put("ids", callLogs.stream().map(TBusiLogS::getId).collect(Collectors.toList()));
			List<Long> existsIds = NPJT.queryForRawObjects(Long.class, callBusiBatchCountSql, map);
			List<TBusiLogS> curr = null;
			if (existsIds.size() > 0) {
				log.info("{} already insert t_busi_log!", existsIds);
				curr = callLogs.stream().filter(log -> !existsIds.contains(log.getId())).collect(Collectors.toList());
			} else {
				curr = callLogs;
			}
			DomainUtil.createDomains(NPJT, curr, true);
			size = curr.size();
		}
		return size;
	}

}
