/**
 * 
 */
package com.platomix.userprofile.handler.support;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class UserEventManager {
	
	@Autowired
	private DynamicExecuteService dynamicExecuteService;
	
	/**
	 * 生成事件缓存表
	 */
	public void genEventPropToMysql() {
		genEventAttrProp();
		genEventCommonProp();
	}
	
	/**
	 * 生成事件关联字典表里的数据
	 */
	public void genEventDicTables() {
		StrBuilder sqlBuilder = new StrBuilder()
				.appendLn("insert into ads.DIM_TB_CHANNELS_2")
				.appendLn("with (select MAX(cnt)+1 from (select CHANNEL,COUNT() as cnt from ads.HIS_FLOW_ORDER  group by CHANNEL having THEMONTH >'202101')) as  MaxCnt")
				.appendLn(" select ID,MaxCnt-cnt as order_number,NAME from (")
				.appendLn("   select ID,cnt,NAME from ( select CHANNEL,COUNT() as cnt from ads.HIS_FLOW_ORDER group by CHANNEL  having THEMONTH >'202101')s")
				.appendLn("  left join ads.DIM_TB_CHANNELS d on s.CHANNEL=d.ID")
				.appendLn("where ID!='' order by cnt desc)");
		log.info("\n" + sqlBuilder.toString());
//		dynamicExecuteService.execute(DsEnum.clickhouse, sqlBuilder.toString(), "");
	}
	
	/**
	 * 生成attr形式缓存
	 */
	public void genEventAttrProp() {
		List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.clickhouse, "select id,name from ads.DIC_EVENT_PROP where is_preset = 1");
		for(JSONObject dataObj : dataList) {
			String id = dataObj.getString("id");
			StrBuilder sqlBuilder = new StrBuilder();
			sqlBuilder.appendLn("select prop_position,proj_code ,code as event from")
					  .appendLn("(select event_id,prop_position from ads.DIC_EVENT_PROP_MAP where prop_id = "+id+") s1")
					  .appendLn("left join ads.DIC_PROJECT_EVENT_MAP s2 on s1.event_id=s2.event_id")
					  .appendLn("left join ads.DIC_EVENT s3 on s1.event_id=s3.id")
					  .appendLn("left join ads.DIC_PROJECT s4 on s2.project_id=s4.id");
			List<JSONObject> events = dynamicExecuteService.list(DsEnum.clickhouse, sqlBuilder.toString());
			
			//拼接事件SQL
			List<String> seclectSqlList = new ArrayList<>();
			for(JSONObject eventObj : events) {
				String projCode = eventObj.getString("proj_code"),
					   event    = eventObj.getString("event"),
					   position = eventObj.getString("prop_position");
				seclectSqlList.add("select "+position+" as attr from ads.user_event where proj ='"+projCode+"' and event ='"+event+"'");
			}
			//事件SQL不为空
			if(!seclectSqlList.isEmpty()) {
				sqlBuilder = new StrBuilder();
				sqlBuilder.appendLn("select attr,COUNT() as num from ( ")
						  .appendLn(String.join(" UNION all ", seclectSqlList))
						  .appendLn(") s group by s.attr having s.attr!='' and s.attr is not null order by num desc LIMIT 30");
				List<JSONObject> options = dynamicExecuteService.list(DsEnum.clickhouse, sqlBuilder.toString());
				//拼接更新SQL
				List<String> updateJsonList = new ArrayList<>();
				for(JSONObject eventObj : options) {
					String attr = eventObj.getString("attr");
					updateJsonList.add("{\"name\":\""+attr+"\",\"code\":\"\"}");
				}
				if(!updateJsonList.isEmpty()) {
					String uptSql = "update prop set options= '[" + String.join(",", updateJsonList) + "]' where id = " + id;
					log.info("\n" + uptSql);
					//更新mysql
					String logRemark = "update attr[id="+id+"]";
					dynamicExecuteService.execute(DsEnum.master, uptSql, logRemark);
				}
			}
		}
	}

	/**
	 * 生成common形式缓存
	 */
	public void genEventCommonProp() {
		List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.clickhouse, "select id,code from ads.DIC_EVENT_PROP where is_preset = 1 and is_common = 1");
		for(JSONObject dataObj : dataList) {
			String id   = dataObj.getString("id"),
				   code = dataObj.getString("code");
			String commonSql = "select attr,COUNT() as num from  (select "+code+" as attr from ads.user_event where toString("+code+")!='' and "+code+" is not null) s GROUP by attr order by num desc LIMIT 50";
			List<JSONObject> options = dynamicExecuteService.list(DsEnum.clickhouse, commonSql);
			//拼接更新SQL
			List<String> updateJsonList = new ArrayList<>();
			for(JSONObject eventObj : options) {
				String attr = eventObj.getString("attr");
				updateJsonList.add("{\"name\":\""+attr+"\",\"code\":\"\"}");
			}
			if(!updateJsonList.isEmpty()) {
				String uptSql = "update prop set options= '[" + String.join(",", updateJsonList) + "]' where id = " + id;
				log.info("\n" + uptSql);
				//更新mysql
				String logRemark = "update attr[id="+id+"]";
				dynamicExecuteService.execute(DsEnum.master, uptSql, logRemark);
			}
		}
	}
}
