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.service.SysAreaService;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDictItemService;
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(entry.getKey(),entry.getValue());
			}
		}
		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("area_" + 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("area_" + area.getAreaName()
							+ CommonConstants.DOWN_LINE_STRING
							+(Common.isNotNull(temp)?temp.getAreaName():""),area.getId());
				}else {
					redisUtil.set("area_" + area.getAreaName(),area.getId());
				}
			}
		}
		log.info("区域数据加入缓存初始化结束...");
	}
}
