<?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="com.zcloud.modules.sys.dao.SysDictionariesDao">

	<select id="queryListParentId" resultType="com.zcloud.modules.sys.entity.SysDictionariesEntity">
		select d.*,
		       (select count(1) from sys_dictionaries c where c.parent_id = d.dictionaries_id) has_children
		       from sys_dictionaries d where d.parent_id = #{parentId} order by d.order_by asc
	</select>

	<select id="getRecurrenceIds" resultType="java.lang.String">
		select getFullDIcId(#{id})
	</select>

	<select id="cteldAll" parameterType="String" resultType="com.zcloud.modules.sys.entity.SysDictionariesEntity">
	with recursive cte as (
		select * from sys_dictionaries where parent_id = #{parentId}
		union all
		select d.* from sys_dictionaries d inner join cte c on d.parent_id = c.dictionaries_id
	)
	select * from cte order by order_by asc
	</select>

	<delete id="deleteCte" parameterType="string">
		WITH RECURSIVE descendant_ids AS (
			SELECT dictionaries_id
			FROM sys_dictionaries
			WHERE parent_id = #{parentId}

			UNION ALL

			SELECT child.dictionaries_id
			FROM sys_dictionaries child
				     JOIN descendant_ids parent ON child.parent_id = parent.dictionaries_id
		)

		DELETE FROM sys_dictionaries
		WHERE dictionaries_id IN (SELECT dictionaries_id FROM descendant_ids);
	</delete>
</mapper>
