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

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.platomix.userprofile.enums.DsEnum;
import com.platomix.userprofile.utils.StrBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *	
 *	计算有效的手机号范围
 */
@Slf4j
@Service
public class MobileRangeService {

	@Autowired
	private DynamicExecuteService dynamicExecuteService;
	
	public final static long DEFAULT_STEP = 18000000L;
	
	final static String DEFAULT_MONTH = "202110";
	
	/**
	 * 根据步长获取手机号区间列表
	 * 说明：使用日期：202110的订购关系和信息化数据的用户，来计算用户手机号区间范围。【该日期用户比较全】
	 * @param step
	 * @return
	 */
	@Cacheable(cacheNames = "userProfileCache", key = "'mobile_range_'+#p0")
	public SortedSet<String> getList(long step){
		//todo
		log.info("计算用户手机号范围开始.....");
		long startTime = System.currentTimeMillis();
		StrBuilder sqlBuilder = new StrBuilder();
		sqlBuilder.appendLn("SELECT rowNumberInAllBlocks() % " + step + " as rNum, USERID")
				  .appendLn("from (select DEVICE_NUMBER as USERID from ads.XXH_ALL_MONTH_LONG order by USERID) where rNum=0");
		List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.clickhouse, sqlBuilder.toString());
		log.info("计算用户手机号范围结束.....|cost:{}s", (System.currentTimeMillis()-startTime)/1000);
		SortedSet<String> resultSet = new TreeSet<String>();
		if(dataList != null && !dataList.isEmpty()) {
			dataList.stream().map(item -> item.getString("USERID")).forEach(resultSet::add);
			resultSet.add("999");
		}
		return resultSet;
	}
	
}
