<?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.hzs.system.sys.mapper.SysApprovalItemMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.hzs.common.domain.system.sys.SysApprovalItem">
        <result column="PK_APPROVAL" property="pkApproval"/>
        <result column="APPROVAL_LEVEL" property="approvalLevel"/>
        <result column="PK_USER" property="pkUser"/>
    </resultMap>

    <!-- 批量插入数据 -->
    <insert id="insertBatch">
        INSERT ALL
        <foreach collection="list" item="item" separator=" ">
            into SYS_APPROVAL_ITEM (PK_APPROVAL, APPROVAL_LEVEL, PK_USER)
            values (#{item.pkApproval}, #{item.approvalLevel}, #{item.pkUser})
        </foreach>
        SELECT 1 FROM dual
    </insert>

    <!-- 根据审批查询列表 -->
    <select id="queryListByApproval" resultType="com.hzs.common.domain.system.sys.ext.SysApprovalItemExt">
        select sai.*, su.nick_name, su.user_name, sd.dept_name
        from SYS_APPROVAL_ITEM sai
                 left join sys_user su
                           on su.user_id = sai.pk_user
                 left join sys_dept sd
                           on sd.dept_id = su.pk_dept
        where sai.pk_approval = #{pkApproval}
        order by sai.approval_level
    </select>

    <!-- 非当前用户指定部门是否存在审批 -->
    <select id="itemExistByUserAndDept" resultType="Integer">
        select count(pk_approval)
        from (
                 select sai.pk_approval
                 from SYS_APPROVAL sa
                          left join SYS_APPROVAL_ITEM sai
                                    on sai.pk_approval = sa.pk_id
                          inner join SYS_USER su
                                     on su.user_id = sai.pk_user
                 where sa.del_flag = 0
                   and (sai.pk_user = #{userId} or su.pk_dept = #{deptId})
                 group by sai.pk_approval
                 having count(sai.pk_approval) > 1
             ) t
    </select>

</mapper>
