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

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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.model.UserprofileTag;
import com.platomix.userprofile.service.DynamicExecuteService;
import com.platomix.userprofile.service.UserprofileTagService;

/**
 * @author wookvn
 *
 */
@Component
public class UserTagManager {
	
	@Autowired
	private DynamicExecuteService dynamicExecuteService;
	
	@Autowired
	private UserprofileTagService tagService;

	/**
	 * 生成标签到mysql数据库
	 */
	public void genSomeTagToMysql() {
		genOrderProductClass();
		genOrderChannel();
		genOrderProducts();
	}
	
	/**
	 * 生成省份标签
	 */
	private void genProvince() {
		List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.oracle108, "select distinct PROV_DESC from XXH202010WO");
		List<UserprofileTag> tagList = new ArrayList<>();
		int index = 0;
		for(JSONObject itemObj : dataList) {
			String tagName = itemObj.getString("PROV_DESC"),
				   tagId   = String.format("A112_02_%03d", ++index);
			UserprofileTag itemTag = new UserprofileTag(tagId, tagName,null, "A", "大网标签", "A2", "省份", "tag_province",null,0,null,null,null);
			itemTag.setTagOrder(index);
			
			//是否上线
//			itemTag.setIsOnline("1");
			itemTag.setTagCType("string");
			itemTag.setSearchType("string");
			
			tagList.add(itemTag);
		}
//		tagService.saveBatch(tagList);
	}

	/**
	 * 生成城市标签
	 */
	private void genCity() {
		List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.clickhouse, "select distinct AREA from ads.FCT_TD_ORDER");
		List<UserprofileTag> tagList = new ArrayList<>();
		int index = 0;
		for(JSONObject itemObj : dataList) {
			String tagName = itemObj.getString("AREA"),
				   tagId   = String.format("A112_10_%03d", ++index);
			UserprofileTag itemTag = new UserprofileTag(tagId, tagName,null,  "A", "大网标签", "A10", "城市", "tag_area",null,0,null,null,null);
			itemTag.setTagDesc("城市");
			itemTag.setTagOrder(index);
			
			//是否上线
//			itemTag.setIsOnline("1");
			itemTag.setTagCType("string");
			itemTag.setSearchType("string");
			
//			//设置分桶规则
//			itemTag.setBucketLeft(">0");
//			itemTag.setBucketRight("<=10");
//			//OR
//			itemTag.setBucketFormula("");
			
			tagList.add(itemTag);
		}
//		tagService.saveBatch(tagList);
	}


	/**
	 * 生成产品标签
	 */
	private void genOrderProductClass() {
		String sql="select CPNAME,CPTYPE2 from\n" +
				"(\n" +
				"select DISTINCT CATEGORYNAME2 as CPNAME,CPTYPE2 from\n" +
				"ads.ETL_V_TB_SP_INFO\n" +
				"where CATEGORYNAME2 !=''\n" +
				"order by toInt32(CPTYPE2)\n" +
				") t0\n" +
				"left join (select tag_id ,tag_name  from ads.DIC_USERTAG where english_name ='event_cpname' )  t on t0.CPNAME=t.tag_name\n" +
				//" limit 2";
				"where tag_id =''";

		UserprofileTag confTag = new UserprofileTag(null, null,null,
				"B", "产品标签", "04", "产品类别", "event_cpname","1",2,"string","string","产品类别字典表CATEGORYNAME2");
		genTagBySql(sql,"CPNAME","CPTYPE2",confTag,true);
	}

	/**
	 * 订购产品
	 */
	private void genOrderProducts() {
		String before12Date = LocalDate.now().minusMonths(12).format(DateTimeFormatter.ofPattern("yyyyMM"));
		String sql="select  concat(SPNAME,'#',sp.SPID) as SPNAME,sp.SPID as SPID, num,tag_id ,tag_name  from\n" +
				"(\n" +
				"\tselect SPID,COUNT(SPID) as num  from (\n" +
				String.format("\tselect SPID from ads.ETL_TD_ORDER_RELATIONS_YEAR where THEMONTH >'%s'\n",before12Date) +
				"\t) group by SPID\n" +
				"\torder by num desc\n" +
				") sp\n" +
				"left join ads.ETL_V_TB_SP_INFO i on sp.SPID=i.SPID\n" +
				"left join (select tag_id ,tag_name,tag_value  from ads.DIC_USERTAG where english_name ='event_spname' )  t on i.SPID=t.tag_value\n" +
				"where SPNAME !='' and tag_id ='' and num >100";

		UserprofileTag confTag = new UserprofileTag(null, null,null,
				"B", "产品标签", "05", "订购产品", "event_spname","1",2,
				"String","String","订购产品");

		genTagBySql(sql,"SPNAME","SPID",confTag,true);
	}

	/**
	 * 订购产品渠道
	 */
	private void genOrderChannel() {
		String before12Date = LocalDate.now().minusMonths(12).format(DateTimeFormatter.ofPattern("yyyyMM"));
		String sql="select * from\n" +
				"(\n" +
				"\tselect DISTINCT concat(NAME,'#',CHANNEL) as ChannelName,CHANNEL,num\n" +
				"\tfrom\n" +
				"\t(\n" +
				"\t  select CHANNEL,COUNT(CHANNEL) as num  from (\n" +
				String.format("\t\tselect CHANNEL from ads.ETL_TD_ORDER_RELATIONS_YEAR where THEMONTH >='%s'\n",before12Date) +
				"\t\t) group by CHANNEL\n" +
				"\t\torder by num desc\n" +
				"\t) sp\n" +
				"\tleft join ads.DIM_TB_CHANNELS i on sp.CHANNEL=i.ID\n" +
				") t0\n" +
				"left join (select tag_id ,tag_name,tag_value  from ads.DIC_USERTAG where english_name ='event_channel' )  t on t0.CHANNEL=t.tag_value\n" +
				"where tag_id ='' and num>100";

		UserprofileTag confTag = new UserprofileTag(null, null,null,
				"B", "产品标签", "10", "订购渠道", "event_channel","1",2,
				"String","String","产品渠道");

		genTagBySql(sql,"ChannelName","CHANNEL",confTag,true);
	}
	
	/**
	 * 生成Tag
	 * @param sql 查询sql
	 * @param tag 标签 level2级别的属性
	 * @param continueIndex 是否从原有数据开始 插入
	 */
	private void genTagBySql(String sql,String nameField,String valueField, UserprofileTag tag,Boolean continueIndex) {
		List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.clickhouse, sql);
		List<UserprofileTag> tagList = new ArrayList<>();
		int index = getTagIdx(tag.getEnglishName(),continueIndex)+1;
		for(JSONObject itemObj : dataList) {
			String tagName = itemObj.getString(nameField),
					tagValue=itemObj.getString(valueField),
					tagId   = String.format("A112_%s_%03d",tag.getLevel2Id(), index++);
			UserprofileTag itemTag = new UserprofileTag(tagId, tagName,tagValue,  tag.getLevel1Id(), tag.getLevel1Name(),
					tag.getLevel1Id()+Integer.parseInt(tag.getLevel2Id()), tag.getLevel2Name(), tag.getEnglishName(),tag.getIsOnline(),tag.getShowHis(),tag.getTagCType(),tag.getSearchType(),
					tag.getTagDesc());

			itemTag.setTagOrder(index);

			//设置分桶规则
			//xxxxx
			tagList.add(itemTag);

		}
		System.out.println(tagList);
		tagService.saveBatch(tagList);
	}

	/**
	 * 获取最新的tag index
	 * @param englishName
	 * @return
	 */
	private Integer getTagIdx(String englishName,Boolean continueIndex){
		Integer i=0;
		if(continueIndex) {
			String sql = String.format("select  toUInt32(SUBSTRING(tag_id,9)) as maxIdx  from ads.DIC_USERTAG where english_name ='%s' order by tag_id desc LIMIT 1",englishName);
			List<JSONObject> dataList = dynamicExecuteService.list(DsEnum.clickhouse, sql);
			if (dataList.size() > 0) {
				i = dataList.get(0).getIntValue("maxIdx");
			}
		}
		return i;
	}
	
}