package com.yifu.cloud.plus.v1.yifu.admin.init;

import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysArea;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.DictRedisVo;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysAreaService;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDictItemService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author fxj
 * @Date 2022/6/23
 * @Description
 * @Version 1.0
 */
@Log4j2
@Component
public class DictItemRedisInit {
	@Autowired
	private SysDictItemService dictItemService;

	@Autowired
	private SysAreaService sysAreaService;

	@Autowired
	private RedisUtil redisUtil;

	@PostConstruct
	public void init(){
		log.info("字典数据加入缓存初始化开始...");
		Map<String, Object> dictItem = dictItemService.getAllDictItemSub();
		if (Common.isNotNull(dictItem)){
			for (Map.Entry<String,Object> entry:dictItem.entrySet()){
				redisUtil.set(CacheConstants.DICT_DETAILS
						+ CommonConstants.COLON_STRING
						+ entry.getKey(),entry.getValue());
			}
		}
		log.info("字典数据加入缓存初始化结束...");
		log.info("转义字典数据加入缓存初始化开始...");
		List<DictRedisVo> lables = dictItemService.getDictRedisVo();
		if (Common.isNotNull(lables)){
			Map<String,String>  lableMap = new HashMap<>();
			for (DictRedisVo vo:lables){
				lableMap.put(vo.getKey(),vo.getValue());
			}
			redisUtil.set(CacheConstants.REDIS_DICT_LABLE ,lableMap);
		}
		log.info("转义字典数据加入缓存初始化结束...");

		log.info("区域数据加入缓存初始化开始...");
		List<SysArea> allAreas = sysAreaService.getAllArea();
		if (Common.isNotNull(allAreas)){
			Map<String,SysArea> areaMap = new HashMap<>();
			for (SysArea area:allAreas){
				redisUtil.set(CacheConstants.AREA_LABEL
						+ area.getId(),area.getAreaName());
				areaMap.put(area.getId().toString(),area);
			}
			SysArea temp;
			for (SysArea area:allAreas){
				if (Common.isNotNull(area.getParentId()) &&  area.getParentId().intValue() > 0){
					temp = areaMap.get(area.getParentId().toString());
					redisUtil.set(CacheConstants.AREA_VALUE
							+ area.getAreaName()
							+ CommonConstants.DOWN_LINE_STRING
							+(Common.isNotNull(temp)?temp.getAreaName():""),area.getId());
				}else {
					redisUtil.set(CacheConstants.AREA_VALUE
							+ area.getAreaName(),area.getId());
				}
			}
		}
		log.info("区域数据加入缓存初始化结束...");
	}
}
