package jj.tech.paolu.biz.webadmin.service;


import static org.mybatis.dynamic.sql.SqlBuilder.*;

import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import jj.tech.paolu.biz.webadmin.component.Hgt8Component;
import jj.tech.paolu.repository.mybatis.dao.CurrentG24Mapper;
import jj.tech.paolu.repository.mybatis.dao.HistoryG24Mapper;
import jj.tech.paolu.repository.mybatis.dao.support.HistoryG24DynamicSqlSupport;
import jj.tech.paolu.repository.mybatis.entity.CurrentG24;
import jj.tech.paolu.repository.mybatis.entity.HistoryG24;
import jj.tech.paolu.utils.IDHelp;

@Service
public class G24Service {
	private static Logger logger = LoggerFactory.getLogger(G24Service.class);
	
	@Autowired CurrentG24Mapper currentG24Mapper;
	@Autowired HistoryG24Mapper historyG24Mapper;
	@Autowired ObjectMapper objectMapper;
	
	@Transactional
	public void getCurretG24Data(String json_data) {
		
		try {
			JsonNode root = objectMapper.readTree(json_data);
			String gameID = root.get("gameID").asText();
			String issue = root.get("issue").asText();
			String newIssue = root.get("newIssue").asText();
			String ball = root.get("ball").asText();
			Integer openTime = root.get("openTime").asInt();
			Integer closeTime = root.get("closeTime").asInt();
			
			if(StringUtils.isBlank(ball)) {
				return;
			}
						
			HistoryG24 his = 
			historyG24Mapper.selectOne(s->s
					.where()
					.and(HistoryG24DynamicSqlSupport.newIssue, isEqualTo(newIssue))
					.limit(1)
			).orElse(null);
			
			if(his==null) {
				
				LocalDateTime now = LocalDateTime.now();
				
				currentG24Mapper.delete(d->d.limit(5));
				
				CurrentG24 currentG24 = new CurrentG24();
				currentG24.setId(IDHelp.getInstance().nextId());
				currentG24.setIssue(issue);
				currentG24.setNewIssue(newIssue);
				currentG24.setBall(ball);
				currentG24.setOpenTime(openTime);
				currentG24.setCloseTime(closeTime);
				currentG24.setAddTime(now);
				currentG24.setGameID(gameID);
				currentG24Mapper.insertSelective(currentG24);
				
				HistoryG24 historyG24 = new HistoryG24();
				historyG24.setId(IDHelp.getInstance().nextId());
				historyG24.setIssue(issue);
				historyG24.setNewIssue(newIssue);
				historyG24.setBall(ball);
				historyG24.setOpenTime(openTime);
				historyG24.setCloseTime(closeTime);
				historyG24.setAddTime(now);
				historyG24.setGameID(gameID);
				historyG24Mapper.insert(historyG24);
				
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException(e);
		}
		
		
		
	}
	

}
