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

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.platomix.userprofile.enums.DsEnum;
import com.platomix.userprofile.service.MobileRangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.platomix.userprofile.handler.AbstractTagHandler;
import com.platomix.userprofile.model.UserprofileTag;
import com.platomix.userprofile.service.UserprofileTagService;
import com.platomix.userprofile.utils.StrBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 * 
 * 	产品订购总时长
 */
@Slf4j
@Service
public class OrderSumDateTagHandler extends AbstractTagHandler {
	
	final static String ZT_TABLE_NAME = "ads.ZT_USER_TAG_ORDER_SUMDATE";

	@Autowired
	private UserprofileTagService userprofileTagService;
	
	@Override
	public void invoke(String month, String mobileLeft, String mobileRight) {
		// 查询所有标签
		List<UserprofileTag> tagList = userprofileTagService.list();
		Map<String, List<UserprofileTag>> tagListMap = tagList.stream().collect(Collectors.groupingBy(t -> t.getEnglishName().toLowerCase()));

		String lrMobileSql = mobileLeft == null || mobileRight == null ? "" : String.format(" and USERID>='%s' and USERID<'%s'", mobileLeft, mobileRight);
		String monthStart = month.substring(0, 4) + "-" + month.substring(4) + "-01";
		
		StrBuilder sqlBuilder = new StrBuilder();
		sqlBuilder.appendLn(super.buildTableSql(ZT_TABLE_NAME, "THEMONTH_OS", "USERID_OS"));
		sqlBuilder.append("select USERID as USERID_OS,").append("'"+month+"'").appendLn(" as THEMONTH_OS,");
		
		//标签范围值
		/**
		 * (case when  sumDate<=1  then 'B112_15_002'
			when  sumDate>1 and sumDate<=6 then 'B112_15_003'
			when  sumDate>6 and sumDate<=12 then 'B112_15_004'
			when  sumDate>12 and sumDate<=24 then 'B112_15_005'
			when  sumDate>24  then 'B112_15_006'
			end) EVENT_ORDER_SUMMONTH,
		 */
		String sql = genBucketSql("event_order_summonth", "sumDate", "sumDate", tagListMap.get("event_order_summonth"));
		sqlBuilder.appendLn(sql);
		sqlBuilder.appendLn("from (")
				  .appendLn("	select  USERID,sum(dateDiff('month',ORDERTIME,ENDTIME1)+1) as sumDate")
				  .appendLn("	from")
				  .appendLn("	(select DISTINCT USERID ,ORDERTIME, if(ENDTIME='1970-01-01', toDate('"+monthStart+"'),ENDTIME) as ENDTIME1")
				  .appendLn("		from ads.HIS_FLOW_ORDER")
				  .append("		    where THEMONTH <='"+month+"'").appendLn(lrMobileSql)
				  .appendLn(" 	) s")
				  .appendLn("	group by USERID")
				  .appendLn(") t");
		log.info("\n" + sqlBuilder.toString());
		dynamicExecuteService.execute(DsEnum.clickhouse, sqlBuilder.toString(), "信息化标签生成");
	}
	
	@Override
	public boolean executeInBatchs() {
		return false;
	}

}
