<?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.capa.mapper.CapaMapper">

  <resultMap id="capaMap" type="com.zioinfo.mes.capa.MesCapa">
    <id property="id" column="id"/>
    <result property="capaNo" column="capa_no"/>
    <result property="ncrNo" column="ncr_no"/>
    <result property="capaType" column="capa_type"/>
    <result property="title" column="title"/>
    <result property="rootCause" column="root_cause"/>
    <result property="actionPlan" column="action_plan"/>
    <result property="owner" column="owner"/>
    <result property="dueDate" column="due_date"/>
    <result property="effectiveness" column="effectiveness"/>
    <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="capaMap">
    SELECT * FROM mes_capa
    <where>
      <if test="status != null and status != ''">AND status = #{status}</if>
      <if test="capaType != null and capaType != ''">AND capa_type = #{capaType}</if>
    </where>
    ORDER BY id DESC
  </select>

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

  <insert id="insert" parameterType="com.zioinfo.mes.capa.MesCapa" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_capa (capa_no, ncr_no, capa_type, title, root_cause, action_plan, owner,
      due_date, effectiveness, status, created_by)
    VALUES (#{capaNo}, #{ncrNo}, #{capaType}, #{title}, #{rootCause}, #{actionPlan}, #{owner},
      #{dueDate}, #{effectiveness}, #{status}, #{createdBy})
  </insert>

  <update id="update" parameterType="com.zioinfo.mes.capa.MesCapa">
    UPDATE mes_capa SET capa_type = #{capaType}, title = #{title}, root_cause = #{rootCause},
      action_plan = #{actionPlan}, owner = #{owner}, due_date = #{dueDate}, updated_at = NOW()
    WHERE id = #{id}
  </update>

  <update id="updateStatus">
    UPDATE mes_capa SET status = #{status},
      effectiveness = COALESCE(#{effectiveness}, effectiveness), updated_at = NOW()
    WHERE id = #{id}
  </update>

</mapper>
