<?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.sundot.airport.system.mapper.portrait.WorkExperienceIndicatorMapper">

    <resultMap type="com.sundot.airport.system.domain.portrait.WorkExperienceStats" id="WorkExperienceStatsResult">
        <result property="averageWorkYears" column="average_work_years"/>
        <result property="totalCount" column="total_count"/>
    </resultMap>

    <sql id="userIdsCondition">
        <foreach collection="userIds" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </sql>

    <!-- 查询个人工作年限 -->
    <select id="queryPersonalWorkYears" resultType="java.lang.Integer">
        SELECT CASE
                   WHEN start_working_date IS NOT NULL THEN TIMESTAMPDIFF(YEAR, start_working_date, CURDATE())
                   ELSE NULL
                   END AS work_years
        FROM sys_user
        WHERE user_id = #{userId}
          AND del_flag = '0'
    </select>

    <!-- 查询组织平均工作年限 -->
    <select id="queryOrgWorkYearsStats" resultMap="WorkExperienceStatsResult">
        SELECT
        CASE
        WHEN COUNT(*) > 0 THEN ROUND(SUM(
        CASE
        WHEN start_working_date IS NOT NULL THEN TIMESTAMPDIFF(YEAR, start_working_date, CURDATE())
        ELSE 0
        END
        ) / COUNT(*), 2)
        ELSE 0
        END AS average_work_years,
        COUNT(*) AS total_count
        FROM sys_user
        WHERE del_flag = '0'
        AND status = '0'
        and user_id in
        <include refid="userIdsCondition"/>
    </select>

    <!-- 查询个人安检工作年限 -->
    <select id="queryPersonalSecurityWorkYears" resultType="java.lang.Integer">
        SELECT CASE
                   WHEN security_check_start_date IS NOT NULL
                       THEN TIMESTAMPDIFF(YEAR, security_check_start_date, CURDATE())
                   ELSE NULL
                   END AS security_work_years
        FROM sys_user
        WHERE user_id = #{userId}
          AND del_flag = '0'
    </select>

    <!-- 查询组织平均安检工作年限 -->
    <select id="queryOrgSecurityWorkYearsStats" resultMap="WorkExperienceStatsResult">
        SELECT
        CASE
        WHEN COUNT(*) > 0 THEN ROUND(SUM(
        CASE
        WHEN security_check_start_date IS NOT NULL THEN TIMESTAMPDIFF(YEAR, security_check_start_date, CURDATE())
        ELSE 0
        END
        ) / COUNT(*), 2)
        ELSE 0
        END AS average_work_years,
        COUNT(*) AS total_count
        FROM sys_user
        WHERE del_flag = '0'
        AND status = '0'
        and user_id in
        <include refid="userIdsCondition"/>
    </select>

</mapper>