<?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.ruoyi.oa.mapper.OaAttendanceRecordMapper">

    <resultMap id="OaAttendanceRecordResult"
               type="com.ruoyi.oa.domain.vo.OaAttendanceRecordVo">
        <!-- ① 主键 -->
        <id property="recordId" column="record_id"/>
        <!-- ② 其他主字段 -->
        <result property="userId" column="user_id"/>
        <result property="relationMonth" column="relation_month"/>
        <result property="calcTime" column="calc_time"/>
        <result property="nickName" column="nick_name"/>
        <result property="trips" column="trips"/>
        <result property="notNum" column="not_num"/>
        <result property="works" column="works"/>
        <result property="projectIds" column="project_ids"/>
        <result property="overNum" column="over_num"/>
        <result property="laborCost" column="labor_cost"/>
        <result property="remark" column="remark"/>

        <!-- ③ ▶︎ 项目维度汇总列表 -->
        <collection property="projectList"
                    ofType="com.ruoyi.oa.domain.vo.ProjectAttendanceSummaryVo"
                    javaType="list">
            <result property="projectId" column="project_id"/>
            <result property="projectName" column="project_name"/>
            <result property="color" column="color"/>
            <result property="workTimes" column="work_times"/>
            <result property="hourWorkTimes" column="hour_work_times"/>
            <result property="overTime" column="over_time"/>
            <result property="tripDays" column="trip_days"/>
        </collection>
    </resultMap>

    <!-- ========= 项目维度汇总查询 ========= -->
    <select id="selectVoByIdPlus"
            parameterType="Long"
            resultMap="OaAttendanceRecordResult">

        SELECT r.record_id,
               r.user_id,
               r.relation_month,
               r.calc_time,
               r.nick_name,
               u.labor_cost,
               r.trips,
               r.not_num,
               r.works,
               r.project_ids,
               r.over_num,
               r.remark,

               p.project_id,
               p.project_name,
               p.color,

               IFNULL(m.work_times, 0)      AS work_times,
               IFNULL(m.hour_work_times, 0) AS hour_work_times,
               IFNULL(m.over_time, 0)       AS over_time,
               IFNULL(m.trip_days, 0)       AS trip_days

        FROM oa_attendance_record r

                 LEFT JOIN sys_user u
                           ON u.user_id = r.user_id

                 LEFT JOIN sys_oa_project p
                           ON FIND_IN_SET(p.project_id, r.project_ids)

                 LEFT JOIN (SELECT user_id,
                                   project_id,
                                   DATE_FORMAT(create_time, '%Y-%m')                               AS relation_month,

                                   COUNT(CASE WHEN project_id != 0 and project_id != 1 THEN 1 END) AS work_times,

                                   SUM(CASE
                                           WHEN project_id != 0
                                               THEN IFNULL(hour, 0) + day_length * 8
                                           ELSE 0 END)                                             AS hour_work_times,

                                   SUM(CASE
                                           WHEN IFNULL(hour, 0) > 0
                                               THEN (IFNULL(hour, 0)) - 8
                                           ELSE 0 END)                                             AS over_time,

                                   SUM(CASE
                                           WHEN project_id = 1
                                               THEN day_length
                                           ELSE 0 END)                                             AS trip_days
                            FROM sys_oa_attendance
                            WHERE del_flag = 0
                            GROUP BY user_id, project_id, relation_month) m
                           ON m.user_id = r.user_id
                               AND m.project_id = p.project_id
                               AND m.relation_month = DATE_FORMAT(r.relation_month, '%Y-%m')

        WHERE r.del_flag = 0
          AND r.record_id = #{recordId}
    </select>

    <select id="listGenDate" resultType="java.lang.String">
        select distinct calc_time
        from oa_attendance_record
        where YEAR(relation_month) = YEAR(#{date})
          and MONTH(relation_month) = month(#{date})
          and del_flag = 0
    </select>

    <select id="listCommonDateRecord" resultType="Long">
        select record_id
        from oa_attendance_record
        where YEAR(calc_time) = YEAR(#{date})
          and MONTH(calc_time) = month(#{date})
          and DAY(calc_time) = DAY(#{date})
          and YEAR(relation_month) = YEAR(#{firstDay})
          and MONTH(relation_month) = month(#{firstDay})
          and del_flag = 0
    </select>


    <!-- 查询每个用户的出勤记录，包括合并好的 project_ids -->
    <select id="getAttendance" resultType="com.ruoyi.oa.domain.ProjectAttendance">
        SELECT
        oar.user_id,
        oar.nick_name,
        oar.relation_month,
        oar.project_ids
        FROM
        oa_attendance_record oar
        WHERE
        oar.user_id IN
        <foreach item="userId" collection="userIds" open="(" separator="," close=")">
            #{userId}
        </foreach>
        AND oar.del_flag = '0'
        AND YEAR(oar.relation_month) = YEAR(#{relationMonth})
        AND MONTH(oar.relation_month) = MONTH(#{relationMonth})
    </select>

    <!-- 根据 project_id 获取项目名称 -->
    <select id="getProjectById" resultType="com.ruoyi.oa.domain.vo.SysOaProjectVo">
        SELECT project_name
        FROM sys_oa_project
        WHERE project_id = #{projectId}
    </select>

    <!-- 根据 userId 和 project_id 获取出勤天数 -->
    <select id="getWorkDays" resultType="java.lang.Long">
        SELECT COALESCE(SUM(CASE
                                WHEN (oas.day_length > 0 OR oas.hour > 0)
                                    AND (oas.project_id != 1 OR oas.project_id = 0)
                                    THEN 1
                                ELSE 0 END), 0) AS work_days
        FROM sys_oa_attendance oas
        WHERE oas.user_id = #{userId}
          AND FIND_IN_SET(oas.project_id, #{projectIds}) > 0
          AND oas.del_flag = '0'
          AND oas.create_time BETWEEN
            DATE_FORMAT(#{relationMonth}, '%Y-%m-01')
            AND IF(#{calcTime} IS NOT NULL, #{calcTime}, NOW())
    </select>

    <select id="selectProjectIds" resultType="java.lang.String">
        SELECT
        oar.project_ids
        FROM
        oa_attendance_record oar
        WHERE
        oar.user_id IN
        <foreach item="userId" collection="userIds" open="(" separator="," close=")">
            #{userId}
        </foreach>
        AND oar.del_flag = '0'
        AND YEAR(oar.relation_month) = YEAR(#{relationMonth})
        AND MONTH(oar.relation_month) = MONTH(#{relationMonth})
        AND (
        -- 如果 calcTime 不为空，查询 calcTime 对应的记录
        (#{calcTime} IS NOT NULL AND oar.calc_time = #{calcTime})
        OR
        -- 如果 calcTime 为空，查询该用户在该月的最新 calc_time
        (#{calcTime} IS NULL AND oar.calc_time =
        (SELECT MAX(oar2.calc_time)
        FROM oa_attendance_record oar2
        WHERE oar2.user_id = oar.user_id
        AND YEAR(oar2.calc_time) = YEAR(#{relationMonth})
        AND MONTH(oar2.calc_time) = MONTH(#{relationMonth}))
        )
        )
    </select>

</mapper>
