<?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.partner.mapper.PartnerMapper">

  <resultMap id="partnerMap" type="com.zioinfo.mes.partner.MesPartner">
    <id property="id" column="id"/>
    <result property="partnerCode" column="partner_code"/>
    <result property="partnerName" column="partner_name"/>
    <result property="partnerType" column="partner_type"/>
    <result property="bizNo" column="biz_no"/>
    <result property="contactName" column="contact_name"/>
    <result property="contactPhoneEnc" column="contact_phone_enc"/>
    <result property="contactEmailEnc" column="contact_email_enc"/>
    <result property="address" column="address"/>
    <result property="status" column="status"/>
    <result property="createdBy" column="created_by"/>
    <result property="createdAt" column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="partnerMap">
    SELECT * FROM mes_partner
    <where>
      <if test="partnerType != null and partnerType != ''">AND partner_type = #{partnerType}</if>
      <if test="status != null and status != ''">AND status = #{status}</if>
      <if test="keyword != null and keyword != ''">
        AND (partner_code ILIKE '%' || #{keyword} || '%' OR partner_name ILIKE '%' || #{keyword} || '%')
      </if>
    </where>
    ORDER BY id DESC
  </select>

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

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

  <insert id="insert" parameterType="com.zioinfo.mes.partner.MesPartner" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mes_partner (partner_code, partner_name, partner_type, biz_no, contact_name,
      contact_phone_enc, contact_email_enc, address, status, created_by)
    VALUES (#{partnerCode}, #{partnerName}, #{partnerType}, #{bizNo}, #{contactName},
      #{contactPhoneEnc}, #{contactEmailEnc}, #{address}, #{status}, #{createdBy})
  </insert>

  <update id="update" parameterType="com.zioinfo.mes.partner.MesPartner">
    UPDATE mes_partner SET partner_code = #{partnerCode}, partner_name = #{partnerName},
      partner_type = #{partnerType}, biz_no = #{bizNo}, contact_name = #{contactName},
      <if test="contactPhoneEnc != null">contact_phone_enc = #{contactPhoneEnc},</if>
      <if test="contactEmailEnc != null">contact_email_enc = #{contactEmailEnc},</if>
      address = #{address}, status = #{status}
    WHERE id = #{id}
  </update>

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

</mapper>
