/**
 * 
 */
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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 ComplainTagHandler extends AbstractTagHandler {

	final static String ZT_TABLE_NAME = "ads.ZT_USER_COMPLAIN";
	
	@Autowired
	private UserprofileTagService userprofileTagService;
	
	@Override
	public void invoke(String month, String mobileLeft, String mobileRight) {
		// 查询投诉次数标签
		LambdaQueryWrapper<UserprofileTag> queryWrapper = Wrappers.<UserprofileTag>lambdaQuery().eq(UserprofileTag::getEnglishName, "tag_complain");
		List<UserprofileTag> tagList = userprofileTagService.list(queryWrapper);
		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);
		
		StrBuilder sqlBuilder = new StrBuilder();
		sqlBuilder.appendLn(super.buildTableSql(ZT_TABLE_NAME, "THEMONTH_COMPLAIN", "USERID_COMPLAIN"));
		sqlBuilder.append("select ACCEPT_PHONENUM as USERID_COMPLAIN,").append("'"+month+"'").appendLn(" as THEMONTH_COMPLAIN,");
		//标签范围值
		/**
		 * (case when TAG_COMPLAIN_V = 0 then 'B112_22_001'
			when TAG_COMPLAIN_V = 1 then 'B112_22_002'
			when TAG_COMPLAIN_V >= 2 and TAG_COMPLAIN_V <= 3 then 'B112_22_003'
			when TAG_COMPLAIN_V >= 4 and TAG_COMPLAIN_V <= 5 then 'B112_22_004'
			when TAG_COMPLAIN_V > 5 then 'B112_22_005'
			end) TAG_COMPLAIN,
		 */
		String sql = genBucketSql("tag_complain", "TAG_COMPLAIN_V", "COUNT(1)", tagListMap.get("tag_complain"));
		sqlBuilder.appendLn(sql);
		sqlBuilder.appendLn("from ads.FCT_CS_COMPLAINT_DETAIL")
				  .appendLn("where THEMONTH < '"+month+"'")
				  .appendLn("group by ACCEPT_PHONENUM");
		log.info("\n" + sqlBuilder.toString());
		dynamicExecuteService.execute(DsEnum.clickhouse, sqlBuilder.toString(), "信息化标签生成");
	}
}
