<?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.receiving.ReceivingMapper">

  <resultMap id="recvMap" type="com.zioinfo.mes.receiving.MesReceiving">
    <id property="id" column="id"/>
    <result property="receivingNo" column="receiving_no"/>
    <result property="partnerCode" column="partner_code"/>
    <result property="itemCode" column="item_code"/>
    <result property="lotNo" column="lot_no"/>
    <result property="qty" column="qty"/>
    <result property="warehouseCode" column="warehouse_code"/>
    <result property="locationCode" column="location_code"/>
    <result property="status" column="status"/>
    <result property="inspectionRequired" column="inspection_required"/>
    <result property="inspectionResult" column="inspection_result"/>
    <result property="remark" column="remark"/>
    <result property="createdBy" column="created_by"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="recvMap">
    SELECT * FROM mes_receiving
    <where>
      <if test="status != null and status != ''">AND status = #{status}</if>
      <if test="itemCode != null and itemCode != ''">AND item_code = #{itemCode}</if>
    </where>
    ORDER BY id DESC
  </select>

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

  <insert id="insert" parameterType="com.zioinfo.mes.receiving.MesReceiving" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_receiving (receiving_no, partner_code, item_code, lot_no, qty, warehouse_code,
      location_code, status, inspection_required, inspection_result, remark, created_by)
    VALUES (#{receivingNo}, #{partnerCode}, #{itemCode}, #{lotNo}, #{qty}, #{warehouseCode},
      #{locationCode}, #{status}, #{inspectionRequired}, #{inspectionResult}, #{remark}, #{createdBy})
  </insert>

  <update id="updateStatus">
    UPDATE mes_receiving
    SET status = #{status},
        inspection_result = COALESCE(#{inspectionResult}, inspection_result)
    WHERE id = #{id}
  </update>

</mapper>
