/**
 * 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.TOperLogS;
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 OperLogJdbcDao {

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

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

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

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

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

	public int insertTOperLog(TOperLogS operLog) {
		int size = JT.queryForInt(operLogCountSql, operLog.getId());
		if (size > 0) {
			log.info(operLog + " already insert t_oper_log!");
			return 0;
		} else {
			return DomainUtil.createDomain(NPJT, operLog);
		}
	}

}
