<?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">
<!-- UIWS system 이식: 공통코드 그룹/값(tb_uiws_code_grp, tb_uiws_code). -->
<mapper namespace="com.zioinfo.mes.uiws.system.mapper.CodeMapper">

    <sql id="kw">
        <if test="keyword != null and keyword != ''">
            AND (grp_cd ILIKE '%' || #{keyword} || '%' OR grp_nm ILIKE '%' || #{keyword} || '%')
        </if>
    </sql>

    <select id="searchGroups" resultType="com.zioinfo.mes.uiws.system.model.SysCodeGrp">
        SELECT * FROM tb_uiws_code_grp WHERE 1=1 <include refid="kw"/>
        ORDER BY grp_cd ASC
        LIMIT #{size} OFFSET #{offset}
    </select>

    <select id="countGroups" resultType="long">
        SELECT COUNT(*) FROM tb_uiws_code_grp WHERE 1=1 <include refid="kw"/>
    </select>

    <select id="findGroupById" resultType="com.zioinfo.mes.uiws.system.model.SysCodeGrp">
        SELECT * FROM tb_uiws_code_grp WHERE grp_cd = #{grpCd}
    </select>

    <select id="groupExists" resultType="boolean">
        SELECT EXISTS(SELECT 1 FROM tb_uiws_code_grp WHERE grp_cd = #{grpCd})
    </select>

    <insert id="insertGroup" parameterType="com.zioinfo.mes.uiws.system.model.SysCodeGrp">
        INSERT INTO tb_uiws_code_grp (grp_cd, grp_nm, use_yn, created_by, created_at)
        VALUES (#{grpCd}, #{grpNm}, #{useYn}, #{createdBy}, now())
    </insert>

    <update id="updateGroup" parameterType="com.zioinfo.mes.uiws.system.model.SysCodeGrp">
        UPDATE tb_uiws_code_grp SET
            grp_nm = #{grpNm}, use_yn = #{useYn}, updated_by = #{updatedBy}, updated_at = now()
        WHERE grp_cd = #{grpCd}
    </update>

    <delete id="deleteGroup">
        DELETE FROM tb_uiws_code_grp WHERE grp_cd = #{grpCd}
    </delete>

    <select id="findValuesByGrp" resultType="com.zioinfo.mes.uiws.system.model.SysCode">
        SELECT * FROM tb_uiws_code WHERE grp_cd = #{grpCd} ORDER BY sort_ord ASC, code_val ASC
    </select>

    <select id="findActiveValuesByGrp" resultType="com.zioinfo.mes.uiws.system.model.SysCode">
        SELECT * FROM tb_uiws_code WHERE grp_cd = #{grpCd} AND use_yn = 'Y'
        ORDER BY sort_ord ASC, code_val ASC
    </select>

    <insert id="insertValue" parameterType="com.zioinfo.mes.uiws.system.model.SysCode">
        INSERT INTO tb_uiws_code (grp_cd, code_val, code_nm, sort_ord, use_yn, created_by, created_at)
        VALUES (#{grpCd}, #{codeVal}, #{codeNm}, #{sortOrd}, #{useYn}, #{createdBy}, now())
    </insert>

    <delete id="deleteValuesByGrp">
        DELETE FROM tb_uiws_code WHERE grp_cd = #{grpCd}
    </delete>
</mapper>
