<?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.swzdr.mapper.RyLhspMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="ryLhspResultMap" type="org.springblade.swzdr.pojo.entity.RyLhspEntity">
        <result column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="spjg" property="spjg"/>
        <result column="jjyy" property="jjyy"/>
        <result column="create_user" property="createUser"/>
        <result column="create_dept" property="createDept"/>
        <result column="create_time" property="createTime"/>
        <result column="update_user" property="updateUser"/>
        <result column="update_time" property="updateTime"/>
        <result column="status" property="status"/>
        <result column="is_deleted" property="isDeleted"/>
    </resultMap>

    <select id="selectRyLhspPage" resultType="org.springblade.swzdr.pojo.vo.RyLhspVO">
        SELECT
            sp.ID,
            sp.user_id,
            sp.spjg,
            ry.xm,
            ry.xb,
            ry.gmsfhm,
            ry.mz,
            string_agg ( dh.lxdh, ',' ) AS lxdh,
            ry.hjdxz,
            ry.jzdxz,
            pcs.dept_name AS pcsName
        FROM
            swzdr_ry_lhsp sp
        LEFT JOIN swzdr_ry_info ry ON ry.ID = sp.user_id
        LEFT JOIN blade_dept pcs ON ry.pcs_id = pcs.id
        LEFT JOIN swzdr_ry_lxdh dh ON dh.user_id = ry.id
        WHERE
            sp.is_deleted = 0
          AND sp.spjg != 1
          AND ( pcs.id = #{params.deptId} :: int8 OR ry.wkdw = #{params.deptId} :: int8 OR ry.mj_id = #{params.userId} :: int8)
        <if test="null != params.spjg">
            AND sp.spjg = #{params.spjg} :: int
        </if>
        <if test="null != params.gmsfhm and '' != params.gmsfhm">
          AND ry.gmsfhm LIKE '%' ||  #{params.gmsfhm} || '%'
        </if>
        <if test="null != params.xm and '' != params.xm">
          AND ry.xm LIKE '%' ||  #{params.xm} || '%'
        </if>
        <if test="null != params.lxdh and '' != params.lxdh">
            AND EXISTS (
            SELECT 1 FROM swzdr_ry_lxdh dh_inner
            WHERE dh_inner.user_id = ry.ID AND dh_inner.lxdh ILIKE '%' || #{params.lxdh} || '%'
            )
        </if>
        GROUP BY
            sp.ID,
            sp.user_id,
            ry.xm,
            ry.xb,
            ry.gmsfhm,
            ry.mz,
            ry.hjdxz,
            ry.jzdxz,
            pcs.dept_name
    </select>

    <select id="exportRyLhsp" resultType="org.springblade.swzdr.excel.RyLhspExcel">
        SELECT * FROM swzdr_ry_lhsp ${ew.customSqlSegment}
    </select>

</mapper>
