<?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.zt.plat.module.qms.resource.record.dal.mapper.RecordRecordMapper">
    <resultMap id="recordRecordResultMap"
               type="com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO">
        <!-- 主键 -->
    </resultMap>

    <sql id="recordRecordColumns">
        trr.ID
        , trr.CTGR_ID AS categoryId, trr.CD AS code, trr.BSN_TP AS businessType,
        trr.FORM_KY AS formKey, trr.NAME, trr.VER AS version,
        trr.CRNT_FLG AS currentFlag,
        trr.MKE_DT AS makeDate,
        trr.CNF_FLG AS confidentialFlag,
        trr.CNF_LVL AS confidentialLevel,
        trr.CNF_WY AS confidentialWay,
        trr.CNF_KY AS confidentialKey,
        trr.PMNT AS permanently,
        trr.SBM_FLG AS submitFlag,
        trr.RCD_STS AS recordStatus,
        trr.EXPR_DT AS expirationDate,
        trr.EFCT_DT AS effectiveDate,
        trr.EXPR_STS AS expirationStatus,
        trr.CNL_FLG AS cancelFlag,
        trr.FORM_DAT AS formData,
        trr.DAT_COLT_ID AS dataCollectionId,
        trr.SRC_URL AS sourceUrl,
        trr.SYS_DEPT_CD AS systemDepartmentCode,
        trr.RMK AS remark,
        trr.COLT_FLG AS collectionFlag,
        trr.MAIN_ID AS mainId,
        trr.OPTN_FLG AS operationFlag,
        trr.CREATE_TIME AS createTime,
        trr.TENANT_ID,
        trr.APL_STS AS applyStatus
    </sql>

    <!--
        多表关联分页查询：以 t_rcd_rcd 为主表，保证行数 1:1。
        通过标量子查询获取 businessType='文件提交' 的申请信息，
        即使同一 recordRecord 有多条 recordApplyDetail，也只取一条（ROWNUM = 1），不产生重复行。
        注意：使用达梦（DM）数据库兼容语法，不支持 LIMIT，改用 AND ROWNUM = 1。
    -->
    <select id="selectRecordWithApplyPage"
            resultType="com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO">
        SELECT
        <include refid="recordRecordColumns"/>,
        apply_info.ID AS applyId,
        apply_info.FLW_INSC_ID AS flowInstanceId,
        apply_info.BSN_STS AS applyBusinessStatus
        FROM t_rcd_rcd trr
        LEFT JOIN (
        SELECT
        trad.DOC_ID,
        tra.ID,
        tra.FLW_INSC_ID,
        tra.BSN_STS,
        -- 使用 DOC_ID 分组，按照规则排序（比如想要最新的申请，就用 CREATE_TIME DESC）
        ROW_NUMBER() OVER (PARTITION BY trad.DOC_ID ORDER BY tra.ID DESC) as rn
        FROM t_rcd_apl_dtl trad
        INNER JOIN t_rcd_apl tra ON trad.APL_ID = tra.ID AND tra.BSN_TP = '文件提交'
        )
        apply_info ON trr.ID = apply_info.DOC_ID AND apply_info.rn = 1

        <where>
            trr.deleted = 0
            <!-- 作废标识 -->
            <if test="reqVO.cancelFlag != null">
                AND trr.CNL_FLG = #{reqVO.cancelFlag}
            </if>
            <!-- 过期标识 -->
            <if test="reqVO.expirationStatus != null">
                AND trr.EXPR_STS = #{reqVO.expirationStatus}
            </if>
            <if test="reqVO.categoryId != null">
                AND trr.CTGR_ID = #{reqVO.categoryId}
            </if>
            <if test="reqVO.code != null and reqVO.code != ''">
                AND trr.CD = #{reqVO.code}
            </if>
            <if test="reqVO.name != null and reqVO.name != ''">
                AND trr.NAME LIKE CONCAT('%', #{reqVO.name}, '%')
            </if>
            <if test="reqVO.version != null and reqVO.version != ''">
                AND trr.VER = #{reqVO.version}
            </if>
            <if test="reqVO.currentFlag != null">
                AND trr.CRNT_FLG = #{reqVO.currentFlag}
            </if>
            <if test="reqVO.makeDate != null and reqVO.makeDate.length > 0">
                AND trr.MKE_DT BETWEEN #{reqVO.makeDate[0]} AND #{reqVO.makeDate[1]}
            </if>
            <if test="reqVO.expirationDate != null and reqVO.expirationDate.length > 0">
                AND trr.EXPR_DT BETWEEN #{reqVO.expirationDate[0]} AND #{reqVO.expirationDate[1]}
            </if>
            <if test="reqVO.mainId != null">
                AND trr.MAIN_ID = #{reqVO.mainId}
            </if>
            <if test="reqVO.createTime != null and reqVO.createTime.length > 0">
                AND trr.CREATE_TIME BETWEEN #{reqVO.createTime[0]} AND #{reqVO.createTime[1]}
            </if>
        </where>
        ORDER BY trr.CREATE_TIME ASC
    </select>

    <!--    获取评审-文件记录-->
    <select id="selectRecordByIdPathLike"
            resultType="com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO">
        SELECT
        <include refid="recordRecordColumns"/>
        FROM T_RCD_RCD trr
        INNER JOIN T_RCD_CTGR trc ON trr.CTGR_ID = trc.ID
        WHERE trr.deleted = 0 and trr.EXPR_STS = 0 and trr.CNL_FLG = 0
        <!-- 查询有效 或者是 即将 生效的：永久有效 或 状态为生效中(1) 或 待生效(3) -->
        and (trr.PMNT = '1' or
             (trr.RCD_STS = 1 or now() > trr.EFCT_DT)
        )

        <!-- 作废标识 -->
        <if test="reqVO.cancelFlag != null">
            AND trr.CNL_FLG = #{reqVO.cancelFlag}
        </if>
        <!-- 过期标识 -->
        <if test="reqVO.expirationStatus != null">
            AND trr.EXPR_STS = #{reqVO.expirationStatus}
        </if>
        <if test="reqVO.categoryId != null">
            AND trr.CTGR_ID = #{reqVO.categoryId}
        </if>
        <if test="reqVO.code != null and reqVO.code != ''">
            AND trr.CD = #{reqVO.code}
        </if>
        <if test="reqVO.name != null and reqVO.name != ''">
            AND trr.NAME LIKE CONCAT('%', #{reqVO.name}, '%')
        </if>
        <if test="reqVO.version != null and reqVO.version != ''">
            AND trr.VER = #{reqVO.version}
        </if>
        <if test="reqVO.currentFlag != null">
            AND trr.CRNT_FLG = #{reqVO.currentFlag}
        </if>

        <!-- 判断列表不为空才拼接条件，防止报 SQL 语法错误 -->
        <if test="pathList != null and pathList.size() > 0">
            AND (
            <foreach collection="pathList" item="path" separator=" OR ">
                trc.ID_PATH LIKE CONCAT('%', #{path}, '%')
            </foreach>
            )
        </if>
    </select>

<!--    查询需要提交，and 有效和将来生效的-->
    <select id="getNotSubmitEffectRecordPage" resultType="com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO">
        SELECT
        <include refid="recordRecordColumns"/>
        FROM t_rcd_rcd trr
        WHERE trr.deleted = 0 and trr.EXPR_STS = 0 and trr.CNL_FLG = 0
        <!-- 已有效  或者 审批通过，待生效的-->
        and (trr.RCD_STS = 1 or (trr.APL_STS = 'completed' and trr.EFCT_DT > now()))
        <if test="categoryIds != null and categoryIds.size() > 0">
            and
            trr.CTGR_ID IN
            <foreach collection="categoryIds" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
        <if test="reqVO.code != null and reqVO.code != ''">
            AND trr.CD = #{reqVO.code}
        </if>
        <if test="reqVO.name != null and reqVO.name != ''">
            AND trr.NAME LIKE CONCAT('%', #{reqVO.name}, '%')
        </if>
        <if test="reqVO.version != null and reqVO.version != ''">
            AND trr.VER = #{reqVO.version}
        </if>
    </select>

<!--    需要提交的（submitFlag == 1）-文件记录分页查询 -->
    <select id="getEffectiveRecordBySubmitFlagPage"
            resultType="com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO">
        SELECT
        <include refid="recordRecordColumns"/>,
        apply_info.ID AS applyId,
        apply_info.FLW_INSC_ID AS flowInstanceId,
        apply_info.BSN_STS AS applyBusinessStatus
        FROM t_rcd_rcd trr
        LEFT JOIN (
        SELECT
        trad.DOC_ID,
        tra.ID,
        tra.FLW_INSC_ID,
        tra.BSN_STS,
        -- 使用 DOC_ID 分组，按照规则排序（比如想要最新的申请，就用 CREATE_TIME DESC）
        ROW_NUMBER() OVER (PARTITION BY trad.DOC_ID ORDER BY tra.ID DESC) as rn
        FROM t_rcd_apl_dtl trad
        INNER JOIN t_rcd_apl tra ON trad.APL_ID = tra.ID AND tra.BSN_TP = '文件提交'
        )
        apply_info ON trr.ID = apply_info.DOC_ID AND apply_info.rn = 1

        <where>
            trr.deleted = 0 and trr.EXPR_STS = 0 and trr.CNL_FLG = 0
            <!-- 查询有效 或者是 即将 生效的：永久有效 或 状态为生效中(1) 或 待生效(3) -->
            AND (
--                 逻辑一：如果查出来的状态是 null
                (apply_info.BSN_STS IS NULL AND
                    (
                    trr.RCD_STS = #{reqVO.recordStatus}
                    <if test="reqVO.permanently !=null and reqVO.permanently != ''">
                        OR trr.PMNT = #{reqVO.permanently}
                    </if>
                    )
                )
                OR 
                -- 逻辑二：如果查出来的状态不是 null（必须等于 completed），并且...
                (apply_info.BSN_STS = 'completed' AND
                    (trr.RCD_STS = #{reqVO.recordStatus}
<!--                    <if test="reqVO.expirationDate != null and reqVO.expirationDate != ''">-->
                        OR trr.EFCT_DT > now())
<!--                    </if>-->
                )
            )

            <!-- 作废标识 -->
            <if test="reqVO.cancelFlag != null">
                AND trr.CNL_FLG = #{reqVO.cancelFlag}
            </if>
            <!-- 过期标识 -->
            <if test="reqVO.expirationStatus != null">
                AND trr.EXPR_STS = #{reqVO.expirationStatus}
            </if>
            <if test="reqVO.categoryId != null">
                AND trr.CTGR_ID = #{reqVO.categoryId}
            </if>
            <if test="reqVO.code != null and reqVO.code != ''">
                AND trr.CD = #{reqVO.code}
            </if>
            <if test="reqVO.name != null and reqVO.name != ''">
                AND trr.NAME LIKE CONCAT('%', #{reqVO.name}, '%')
            </if>
            <if test="reqVO.version != null and reqVO.version != ''">
                AND trr.VER = #{reqVO.version}
            </if>
            <if test="reqVO.currentFlag != null">
                AND trr.CRNT_FLG = #{reqVO.currentFlag}
            </if>
            <if test="reqVO.makeDate != null and reqVO.makeDate.length > 0">
                AND trr.MKE_DT BETWEEN #{reqVO.makeDate[0]} AND #{reqVO.makeDate[1]}
            </if>
            <if test="reqVO.expirationDate != null and reqVO.expirationDate.length > 0">
                AND trr.EXPR_DT BETWEEN #{reqVO.expirationDate[0]} AND #{reqVO.expirationDate[1]}
            </if>
            <if test="reqVO.mainId != null">
                AND trr.MAIN_ID = #{reqVO.mainId}
            </if>
            <if test="reqVO.createTime != null and reqVO.createTime.length > 0">
                AND trr.CREATE_TIME BETWEEN #{reqVO.createTime[0]} AND #{reqVO.createTime[1]}
            </if>
        </where>
        ORDER BY trr.CREATE_TIME ASC
    </select>

<!--    查询不需要提交，and 有效和将来生效的-->
    <select id="getSubmitEffectRecordPage"
            resultType="com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO">
        SELECT
        <include refid="recordRecordColumns"/>
        FROM t_rcd_rcd trr
        WHERE
        trr.deleted = 0 and trr.EXPR_STS = 0 and trr.CNL_FLG = 0
        <!-- 长期有效  或者 没有过期的-->
        and (trr.PMNT = '1' or
        trr.EXPR_DT > now()
        )

        <if test="categoryIds != null and categoryIds.size() > 0">
            and
            trr.CTGR_ID IN
            <foreach collection="categoryIds" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
        <if test="reqVO.code != null and reqVO.code != ''">
            AND trr.CD = #{reqVO.code}
        </if>
        <if test="reqVO.name != null and reqVO.name != ''">
            AND trr.NAME LIKE CONCAT('%', #{reqVO.name}, '%')
        </if>
        <if test="reqVO.version != null and reqVO.version != ''">
            AND trr.VER = #{reqVO.version}
        </if>
        ORDER BY trr.CREATE_TIME ASC
    </select>
</mapper>