<?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.process.ProcessMapper">

  <resultMap id="procMap" type="com.zioinfo.mes.process.MesProcessProgress">
    <id property="id" column="id"/>
    <result property="workorderId" column="workorder_id"/>
    <result property="woNo" column="wo_no"/>
    <result property="opSeq" column="op_seq"/>
    <result property="processCode" column="process_code"/>
    <result property="processName" column="process_name"/>
    <result property="equipmentCode" column="equipment_code"/>
    <result property="workerId" column="worker_id"/>
    <result property="status" column="status"/>
    <result property="inputQty" column="input_qty"/>
    <result property="outputQty" column="output_qty"/>
    <result property="startedAt" column="started_at"/>
    <result property="endedAt" column="ended_at"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findByWorkorder" resultMap="procMap">
    SELECT * FROM mes_process_progress WHERE workorder_id = #{workorderId} ORDER BY op_seq ASC
  </select>
  <select id="findRunning" resultMap="procMap">
    SELECT * FROM mes_process_progress WHERE status = 'RUNNING' ORDER BY started_at DESC
  </select>
  <select id="findById" resultMap="procMap">SELECT * FROM mes_process_progress WHERE id = #{id}</select>

  <insert id="insert" parameterType="com.zioinfo.mes.process.MesProcessProgress" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_process_progress (workorder_id, wo_no, op_seq, process_code, process_name,
      equipment_code, worker_id, status, input_qty, output_qty)
    VALUES (#{workorderId}, #{woNo}, #{opSeq}, #{processCode}, #{processName},
      #{equipmentCode}, #{workerId}, #{status}, #{inputQty}, #{outputQty})
  </insert>

  <update id="update" parameterType="com.zioinfo.mes.process.MesProcessProgress">
    UPDATE mes_process_progress SET equipment_code = #{equipmentCode}, worker_id = #{workerId},
      input_qty = #{inputQty}, output_qty = #{outputQty} WHERE id = #{id}
  </update>

  <update id="updateStatus">
    UPDATE mes_process_progress
    SET status = #{status},
        started_at = CASE WHEN #{status} = 'RUNNING' AND started_at IS NULL THEN NOW() ELSE started_at END,
        ended_at = CASE WHEN #{status} = 'DONE' THEN NOW() ELSE ended_at END
    WHERE id = #{id}
  </update>

</mapper>
