<?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="org.springblade.modules.sqmy.mapper.JmhInfoMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="jmhInfoResultMap" type="org.springblade.modules.sqmy.pojo.entity.JmhInfoEntity">
        <result column="hyzt" property="hyzt"/>
        <result column="hynr" property="hynr"/>
        <result column="fj" property="fj"/>
        <result column="sssq_bm" property="sssqBm"/>
    </resultMap>

    <select id="selectJmhInfoPage" resultType="org.springblade.modules.sqmy.pojo.vo.JmhInfoVO">
        SELECT
            ji.id,
            ji.hyzt,
            ji.hynr,
            ji.create_time,
            sq.dept_name AS sssqName,
            STRING_AGG ( ry.zw || '  ' || ry.xm, ', ' ) AS names
        FROM
            sqmy.jmh_info ji
        LEFT JOIN jdrh.blade_dept sq ON sq.id = ji.sssq_bm
        LEFT JOIN sqmy.jmh_ry ry ON ry.jmh_id = ji.id AND ry.is_deleted = 0
        WHERE
            ji.is_deleted = 0
          AND (#{params.deptId} LIKE '%' || sq.id || '%' OR sq.ancestors LIKE '%' || #{params.deptId} || '%')
        GROUP BY
            ji.id,
            ji.hyzt,
            ji.hynr,
            ji.create_time,
            sq.dept_name
        ORDER BY ji.create_time DESC
    </select>

    <select id="exportJmhInfo" resultType="org.springblade.modules.sqmy.excel.JmhInfoExcel">
        SELECT * FROM jmh_info ${ew.customSqlSegment}
    </select>

    <select id="getBzJmh" resultType="org.springblade.modules.sqmy.pojo.entity.JmhInfoEntity">
        SELECT
            ji.*
        FROM
            sqmy.jmh_info ji
        LEFT JOIN jdrh.blade_dept sq ON sq.id = ji.sssq_bm
        WHERE
            ji.is_deleted = 0
          AND (#{params.deptId} LIKE '%' || sq.id || '%' OR sq.ancestors LIKE '%' || #{params.deptId} || '%')
          AND ji.create_time BETWEEN (CURRENT_DATE - EXTRACT(DOW FROM CURRENT_DATE)::INT + (CASE WHEN EXTRACT(DOW FROM CURRENT_DATE) = 0 THEN 7 ELSE 1 END)) AND (CURRENT_DATE - EXTRACT(DOW FROM CURRENT_DATE)::INT + (CASE WHEN EXTRACT(DOW FROM CURRENT_DATE) = 0 THEN 7 ELSE 1 END) + INTERVAL '7 days')
        ORDER BY ji.create_time DESC
        LIMIT 1
    </select>

    <select id="detailById" resultType="org.springblade.modules.sqmy.pojo.vo.JmhInfoVO">
        SELECT
            ji.*,
            sq.dept_name AS sssqName
        FROM
            sqmy.jmh_info ji
            LEFT JOIN jdrh.blade_dept sq ON sq.id = ji.sssq_bm
        WHERE
            ji.id = #{id}
    </select>
</mapper>
