<?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.equipment.mapper.EquipmentMapper">

  <resultMap id="eqpMap" type="com.zioinfo.mes.equipment.MesEquipment">
    <id property="id" column="id"/>
    <result property="equipmentCode" column="equipment_code"/>
    <result property="equipmentName" column="equipment_name"/>
    <result property="processCode" column="process_code"/>
    <result property="warehouseCode" column="warehouse_code"/>
    <result property="checkCycleDays" column="check_cycle_days"/>
    <result property="lastCheckedAt" column="last_checked_at"/>
    <result property="parameters" column="parameters"/>
    <result property="runStatus" column="run_status"/>
    <result property="status" column="status"/>
    <result property="createdBy" column="created_by"/>
    <result property="createdAt" column="created_at"/>
    <result property="updatedAt" column="updated_at"/>
  </resultMap>

  <select id="findAll" resultMap="eqpMap">
    SELECT * FROM mes_equipment
    <where>
      <if test="status != null and status != ''">AND status = #{status}</if>
      <if test="runStatus != null and runStatus != ''">AND run_status = #{runStatus}</if>
    </where>
    ORDER BY id DESC
  </select>

  <select id="findById" resultMap="eqpMap">SELECT * FROM mes_equipment WHERE id = #{id}</select>
  <select id="findByCode" resultMap="eqpMap">SELECT * FROM mes_equipment WHERE equipment_code = #{equipmentCode}</select>

  <select id="countByCode" resultType="int">
    SELECT COUNT(*) FROM mes_equipment WHERE equipment_code = #{equipmentCode}
    <if test="excludeId != null">AND id != #{excludeId}</if>
  </select>

  <insert id="insert" parameterType="com.zioinfo.mes.equipment.MesEquipment" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_equipment (equipment_code, equipment_name, process_code, warehouse_code,
      check_cycle_days, last_checked_at, parameters, run_status, status, created_by)
    VALUES (#{equipmentCode}, #{equipmentName}, #{processCode}, #{warehouseCode},
      #{checkCycleDays}, #{lastCheckedAt}, #{parameters}::jsonb, #{runStatus}, #{status}, #{createdBy})
  </insert>

  <update id="update" parameterType="com.zioinfo.mes.equipment.MesEquipment">
    UPDATE mes_equipment SET equipment_code = #{equipmentCode}, equipment_name = #{equipmentName},
      process_code = #{processCode}, warehouse_code = #{warehouseCode}, check_cycle_days = #{checkCycleDays},
      last_checked_at = #{lastCheckedAt}, parameters = #{parameters}::jsonb, run_status = #{runStatus},
      status = #{status}, updated_at = NOW()
    WHERE id = #{id}
  </update>

  <update id="updateRunStatus">
    UPDATE mes_equipment SET run_status = #{runStatus}, updated_at = NOW() WHERE id = #{id}
  </update>

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

</mapper>
