<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="net.chenlin.dp.modules.sys.dao.SysOrgMapper">
	
	<select id="countOrgChildren" resultType="int">
		SELECT
			COUNT(*)
		FROM
			sys_org
		WHERE
			parent_id = #{value}
	</select>

	<select id="listOrgChildren" resultType="long">
		SELECT
			org_id
		FROM
			sys_org
		WHERE
			parent_id = #{value}
	</select>
	
	<select id="list" resultType="net.chenlin.dp.modules.sys.entity.SysOrgEntity">
		SELECT
			o.org_id,
			o.parent_id,
			(
				SELECT
					p.name
				FROM
					sys_org p
				WHERE
					p.org_id = o.parent_id
			) AS parentName,
			o.code,
			o.name,
			o.status,
			o.order_num
		FROM
			sys_org o
		ORDER BY
			o.order_num ASC
	</select>	
		
	<insert id="save">
		INSERT INTO sys_org (
			org_id,
			parent_id,
			code,
			name,		
			order_num,
			status,
			gmt_create
		)
		VALUES (
			#{orgId},
			#{parentId},
			#{code},
			#{name},
			#{orderNum},
			#{status},
			NOW()
		)
	</insert>
	
	<select id="getObjectById" resultType="net.chenlin.dp.modules.sys.entity.SysOrgEntity">
		SELECT
			o.org_id,
			o.parent_id,
			(
				SELECT
					p.name
				FROM
					sys_org p
				WHERE
					p.org_id = o.parent_id
			) AS parentName,
			o.code,
			o.name,		
			o.status,
			o.order_num
		FROM
			sys_org o
		WHERE
			o.org_id = #{value}
	</select>
	
	<update id="update">
		UPDATE sys_org
		<set> 
			<if test="orgId != null">org_id = #{orgId}, </if>
			<if test="code != null">code = #{code}, </if>
			<if test="name != null">name = #{name}, </if>
			<if test="status != null">status = #{status}, </if>			
			<if test="orderNum != null">order_num = #{orderNum}, </if>
			gmt_modified = NOW()
		</set>
		where org_id = #{orgId}
	</update>
	
	<delete id="batchRemove">
		DELETE
		FROM
			sys_org
		WHERE
			org_id IN
		<foreach item="id" collection="array" open="(" separator="," close=")">
			#{id}
		</foreach>
	</delete>
	
</mapper>