<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zioinfo.cms.menu.mapper.MenuMapper">

  <resultMap id="menuMap" type="com.zioinfo.cms.menu.CmsMenu">
    <id property="id" column="id"/>
    <result property="parentId" column="parent_id"/>
    <result property="name" column="name"/>
    <result property="menuType" column="menu_type"/>
    <result property="url" column="url"/>
    <result property="slug" column="slug"/>
    <result property="sortOrder" column="sort_order"/>
    <result property="depth" column="depth"/>
    <result property="active" column="is_active"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="menuMap">
    SELECT * FROM cms_menu
    <where>
      <if test="menuType != null and menuType != ''">AND menu_type = #{menuType}</if>
    </where>
    ORDER BY depth ASC, sort_order ASC NULLS LAST, id ASC
  </select>

  <select id="findById" resultMap="menuMap">SELECT * FROM cms_menu WHERE id = #{id}</select>

  <insert id="insert" parameterType="com.zioinfo.cms.menu.CmsMenu" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO cms_menu (parent_id, name, menu_type, url, slug, sort_order, depth, is_active)
    VALUES (#{parentId}, #{name}, #{menuType}, #{url}, #{slug}, #{sortOrder}, #{depth}, #{active})
  </insert>

  <update id="update" parameterType="com.zioinfo.cms.menu.CmsMenu">
    UPDATE cms_menu SET parent_id = #{parentId}, name = #{name}, menu_type = #{menuType}, url = #{url},
      slug = #{slug}, sort_order = #{sortOrder}, is_active = #{active}
    WHERE id = #{id}
  </update>

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

  <select id="countChildren" resultType="int">SELECT COUNT(*) FROM cms_menu WHERE parent_id = #{parentId}</select>

</mapper>
