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

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

import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.platomix.userprofile.enums.DsEnum;
import com.platomix.userprofile.handler.AbstractTagHandler;
import com.platomix.userprofile.utils.StrBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *	
 *	订购偏好预测
 */
@Slf4j
@Service
@Deprecated
public class ForecastOrderTagHandler2 extends AbstractTagHandler {

	final static String ZT_TABLE_NAME = "ads.ZT_ORDER_PREFERENCE";
	final static String ZT_TEMP_TABLE_NAME = "ads.ZT_ORDER_PREFERENCE_temp1";
	
	@Override
	public void invoke(String month, String mobileLeft, String mobileRight) {
		//1.获取临时表的字段
		List<JSONObject> tempColumnList = dynamicExecuteService.list(DsEnum.clickhouse, "desc " + ZT_TEMP_TABLE_NAME);
		List<String> userIdColumnList = new ArrayList<>(),
					 columnList = new ArrayList<>();
		for(JSONObject jsonObj : tempColumnList) {
			String columnName = jsonObj.getString("name");
			if(columnName.contains("USERID")) {
				userIdColumnList.add(columnName);
			}else {
				columnList.add(columnName);
			}
		}
		StrBuilder sqlBuilder = new StrBuilder();
		sqlBuilder.appendLn(super.buildTableSql(ZT_TABLE_NAME, "THEMONTH_PRE", "USERID_PRE"));
		sqlBuilder.append("select USERID_PRE,").append("'"+month+"'").appendLn(" as THEMONTH_PRE,");
		for(String coldot : columnList) {
			String col = coldot.split("\\.")[1];
			sqlBuilder.appendLn(String.format("any(`%s`) as %s,", col, col));
		}
		sqlBuilder.deleteLastChar().deleteLastChar().appendLn("");
		sqlBuilder.append("from ( select multiIf(");
		for(String useridCol : userIdColumnList) {
			sqlBuilder.appendLn(String.format("`%s` != '', `%s`, ", useridCol, useridCol));
		}
		sqlBuilder.appendLn("'err') as USERID_PRE,");
		for(String coldot : columnList) {
			String colAlias = coldot.split("\\.")[1];
			sqlBuilder.appendLn(String.format("`%s` as %s,", coldot, colAlias));
		}
		sqlBuilder.deleteLastChar().deleteLastChar().appendLn("");
		sqlBuilder.appendLn("from ads.ZT_ORDER_PREFERENCE_temp");
		if(!StringUtils.isEmpty(mobileLeft) && !StringUtils.isEmpty(mobileRight)) {
			List<String> whereSql = new ArrayList<>();
			for(String useridCol : userIdColumnList) {
				whereSql.add(String.format("(`%s` >= '%s' and `%s` < '%s')", useridCol, mobileLeft, useridCol, mobileRight));
			}
			if(!whereSql.isEmpty()) sqlBuilder.append(" where ").appendLn(String.join(" or \n", whereSql));
		}
		sqlBuilder.appendLn(")  group by USERID_PRE");
		log.info("\n" + sqlBuilder.toString());
//		dynamicExecuteService.execute(DsEnum.clickhouse, sqlBuilder.toString(), "退订预测标签生成");
	}
	
	@Override
	public boolean executeInBatchs() {
		return true;
	}
}
