<?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="org.sky.scientific.mapper.SubjectMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="ResultMap" type="org.sky.scientific.pojo.entity.Subject">
        <id column="id" property="id"/>
        <result column="tenant_id" property="tenantId"/>
        <result column="type" property="type"/>
        <result column="parent_id" property="parentId"/>
        <result column="code" property="code"/>
        <result column="name" property="name"/>
        <result column="acc_subject" property="accSubject"/>
        <result column="rd_subject_enable" property="rdSubjectEnable"/>
        <result column="rd_subject" property="rdSubject"/>
        <result column="ad_subject_enable" property="adSubjectEnable"/>
        <result column="ad_subject" property="adSubject"/>
    </resultMap>

    <resultMap id="treeNodeResultMap" type="org.sky.core.tool.node.TreeNode">
        <id column="id" property="id"/>
        <result column="parent_id" property="parentId"/>
        <result column="title" property="title"/>
        <result column="value" property="value"/>
        <result column="key" property="key"/>
    </resultMap>

    <resultMap id="ResultVoMap" type="org.sky.scientific.pojo.vo.SubjectVO" extends="ResultMap">
        <result column="has_children" property="hasChildren"/>
    </resultMap>

    <select id="getByName" resultMap="ResultMap">
        select *
        from kd_subject
        where name = #{name} and parent_id = #{parentId}
        and (type = 1 or (type = 0 and tenant_id = #{tenantId}))
    </select>

<!--    <select id="getByCode" resultMap="ResultMap">-->
<!--        select *-->
<!--        from kd_subject-->
<!--        where code = #{code} and parent_id = #{parentId}-->
<!--          and (type = 1 or (type = 0 and tenant_id = #{tenantId}))-->
<!--    </select>-->

    <select id="getMaxCode" resultType="java.lang.String">
        select max(code)
        from kd_subject
        where parent_id = #{parentId}
    </select>

    <delete id="deleteSubject">
        delete from kd_subject where id = #{subjectId}
    </delete>

    <select id="lazyList" resultMap="ResultVoMap">
        SELECT
            sub.*,
            (
                SELECT
                    CASE WHEN count( 1 ) > 0 THEN 1 ELSE 0 END
                FROM
                    kd_subject
                WHERE
                    parent_id = sub.id
            ) AS "has_children"
        FROM
            kd_subject sub
        where (sub.type=1 or (sub.type=0 and sub.tenant_id = #{tenantId}))
        <if test="ew.code!=null and ew.code !=''">and code like concat('%',#{ew.code},'%')</if>
        <if test="ew.name!=null and ew.name !=''">and name like concat('%',#{ew.name},'%')</if>
        order by code asc
     </select>
</mapper>
