<?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.yfd.platform.modules.experimentalData.mapper.TsFilesMapper">

    <!-- 批量插入试验任务文件表（存在唯一键冲突时忽略） -->
    <insert id="batchInsertTsFiles">
        INSERT INTO ts_files
        (id,node_id, task_id, is_file, parent_id, file_name, file_size, work_path,upload_time,uploader)
        VALUES
        <foreach collection="list" item="item" separator=",">
            (#{item.id},#{item.nodeId}, #{item.taskId}, #{item.isFile}, #{item.parentId},
            #{item.fileName}, #{item.fileSize}, #{item.workPath}, #{item.uploadTime},#{item.uploader})
        </foreach>
    </insert>

    <update id="updateParentIdByPathHierarchy">
        UPDATE ts_files a
            LEFT JOIN ts_files b
        ON b.task_id = a.task_id
            AND b.node_id = a.node_id
            AND a.work_path = CONCAT( b.work_path, b.file_name, '/' )
            SET a.parent_id = b.id
        WHERE
            b.task_id = #{taskId}
          AND b.node_id = #{nodeId}
    </update>

    <select id="countFiles" resultType="java.lang.Integer">
        WITH RECURSIVE node_tree AS (SELECT node_id
                                     FROM ts_nodes
                                     WHERE node_id = #{id}

                                     UNION ALL

                                     SELECT n.node_id
                                     FROM ts_nodes n
                                              INNER JOIN node_tree t ON n.parent_id = t.node_id)
        SELECT count(*)
        FROM ts_files
        WHERE node_id IN (SELECT node_id FROM node_tree)
          AND backup_path IS NOT NULL
    </select>

</mapper>
