Browse Source

场景增加子场景查询

wangyangyang 4 years ago
parent
commit
c71167b4e1

+ 304 - 0
sms_water/src/main/java/com/huaxu/common/Reflections.java

@@ -0,0 +1,304 @@
+/**
+ * Copyright (c) 2005-2012 springside.org.cn
+ */
+package com.huaxu.common;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.Validate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.Assert;
+
+/**
+ * 反射工具类.
+ * 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
+ * @author calvin
+ * @version 2013-01-15
+ */
+@SuppressWarnings("rawtypes")
+public class Reflections {
+	
+	private static final String SETTER_PREFIX = "set";
+
+	private static final String GETTER_PREFIX = "get";
+
+	private static final String CGLIB_CLASS_SEPARATOR = "$$";
+	
+	private static Logger logger = LoggerFactory.getLogger(Reflections.class);
+
+	/**
+	 * 调用Getter方法.
+	 * 支持多级,如:对象名.对象名.方法
+	 */
+	public static Object invokeGetter(Object obj, String propertyName) {
+		Object object = obj;
+		for (String name : StringUtils.split(propertyName, ".")){
+			String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
+			object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
+		}
+		return object;
+	}
+
+	/**
+	 * 调用Setter方法, 仅匹配方法名。
+	 * 支持多级,如:对象名.对象名.方法
+	 */
+	public static void invokeSetter(Object obj, String propertyName, Object value) {
+		Object object = obj;
+		String[] names = StringUtils.split(propertyName, ".");
+		for (int i=0; i<names.length; i++){
+			if(i<names.length-1){
+				String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
+				object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
+			}else{
+				String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
+				invokeMethodByName(object, setterMethodName, new Object[] { value });
+			}
+		}
+	}
+
+	/**
+	 * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
+	 */
+	public static Object getFieldValue(final Object obj, final String fieldName) {
+		Field field = getAccessibleField(obj, fieldName);
+
+		if (field == null) {
+			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
+		}
+
+		Object result = null;
+		try {
+			result = field.get(obj);
+		} catch (IllegalAccessException e) {
+			logger.error("不可能抛出的异常{}", e.getMessage());
+		}
+		return result;
+	}
+
+	/**
+	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
+	 */
+	public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
+		Field field = getAccessibleField(obj, fieldName);
+
+		if (field == null) {
+			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
+		}
+
+		try {
+			field.set(obj, value);
+		} catch (IllegalAccessException e) {
+			logger.error("不可能抛出的异常:{}", e.getMessage());
+		}
+	}
+
+	/**
+	 * 直接调用对象方法, 无视private/protected修饰符.
+	 * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
+	 * 同时匹配方法名+参数类型,
+	 */
+	public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
+			final Object[] args) {
+		Method method = getAccessibleMethod(obj, methodName, parameterTypes);
+		if (method == null) {
+			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
+		}
+
+		try {
+			return method.invoke(obj, args);
+		} catch (Exception e) {
+			throw convertReflectionExceptionToUnchecked(e);
+		}
+	}
+
+	/**
+	 * 直接调用对象方法, 无视private/protected修饰符,
+	 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
+	 * 只匹配函数名,如果有多个同名函数调用第一个。
+	 */
+	public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
+		Method method = getAccessibleMethodByName(obj, methodName);
+		if (method == null) {
+			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
+		}
+
+		try {
+			return method.invoke(obj, args);
+		} catch (Exception e) {
+			throw convertReflectionExceptionToUnchecked(e);
+		}
+	}
+
+	/**
+	 * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
+	 * 
+	 * 如向上转型到Object仍无法找到, 返回null.
+	 */
+	public static Field getAccessibleField(final Object obj, final String fieldName) {
+		Validate.notNull(obj, "object can't be null");
+		Validate.notBlank(fieldName, "fieldName can't be blank");
+		for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
+			try {
+				Field field = superClass.getDeclaredField(fieldName);
+				makeAccessible(field);
+				return field;
+			} catch (NoSuchFieldException e) {//NOSONAR
+				// Field不在当前类定义,继续向上转型
+				continue;// new add
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
+	 * 如向上转型到Object仍无法找到, 返回null.
+	 * 匹配函数名+参数类型。
+	 * 
+	 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
+	 */
+	public static Method getAccessibleMethod(final Object obj, final String methodName,
+			final Class<?>... parameterTypes) {
+		Validate.notNull(obj, "object can't be null");
+		Validate.notBlank(methodName, "methodName can't be blank");
+
+		for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
+			try {
+				Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
+				makeAccessible(method);
+				return method;
+			} catch (NoSuchMethodException e) {
+				// Method不在当前类定义,继续向上转型
+				continue;// new add
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
+	 * 如向上转型到Object仍无法找到, 返回null.
+	 * 只匹配函数名。
+	 * 
+	 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
+	 */
+	public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
+		Validate.notNull(obj, "object can't be null");
+		Validate.notBlank(methodName, "methodName can't be blank");
+
+		for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
+			Method[] methods = searchType.getDeclaredMethods();
+			for (Method method : methods) {
+				if (method.getName().equals(methodName)) {
+					makeAccessible(method);
+					return method;
+				}
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
+	 */
+	public static void makeAccessible(Method method) {
+		if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
+				&& !method.isAccessible()) {
+			method.setAccessible(true);
+		}
+	}
+
+	/**
+	 * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
+	 */
+	public static void makeAccessible(Field field) {
+		if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
+				.isFinal(field.getModifiers())) && !field.isAccessible()) {
+			field.setAccessible(true);
+		}
+	}
+
+	/**
+	 * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
+	 * 如无法找到, 返回Object.class.
+	 * eg.
+	 * public UserDao extends HibernateDao<User>
+	 *
+	 * @param clazz The class to introspect
+	 * @return the first generic declaration, or Object.class if cannot be determined
+	 */
+	@SuppressWarnings("unchecked")
+	public static <T> Class<T> getClassGenricType(final Class clazz) {
+		return getClassGenricType(clazz, 0);
+	}
+
+	/**
+	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
+	 * 如无法找到, 返回Object.class.
+	 * 
+	 * 如public UserDao extends HibernateDao<User,Long>
+	 *
+	 * @param clazz clazz The class to introspect
+	 * @param index the Index of the generic ddeclaration,start from 0.
+	 * @return the index generic declaration, or Object.class if cannot be determined
+	 */
+	public static Class getClassGenricType(final Class clazz, final int index) {
+
+		Type genType = clazz.getGenericSuperclass();
+
+		if (!(genType instanceof ParameterizedType)) {
+			logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
+			return Object.class;
+		}
+
+		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
+
+		if (index >= params.length || index < 0) {
+			logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+					+ params.length);
+			return Object.class;
+		}
+		if (!(params[index] instanceof Class)) {
+			logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
+			return Object.class;
+		}
+
+		return (Class) params[index];
+	}
+	
+	public static Class<?> getUserClass(Object instance) {
+		Assert.notNull(instance, "Instance must not be null");
+		Class clazz = instance.getClass();
+		if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
+			Class<?> superClass = clazz.getSuperclass();
+			if (superClass != null && !Object.class.equals(superClass)) {
+				return superClass;
+			}
+		}
+		return clazz;
+
+	}
+	
+	/**
+	 * 将反射时的checked exception转换为unchecked exception.
+	 */
+	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
+		if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
+				|| e instanceof NoSuchMethodException) {
+			return new IllegalArgumentException(e);
+		} else if (e instanceof InvocationTargetException) {
+			return new RuntimeException(((InvocationTargetException) e).getTargetException());
+		} else if (e instanceof RuntimeException) {
+			return (RuntimeException) e;
+		}
+		return new RuntimeException("Unexpected Checked Exception.", e);
+	}
+}

+ 351 - 0
sms_water/src/main/java/com/huaxu/common/StringUtils.java

@@ -0,0 +1,351 @@
+/**
+ * Copyright &copy;1997-2017 <a href="http://www.hxiswater.com">huaxutech</a> All rights reserved.
+ */
+package com.huaxu.common;
+
+import java.io.UnsupportedEncodingException;
+import java.util.List;
+import java.util.Locale;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.servlet.LocaleResolver;
+
+import com.google.common.collect.Lists;
+
+/**
+ * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
+ * @author wyy
+ * @version 2013-05-22
+ */
+public class StringUtils extends org.apache.commons.lang3.StringUtils {
+	
+    private static final char SEPARATOR = '_';
+    private static final String CHARSET_NAME = "UTF-8";
+    
+    /**
+     * 转换为字节数组
+     * @param str
+     * @return
+     */
+    public static byte[] getBytes(String str){
+    	if (str != null){
+    		try {
+				return str.getBytes(CHARSET_NAME);
+			} catch (UnsupportedEncodingException e) {
+				return null;
+			}
+    	}else{
+    		return null;
+    	}
+    }
+    
+    /**
+     * 转换为字节数组
+     * @param bytes
+     * @return
+     */
+    public static String toString(byte[] bytes){
+    	try {
+			return new String(bytes, CHARSET_NAME);
+		} catch (UnsupportedEncodingException e) {
+			return EMPTY;
+		}
+    }
+    
+    /**
+     * 是否包含字符串
+     * @param str 验证字符串
+     * @param strs 字符串组
+     * @return 包含返回true
+     */
+    public static boolean inString(String str, String... strs){
+    	if (str != null){
+        	for (String s : strs){
+        		if (str.equals(trim(s))){
+        			return true;
+        		}
+        	}
+    	}
+    	return false;
+    }
+    
+	/**
+	 * 替换掉HTML标签方法
+	 */
+	public static String replaceHtml(String html) {
+		if (isBlank(html)){
+			return "";
+		}
+		String regEx = "<.+?>";
+		Pattern p = Pattern.compile(regEx);
+		Matcher m = p.matcher(html);
+		String s = m.replaceAll("");
+		return s;
+	}
+	
+	/**
+	 * 替换为手机识别的HTML,去掉样式及属性,保留回车。
+	 * @param html
+	 * @return
+	 */
+	public static String replaceMobileHtml(String html){
+		if (html == null){
+			return "";
+		}
+		return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
+	}
+
+
+	/**
+	 * 缩略字符串(不区分中英文字符)
+	 * @param str 目标字符串
+	 * @param length 截取长度
+	 * @return
+	 */
+	public static String abbr(String str, int length) {
+		if (str == null) {
+			return "";
+		}
+		try {
+			StringBuilder sb = new StringBuilder();
+			int currentLength = 0;
+			for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
+				currentLength += String.valueOf(c).getBytes("GBK").length;
+				if (currentLength <= length - 3) {
+					sb.append(c);
+				} else {
+					sb.append("...");
+					break;
+				}
+			}
+			return sb.toString();
+		} catch (UnsupportedEncodingException e) {
+			e.printStackTrace();
+		}
+		return "";
+	}
+	
+	public static String abbr2(String param, int length) {
+		if (param == null) {
+			return "";
+		}
+		StringBuffer result = new StringBuffer();
+		int n = 0;
+		char temp;
+		boolean isCode = false; // 是不是HTML代码
+		boolean isHTML = false; // 是不是HTML特殊字符,如&nbsp;
+		for (int i = 0; i < param.length(); i++) {
+			temp = param.charAt(i);
+			if (temp == '<') {
+				isCode = true;
+			} else if (temp == '&') {
+				isHTML = true;
+			} else if (temp == '>' && isCode) {
+				n = n - 1;
+				isCode = false;
+			} else if (temp == ';' && isHTML) {
+				isHTML = false;
+			}
+			try {
+				if (!isCode && !isHTML) {
+					n += String.valueOf(temp).getBytes("GBK").length;
+				}
+			} catch (UnsupportedEncodingException e) {
+				e.printStackTrace();
+			}
+
+			if (n <= length - 3) {
+				result.append(temp);
+			} else {
+				result.append("...");
+				break;
+			}
+		}
+		// 取出截取字符串中的HTML标记
+		String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)",
+				"$1$2");
+		// 去掉不需要结素标记的HTML标记
+		temp_result = temp_result
+				.replaceAll(
+						"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
+						"");
+		// 去掉成对的HTML标记
+		temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>",
+				"$2");
+		// 用正则表达式取出标记
+		Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
+		Matcher m = p.matcher(temp_result);
+		List<String> endHTML = Lists.newArrayList();
+		while (m.find()) {
+			endHTML.add(m.group(1));
+		}
+		// 补全不成对的HTML标记
+		for (int i = endHTML.size() - 1; i >= 0; i--) {
+			result.append("</");
+			result.append(endHTML.get(i));
+			result.append(">");
+		}
+		return result.toString();
+	}
+	
+	/**
+	 * 转换为Double类型
+	 */
+	public static Double toDouble(Object val){
+		if (val == null){
+			return 0D;
+		}
+		try {
+			return Double.valueOf(trim(val.toString()));
+		} catch (Exception e) {
+			return 0D;
+		}
+	}
+
+	/**
+	 * 转换为Float类型
+	 */
+	public static Float toFloat(Object val){
+		return toDouble(val).floatValue();
+	}
+
+	/**
+	 * 转换为Long类型
+	 */
+	public static Long toLong(Object val){
+		return toDouble(val).longValue();
+	}
+
+	/**
+	 * 转换为Integer类型
+	 */
+	public static Integer toInteger(Object val){
+		return toLong(val).intValue();
+	}
+
+	
+	/**
+	 * 获得用户远程地址
+	 */
+	public static String getRemoteAddr(HttpServletRequest request){
+		String remoteAddr = request.getHeader("X-Real-IP");
+        if (isNotBlank(remoteAddr)) {
+        	remoteAddr = request.getHeader("X-Forwarded-For");
+        }else if (isNotBlank(remoteAddr)) {
+        	remoteAddr = request.getHeader("Proxy-Client-IP");
+        }else if (isNotBlank(remoteAddr)) {
+        	remoteAddr = request.getHeader("WL-Proxy-Client-IP");
+        }
+        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
+	}
+
+	/**
+	 * 驼峰命名法工具
+	 * @return
+	 * 		toCamelCase("hello_world") == "helloWorld" 
+	 * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
+	 * 		toUnderScoreCase("helloWorld") = "hello_world"
+	 */
+    public static String toCamelCase(String s) {
+        if (s == null) {
+            return null;
+        }
+
+        s = s.toLowerCase();
+
+        StringBuilder sb = new StringBuilder(s.length());
+        boolean upperCase = false;
+        for (int i = 0; i < s.length(); i++) {
+            char c = s.charAt(i);
+
+            if (c == SEPARATOR) {
+                upperCase = true;
+            } else if (upperCase) {
+                sb.append(Character.toUpperCase(c));
+                upperCase = false;
+            } else {
+                sb.append(c);
+            }
+        }
+
+        return sb.toString();
+    }
+
+    /**
+	 * 驼峰命名法工具
+	 * @return
+	 * 		toCamelCase("hello_world") == "helloWorld" 
+	 * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
+	 * 		toUnderScoreCase("helloWorld") = "hello_world"
+	 */
+    public static String toCapitalizeCamelCase(String s) {
+        if (s == null) {
+            return null;
+        }
+        s = toCamelCase(s);
+        return s.substring(0, 1).toUpperCase() + s.substring(1);
+    }
+    
+    /**
+	 * 驼峰命名法工具
+	 * @return
+	 * 		toCamelCase("hello_world") == "helloWorld" 
+	 * 		toCapitalizeCamelCase("hello_world") == "HelloWorld"
+	 * 		toUnderScoreCase("helloWorld") = "hello_world"
+	 */
+    public static String toUnderScoreCase(String s) {
+        if (s == null) {
+            return null;
+        }
+
+        StringBuilder sb = new StringBuilder();
+        boolean upperCase = false;
+        for (int i = 0; i < s.length(); i++) {
+            char c = s.charAt(i);
+
+            boolean nextUpperCase = true;
+
+            if (i < (s.length() - 1)) {
+                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
+            }
+
+            if ((i > 0) && Character.isUpperCase(c)) {
+                if (!upperCase || !nextUpperCase) {
+                    sb.append(SEPARATOR);
+                }
+                upperCase = true;
+            } else {
+                upperCase = false;
+            }
+
+            sb.append(Character.toLowerCase(c));
+        }
+
+        return sb.toString();
+    }
+ 
+    /**
+     * 转换为JS获取对象值,生成三目运算返回结果
+     * @param objectString 对象串
+     *   例如:row.user.id
+     *   返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
+     */
+    public static String jsGetVal(String objectString){
+    	StringBuilder result = new StringBuilder();
+    	StringBuilder val = new StringBuilder();
+    	String[] vals = split(objectString, ".");
+    	for (int i=0; i<vals.length; i++){
+    		val.append("." + vals[i]);
+    		result.append("!"+(val.substring(1))+"?'':");
+    	}
+    	result.append(val.substring(1));
+    	return result.toString();
+    }
+    
+}

+ 7 - 1
sms_water/src/main/java/com/huaxu/controller/SceneController.java

@@ -113,7 +113,13 @@ public class SceneController {
         int result = sceneService.updateSceneById(scene) ? 1 : 0;
         return new AjaxMessage<>(ResultStatus.OK, result);
     }
-
+    @RequestMapping(value = "/findByParentIdsLike", method = RequestMethod.GET)
+    @ResponseBody
+    @ApiOperation(value = "根据父级ID查询所有子节点及本身")
+    public  List<Long> findByParentIdsLike(@ApiParam(value = "父级场景ID", required = false)@RequestParam(required = false) Long id) {
+        List<Long> longs = sceneService.findByParentIdsLike(id);
+        return longs;
+    }
     /**
      * 删除
      */

+ 2 - 0
sms_water/src/main/java/com/huaxu/dao/SceneMapper.java

@@ -33,5 +33,7 @@ public interface SceneMapper extends BaseMapper<SceneEntity> {
 
     List<SceneEntity> findByParentSceneIds(@Param(value = "Ids") Long[] Ids);
 
+    List<SceneEntity> findByParentIdsLike(@Param(value = "scene") SceneEntity sceneEntity);
+
     /**删除相关方法  使用mybatis-plus集成的 **/
 }

+ 4 - 0
sms_water/src/main/java/com/huaxu/entity/SceneEntity.java

@@ -38,6 +38,10 @@ public class SceneEntity implements Serializable {
     @ApiModelProperty(value = "上级场景")
     private Long parentSceneId;
 
+    /** 上级场景IDS */
+    @ApiModelProperty(value = "上级场景IDS")
+    private String parentSceneIds;
+
     /** 场景名称 */
     @ApiModelProperty(value = "场景名称")
     private String sceneName;

+ 103 - 19
sms_water/src/main/java/com/huaxu/service/SceneService.java

@@ -2,6 +2,8 @@ package com.huaxu.service;
 
 
 import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.huaxu.common.Reflections;
+import com.huaxu.common.StringUtils;
 import com.huaxu.dao.SceneImageMapper;
 import com.huaxu.dao.SceneMapper;
 import com.huaxu.entity.SceneEntity;
@@ -133,6 +135,8 @@ public class SceneService extends ServiceImpl<SceneMapper, SceneEntity> {
         return this.removeById(id);
     }
 
+
+
     /**
      * 保存
      */
@@ -140,44 +144,124 @@ public class SceneService extends ServiceImpl<SceneMapper, SceneEntity> {
         LoginUser currentUser = UserUtil.getCurrentUser();
         scene.setTenantId(currentUser.getTenantId());
         scene.setStatus(1);
+
+        // 如果没有设置父节点,则代表为跟节点,有则获取父节点实体
+        if (scene.getParentSceneId() == null || StringUtils.isBlank(scene.getParentSceneId().toString())) {
+            scene.setParentSceneId(Long.valueOf(0));
+        } else {
+            scene.setParentSceneId(scene.getParentSceneId());
+        }
+        if (scene.getParentSceneId() == null) {
+            scene.setParentSceneIds("0,");
+        }
+        //查询父节点信息
+        SceneEntity sceneEntity = sceneMapper.findSceneById(scene.getParentSceneId());
         if (this.save(scene)) {
             Long id = scene.getId();
+            // 设置新的父节点串
+            if (sceneEntity != null) {
+                scene.setParentSceneIds(sceneEntity.getParentSceneIds() + id + ",");
+            } else {
+                scene.setParentSceneIds("0," + id + ",");
+            }
+            sceneMapper.updateById(scene);
+
             //增加场景图片
-            for(SceneImageEntity sceneImage: scene.getSceneImages())
-            {
-                sceneImage.setCreateBy(currentUser.getName());
-                sceneImage.setDateCreate(new Date());
-                sceneImage.setDateUpdate(new Date());
-                sceneImage.setSceneId(id);
-                sceneImage.setStatus(1);
-                sceneImage.setUpdateBy(currentUser.getName());
+            if (scene.getSceneImages() != null) {
+                for (SceneImageEntity sceneImage : scene.getSceneImages()) {
+                    sceneImage.setCreateBy(currentUser.getName());
+                    sceneImage.setDateCreate(new Date());
+                    sceneImage.setDateUpdate(new Date());
+                    sceneImage.setSceneId(id);
+                    sceneImage.setStatus(1);
+                    sceneImage.setUpdateBy(currentUser.getName());
+                }
+                sceneImageService.saveBatch(scene.getSceneImages());
             }
-            sceneImageService.saveBatch(scene.getSceneImages());
             return true;
         }
         return false;
     }
-
+    /**
+     * 根据父级ID查询所有子节点及本身
+     */
+    public  List<Long> findByParentIdsLike(Long id) {
+        LoginUser currentUser = UserUtil.getCurrentUser();
+        SceneEntity scene = new SceneEntity();
+        if (id != null)
+            scene.setParentSceneIds("%," + id + ",%");
+        scene.setTenantId(currentUser.getTenantId());
+        scene.setStatus(1);
+        scene.setProgramItems(currentUser.getProgramItemList());
+        scene.setUserType(currentUser.getType());
+        //1是公司,2是公司及以下,3部门,4部门及以下,5自定义
+        scene.setPermissonType(currentUser.getPermissonType());
+        List<SceneEntity> list = sceneMapper.findByParentIdsLike(scene);
+        List<Long> longs = newArrayList();
+        for (SceneEntity item : list) {
+            longs.add(item.getId());
+        }
+        return longs;
+    }
     /**
      * 修改根居ID
      */
     public boolean updateSceneById(SceneEntity scene) {
         LoginUser currentUser = UserUtil.getCurrentUser();
         scene.setUpdateBy(currentUser.getName());
+
+        // 获取修改前的parentIds,用于更新子节点的parentIds
+        SceneEntity cScene = sceneMapper.findSceneById(scene.getId());
+        String oldParentIds = cScene.getParentSceneIds();
+        // 如果没有设置父节点,则代表为跟节点,有则获取父节点实体
+        if (scene.getParentSceneId() == null || StringUtils.isBlank(scene.getParentSceneId().toString())) {
+            scene.setParentSceneId(Long.valueOf(0));
+        } else {
+            scene.setParentSceneId(scene.getParentSceneId());
+        }
+        if (scene.getParentSceneId() == null) {
+            scene.setParentSceneIds("0,");
+        }
+        //查询父节点信息
+        SceneEntity sceneEntity = sceneMapper.findSceneById(scene.getParentSceneId());
         if (this.updateById(scene)) {
+            // 设置新的父节点串
+            if (sceneEntity != null) {
+                scene.setParentSceneIds(sceneEntity.getParentSceneIds() + scene.getId() + ",");
+            } else {
+                scene.setParentSceneIds("0," + scene.getId() + ",");
+            }
+            sceneMapper.updateById(scene);
+            // 更新子节点 parentIds
+            Class<SceneEntity> entityClass = Reflections.getClassGenricType(getClass(), 1);
+            SceneEntity o = null;
+            try {
+                o = entityClass.newInstance();
+            } catch (Exception e) {
+
+            }
+            o.setParentSceneIds("%,"+scene.getId()+",%");
+            List<SceneEntity> list = sceneMapper.findByParentIdsLike(o);
+            for (SceneEntity e : list) {
+                if (!e.getId().equals(scene.getId()) && e.getParentSceneId() != null && oldParentIds != null) {
+                    e.setParentSceneIds(e.getParentSceneIds().replace(oldParentIds, scene.getParentSceneIds()));
+                    sceneMapper.updateById(e);
+                }
+            }
             //删除之前的图片信息
              sceneImageService.updateBySceneId(scene.getId());
             //增加场景图片
-            for(SceneImageEntity sceneImage: scene.getSceneImages())
-            {
-                sceneImage.setCreateBy(currentUser.getName());
-                sceneImage.setDateCreate(new Date());
-                sceneImage.setDateUpdate(new Date());
-                sceneImage.setSceneId(scene.getId());
-                sceneImage.setStatus(1);
-                sceneImage.setUpdateBy(currentUser.getName());
+            if(scene.getSceneImages()!=null) {
+                for (SceneImageEntity sceneImage : scene.getSceneImages()) {
+                    sceneImage.setCreateBy(currentUser.getName());
+                    sceneImage.setDateCreate(new Date());
+                    sceneImage.setDateUpdate(new Date());
+                    sceneImage.setSceneId(scene.getId());
+                    sceneImage.setStatus(1);
+                    sceneImage.setUpdateBy(currentUser.getName());
+                }
+                sceneImageService.saveBatch(scene.getSceneImages());
             }
-            sceneImageService.saveBatch(scene.getSceneImages());
             return true;
         }
         return false;