<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.elephant.framework.galaxy.aroad.module.attendance.mapper.AttendanceMapper">

  <!--<resultMap id="attendanceMap" type="com.elephant.framework.galaxy.aroad.module.attendance.entity.Attendance">-->
        <!--<id property="attendanceId" column="attendance_id"/>-->
        <!--<result property="shiftId" column="shift_id"/>-->
        <!--<result property="unitId" column="unit_id"/>-->
        <!--<result property="time" column="time"/>-->
  <!--</resultMap>-->

  <resultMap id="attendanceDtoMap" type="com.elephant.framework.galaxy.aroad.module.attendance.dto.AttendanceDto">
      <result property="attendanceId" column="attendance_id"/>
      <result property="shiftId" column="shift_id"/>
      <result property="unitId" column="unit_id"/>
      <result property="time" column="time"/>
      <result property="shiftName" column="shift_name"/>
      <result property="count" column="count"/>
  </resultMap>

  <select id="getAttendance" resultMap="attendanceDtoMap">
      SELECT
        a.attendance_id,a.unit_id,a.time,t.shift_id,t.shift_name,COUNT(m.id) as count
      FROM attendance a
      INNER JOIN attendance_templates  t
      ON a.shift_id = t.shift_id
      INNER JOIN attendance_members m
      ON a.attendance_id = m.attendance_id
      WHERE a.unit_id = #{unitId}
      GROUP BY a.attendance_id,
	    a.unit_id,
	    a.TIME,
	    t.shift_id,
	    t.shift_name
  </select>

    <insert id="saveAttendance">
        <selectKey order="AFTER" keyProperty="attendanceId" resultType="int">
            SELECT currval('attendance_attendance_id_seq')
        </selectKey>
      insert into
        attendance(attendance_id, unit_id,shift_id,time)
      values
        (nextVal('attendance_attendance_id_seq'), #{unitId},#{shiftId},#{time})
    </insert>

    <select id="getAttendanceId" resultType="java.lang.Integer">
       select
          attendance_id
       from
          attendance
       where
          unit_id =  #{unitId}
       and
          shift_id = #{shiftId}
       and
          time = #{time}
    </select>
</mapper>
