<?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.mes.bom.mapper.BomMapper">

  <resultMap id="bomMap" type="com.zioinfo.mes.bom.MesBom">
    <id property="id" column="id"/>
    <result property="parentItemCode" column="parent_item_code"/>
    <result property="childItemCode" column="child_item_code"/>
    <result property="qtyPer" column="qty_per"/>
    <result property="unit" column="unit"/>
    <result property="seq" column="seq"/>
    <result property="bomVersion" column="bom_version"/>
    <result property="lossRate" column="loss_rate"/>
    <result property="status" column="status"/>
    <result property="createdBy" column="created_by"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findByParent" resultMap="bomMap">
    SELECT * FROM mes_bom
    WHERE parent_item_code = #{parentItemCode} AND status = 'ACTIVE'
    <if test="bomVersion != null and bomVersion != ''">AND bom_version = #{bomVersion}</if>
    ORDER BY seq ASC, id ASC
  </select>

  <select id="findAll" resultMap="bomMap">
    SELECT * FROM mes_bom
    <where><if test="status != null and status != ''">AND status = #{status}</if></where>
    ORDER BY parent_item_code, seq
  </select>

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

  <insert id="insert" parameterType="com.zioinfo.mes.bom.MesBom" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_bom (parent_item_code, child_item_code, qty_per, unit, seq, bom_version, loss_rate, status, created_by)
    VALUES (#{parentItemCode}, #{childItemCode}, #{qtyPer}, #{unit}, #{seq}, #{bomVersion}, #{lossRate}, #{status}, #{createdBy})
  </insert>

  <update id="update" parameterType="com.zioinfo.mes.bom.MesBom">
    UPDATE mes_bom SET parent_item_code = #{parentItemCode}, child_item_code = #{childItemCode},
      qty_per = #{qtyPer}, unit = #{unit}, seq = #{seq}, bom_version = #{bomVersion},
      loss_rate = #{lossRate}, status = #{status}
    WHERE id = #{id}
  </update>

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

</mapper>
