package org.springblade.third.iotdevice.util;

import org.springblade.common.utils.SerializableUtil;
import org.springblade.device.entity.IotAlarm;
import org.springblade.system.expand.entity.OrgPosition;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @author lidexi
 * @date 2021/5/28 10:07
 */

public class RedisUtil {

	public static void saveAlarmToRedis(IotAlarm alarm, String alarmOrgPosition, String tenantId, IUserClient userClient,
								  RedisTemplate redisTemplate,IOrgPositionClient orgPositionClient)  {

		if (alarmOrgPosition != null && alarmOrgPosition.trim() != "") {
			if (tenantId != null) {
				//查询出该租户下所有管理员账号
				List<User> users = userClient.userByTenantId(tenantId).getData();
				for (int i = 0; i < users.size(); i++) {
					//当前用户
					User user = users.get(i);
					if (isHasPermission(user, alarmOrgPosition,orgPositionClient)) {//若用户有权限
						String redisKey = "ycwg:alarm:" + user.getId()+":"+alarm.getId();
						try {
							redisTemplate.opsForValue().set(redisKey, SerializableUtil.serializeToString(alarm));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}


				}
			}
		}
	}

	/**
	 * 判断用户账号有没有权限看到该告警记录
	 *
	 * @param user
	 * @param orgPosition
	 * @return
	 */
	private static boolean isHasPermission(User user, String orgPosition, IOrgPositionClient orgPositionClient) {
		boolean flag = false;
		String deptId = user.getDeptId();
		String[] deptIds = deptId.split(",");
		for (int i = 0; i < deptIds.length; i++) {
			OrgPosition search = new OrgPosition();
			search.setOrgId(Long.valueOf(deptIds[i]));
			OrgPosition orgPosition1 = orgPositionClient.detail(search);
			if (orgPosition1 != null){
				if(orgPosition.contains(orgPosition1.getOrgPosition())){
					flag = true;
					break;
				}
			}

		}
		return flag;
	}
}
