package com.scpyun.platform.jilinsscgsdp.utils;

import com.alibaba.fastjson.JSON;
import com.scpyun.base.core.utils.StringUtils;
import com.scpyun.base.core.utils.UnifyLogger;
import com.scpyun.platform.jilinsscgsdp.utils.RedisTemplateUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
 *
 * @Title:  GetUserRedisInfoUtil
 * @Package GetUserRedisInfoUtil.java
 * @Description: copy By scp-grid
 * @author:  guojiucoder
 * @date:   2024/7/31 14:09
 * @version V1.0.0
 *
 */
public class GetUserRedisInfoUtil {

	private static final String redis = "grid";

	public void getUserRedisInfo(HttpServletRequest request, String uuid, Integer grade) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (c.getName().equals("juyou.session.id")) {
					String key = c.getValue();
//					juyou_session_05d1573a87f94966bde6ce7eae40ef62_info
					String redisKey = "juyou_session_" + key + "_info";
					String redisInfo = RedisTemplateUtils.get(redisKey, redis);
					Map<String, Object> infoMap = JSON.parseObject(redisInfo, Map.class);
					if (infoMap != null) {
						Map<String, String> redis_userMap = (Map<String, String>) infoMap.get("_user");
						if (grade == 6) {
							if (redis_userMap.get("garden_id") == null) {
								redis_userMap.put("garden_id", uuid);
							} else {
								String garden_id = StringUtils.toString(redis_userMap.get("garden_id"));
								redis_userMap.put("garden_id", garden_id + "," + uuid);
							}
							infoMap.put("_user", redis_userMap);
							RedisTemplateUtils.set(redisKey, JSON.toJSONString(infoMap), 14400, redis);
						}
						if (grade == 7) {
							if (redis_userMap.get("building_id") == null) {
								redis_userMap.put("building_id", uuid);
							} else {
								String building_id = StringUtils.toString(redis_userMap.get("building_id"));
								redis_userMap.put("building_id", building_id + "," + uuid);
							}
							infoMap.put("_user", redis_userMap);
							RedisTemplateUtils.set(redisKey, JSON.toJSONString(infoMap), 14400, redis);
						}
					}
				} else {
					UnifyLogger.parent("【getUserRedisInfo】获取 juyou.session.id 异常！", UnifyLogger.Level.INFO);
				}
			}
		} else {
			UnifyLogger.parent("【getUserRedisInfo】获取 cookies 异常！", UnifyLogger.Level.INFO);
		}
	}
}
