<?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.ga.common.code.AccountCodeMapper">

    <resultMap id="AccountCodeMap" type="com.ga.common.code.AccountCodeVO"/>

    <sql id="Columns">
        account_code, account_name, account_type, is_active, sort_order, description,
        created_at, created_by, updated_at, updated_by
    </sql>

    <select id="selectAll" resultMap="AccountCodeMap">
        SELECT <include refid="Columns"/>
        FROM account_code
        <where>
            <if test="accountType != null and accountType != ''">
                AND account_type = #{accountType}
            </if>
        </where>
        ORDER BY sort_order, account_code
    </select>

    <select id="selectActive" resultMap="AccountCodeMap">
        SELECT <include refid="Columns"/>
        FROM account_code
        WHERE is_active = 'Y'
        <if test="accountType != null and accountType != ''">
            AND account_type = #{accountType}
        </if>
        ORDER BY sort_order, account_code
    </select>

    <select id="selectOne" resultMap="AccountCodeMap">
        SELECT <include refid="Columns"/>
        FROM account_code WHERE account_code = #{accountCode}
    </select>

    <insert id="insert" parameterType="com.ga.common.code.AccountCodeVO">
        INSERT INTO account_code (
            account_code, account_name, account_type, is_active, sort_order, description,
            created_at, created_by
        ) VALUES (
            #{accountCode}, #{accountName}, #{accountType},
            COALESCE(#{isActive},'Y'), COALESCE(#{sortOrder},0), #{description},
            now(), #{createdBy}
        )
    </insert>

    <update id="update" parameterType="com.ga.common.code.AccountCodeVO">
        UPDATE account_code SET
            account_name = #{accountName},
            account_type = #{accountType},
            is_active    = #{isActive},
            sort_order   = #{sortOrder},
            description  = #{description},
            updated_at   = now(),
            updated_by   = #{updatedBy}
        WHERE account_code = #{accountCode}
    </update>

    <delete id="delete">
        DELETE FROM account_code WHERE account_code = #{accountCode}
    </delete>

    <select id="existsByCode" resultType="int">
        SELECT COUNT(*) FROM account_code WHERE account_code = #{accountCode}
    </select>

</mapper>
