<?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.xyzh.crontab.mapper.CrontabTaskMapper">

    <!-- 结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.crontab.TbCrontabTask">
        <id column="id" property="ID" />
        <result column="task_id" property="taskId" />
        <result column="task_name" property="taskName" />
        <result column="task_group" property="taskGroup" />
        <result column="bean_name" property="beanName" />
        <result column="method_name" property="methodName" />
        <result column="method_params" property="methodParams" />
        <result column="meta_id" property="metaId" />
        <result column="default_recipient" property="defaultRecipient" />
        <result column="cron_expression" property="cronExpression" />
        <result column="status" property="status" />
        <result column="description" property="description" />
        <result column="concurrent" property="concurrent" />
        <result column="misfire_policy" property="misfirePolicy" />
        <result column="creator" property="creator" />
        <result column="updater" property="updater" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
        <result column="delete_time" property="deleteTime" />
        <result column="deleted" property="deleted" />
        <result column="meta_name" property="metaName" />
        <result column="meta_description" property="metaDescription" />
    </resultMap>

    <!-- 字段列表 -->
    <sql id="Base_Column_List">
        id, task_id, task_name, task_group, bean_name, method_name, method_params, meta_id, default_recipient, 
        cron_expression, status, description, concurrent, misfire_policy, 
        creator, updater, create_time, update_time, delete_time, deleted
    </sql>

    <!-- 查询条件 -->
    <sql id="Base_Where_Clause">
        <where>
            deleted = 0
            <if test="taskId != null and taskId != ''">
                AND task_id = #{taskId}
            </if>
            <if test="taskName != null and taskName != ''">
                AND task_name LIKE CONCAT('%', #{taskName}, '%')
            </if>
            <if test="taskGroup != null and taskGroup != ''">
                AND task_group = #{taskGroup}
            </if>
            <if test="beanName != null and beanName != ''">
                AND bean_name = #{beanName}
            </if>
            <if test="methodName != null and methodName != ''">
                AND method_name = #{methodName}
            </if>
            <if test="status != null">
                AND status = #{status}
            </if>
            <if test="deleted != null">
                AND deleted = #{deleted}
            </if>
        </where>
    </sql>

    <sql id="Filter_Where_Clause">
        <where>
            <if test="filter != null">
                <if test="filter.ID != null and filter.ID != ''">
                    AND id = #{filter.ID}
                </if>
                <if test="filter.taskId != null and filter.taskId != ''">
                    AND task_id = #{filter.taskId}
                </if>
                <if test="filter.taskName != null and filter.taskName != ''">
                    AND task_name LIKE CONCAT('%', #{filter.taskName}, '%')
                </if>
                <if test="filter.taskGroup != null and filter.taskGroup != ''">
                    AND task_group = #{filter.taskGroup}
                </if>
                <if test="filter.beanName != null and filter.beanName != ''">
                    AND bean_name = #{filter.beanName}
                </if>
                <if test="filter.methodName != null and filter.methodName != ''">
                    AND method_name = #{filter.methodName}
                </if>
                <if test="filter.status != null">
                    AND status = #{filter.status}
                </if>
                <if test="filter.deleted != null">
                    AND deleted = #{filter.deleted}
                </if>
            </if>
        </where>
    </sql>

    <!-- 权限过滤条件（基于dept_path的高效继承） -->
    <sql id="Permission_Filter">
        INNER JOIN tb_resource_permission rp ON ct.task_id = rp.resource_id 
            AND rp.resource_type = 7 
            AND rp.deleted = 0
            AND rp.can_read = 1
            AND (
                -- 全局权限：所有用户可访问
                (rp.dept_id IS NULL AND rp.role_id IS NULL)
                <if test="userDeptRoles != null and userDeptRoles.size() > 0">
                    OR EXISTS (
                        SELECT 1 
                        FROM (
                            <foreach collection="userDeptRoles" item="udr" separator=" UNION ALL ">
                                SELECT #{udr.deptID} AS dept_id, #{udr.deptPath} AS dept_path, #{udr.roleID} AS role_id
                            </foreach>
                        ) user_roles
                        LEFT JOIN tb_sys_dept perm_dept ON perm_dept.dept_id = rp.dept_id AND perm_dept.deleted = 0
                        WHERE 
                           -- 部门级权限：当前部门或父部门（通过dept_path判断继承关系）
                           (rp.role_id IS NULL AND rp.dept_id IS NOT NULL 
                               AND user_roles.dept_path LIKE CONCAT(perm_dept.dept_path, '%'))
                           -- 角色级权限：跨部门的角色权限
                           OR (rp.dept_id IS NULL AND rp.role_id = user_roles.role_id)
                           -- 精确权限：特定部门的特定角色
                           OR (rp.dept_id = user_roles.dept_id AND rp.role_id = user_roles.role_id)
                    )
                </if>
            )
    </sql>

    <!-- 插入任务 -->
    <insert id="insertTask">
        INSERT INTO tb_crontab_task
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="task.ID != null">id,</if>
            <if test="task.taskId != null">task_id,</if>
            <if test="task.taskName != null">task_name,</if>
            <if test="task.taskGroup != null">task_group,</if>
            <if test="task.beanName != null">bean_name,</if>
            <if test="task.methodName != null">method_name,</if>
            <if test="task.methodParams != null">method_params,</if>
            <if test="task.metaId != null">meta_id,</if>
            <if test="task.defaultRecipient != null">default_recipient,</if>
            <if test="task.cronExpression != null">cron_expression,</if>
            <if test="task.status != null">status,</if>
            <if test="task.description != null">description,</if>
            <if test="task.concurrent != null">concurrent,</if>
            <if test="task.misfirePolicy != null">misfire_policy,</if>
            <if test="task.creator != null">creator,</if>
            <if test="task.createTime != null">create_time,</if>
            deleted
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="task.ID != null">#{task.ID},</if>
            <if test="task.taskId != null">#{task.taskId},</if>
            <if test="task.taskName != null">#{task.taskName},</if>
            <if test="task.taskGroup != null">#{task.taskGroup},</if>
            <if test="task.beanName != null">#{task.beanName},</if>
            <if test="task.methodName != null">#{task.methodName},</if>
            <if test="task.methodParams != null">#{task.methodParams},</if>
            <if test="task.metaId != null">#{task.metaId},</if>
            <if test="task.defaultRecipient != null">#{task.defaultRecipient},</if>
            <if test="task.cronExpression != null">#{task.cronExpression},</if>
            <if test="task.status != null">#{task.status},</if>
            <if test="task.description != null">#{task.description},</if>
            <if test="task.concurrent != null">#{task.concurrent},</if>
            <if test="task.misfirePolicy != null">#{task.misfirePolicy},</if>
            <if test="task.creator != null">#{task.creator},</if>
            <if test="task.createTime != null">#{task.createTime},</if>
            0
        </trim>
    </insert>

    <!-- 更新任务 -->
    <update id="updateTask">
        UPDATE tb_crontab_task
        <set>
            <if test="task.taskName != null">task_name = #{task.taskName},</if>
            <if test="task.taskGroup != null">task_group = #{task.taskGroup},</if>
            <if test="task.beanName != null">bean_name = #{task.beanName},</if>
            <if test="task.methodName != null">method_name = #{task.methodName},</if>
            <if test="task.methodParams != null">method_params = #{task.methodParams},</if>
            <if test="task.metaId != null">meta_id = #{task.metaId},</if>
            <if test="task.defaultRecipient != null">default_recipient = #{task.defaultRecipient},</if>
            <if test="task.cronExpression != null">cron_expression = #{task.cronExpression},</if>
            <if test="task.status != null">status = #{task.status},</if>
            <if test="task.description != null">description = #{task.description},</if>
            <if test="task.concurrent != null">concurrent = #{task.concurrent},</if>
            <if test="task.misfirePolicy != null">misfire_policy = #{task.misfirePolicy},</if>
            <if test="task.updater != null">updater = #{task.updater},</if>
            update_time = NOW()
        </set>
        WHERE id = #{task.ID} AND deleted = 0
    </update>

    <!-- 删除任务（逻辑删除） -->
    <update id="deleteTask">
        UPDATE tb_crontab_task 
        SET deleted = 1,
            delete_time = NOW()
        WHERE task_id=#{taskId} AND deleted = 0
    </update>

    <!-- 根据ID查询任务 -->
    <select id="selectTaskById" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_crontab_task
        WHERE task_id=#{taskId} AND deleted = 0
    </select>

    <!-- 根据过滤条件查询任务列表 -->
    <select id="selectTaskList" resultMap="BaseResultMap">
        SELECT DISTINCT ct.*
        FROM tb_crontab_task ct
        <include refid="Permission_Filter" />
        WHERE ct.deleted = 0
            <if test="filter != null">
                <if test="filter.ID != null and filter.ID != ''">
                    AND ct.id = #{filter.ID}
                </if>
                <if test="filter.taskId != null and filter.taskId != ''">
                    AND ct.task_id = #{filter.taskId}
                </if>
                <if test="filter.taskName != null and filter.taskName != ''">
                    AND ct.task_name LIKE CONCAT('%', #{filter.taskName}, '%')
                </if>
                <if test="filter.taskGroup != null and filter.taskGroup != ''">
                    AND ct.task_group = #{filter.taskGroup}
                </if>
                <if test="filter.status != null">
                    AND ct.status = #{filter.status}
                </if>
            </if>
        ORDER BY ct.create_time DESC
    </select>

    <!-- 分页查询任务列表 -->
    <select id="selectTaskPage" resultMap="BaseResultMap">
        SELECT DISTINCT
            ct.id,
            ct.task_id,
            ct.task_name,
            ct.task_group,
            ct.bean_name,
            ct.method_name,
            ct.method_params,
            ct.meta_id,
            ct.default_recipient,
            ct.cron_expression,
            ct.status,
            ct.description,
            ct.concurrent,
            ct.misfire_policy,
            ct.creator,
            ct.updater,
            ct.create_time,
            ct.update_time,
            ct.delete_time,
            ct.deleted,
            m.name        AS meta_name,
            m.description AS meta_description
        FROM tb_crontab_task ct
        <include refid="Permission_Filter" />
        LEFT JOIN tb_crontab_task_meta m
            ON ct.meta_id = m.meta_id AND m.deleted = 0
        WHERE ct.deleted = 0
            <if test="filter != null">
                <if test="filter.ID != null and filter.ID != ''">
                    AND ct.id = #{filter.ID}
                </if>
                <if test="filter.taskId != null and filter.taskId != ''">
                    AND ct.task_id = #{filter.taskId}
                </if>
                <if test="filter.taskName != null and filter.taskName != ''">
                    AND ct.task_name LIKE CONCAT('%', #{filter.taskName}, '%')
                </if>
                <if test="filter.taskGroup != null and filter.taskGroup != ''">
                    AND ct.task_group = #{filter.taskGroup}
                </if>
                <if test="filter.status != null">
                    AND ct.status = #{filter.status}
                </if>
            </if>
        ORDER BY ct.create_time DESC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 查询所有运行中的任务（包含权限过滤） -->
    <select id="selectRunningTasks" resultMap="BaseResultMap">
        SELECT DISTINCT ct.*
        FROM tb_crontab_task ct
        <include refid="Permission_Filter" />
        WHERE ct.status = 1 AND ct.deleted = 0
        ORDER BY ct.create_time DESC
    </select>

    <!-- 查询所有运行中的任务（系统级，不含权限过滤，用于系统初始化） -->
    <select id="selectAllRunningTasks" resultMap="BaseResultMap">
        SELECT *
        FROM tb_crontab_task
        WHERE status = 1 AND deleted = 0
        ORDER BY create_time DESC
    </select>

    <!-- 更新任务状态 -->
    <update id="updateTaskStatus">
        UPDATE tb_crontab_task
        SET status = #{status},
            update_time = NOW()
        WHERE task_id=#{taskId} AND deleted = 0
    </update>

    <!-- 根据Bean名称和方法名称查询任务 -->
    <select id="selectTaskByBeanAndMethod" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_crontab_task
        WHERE bean_name = #{beanName} 
        AND method_name = #{methodName} 
        AND deleted = 0
        LIMIT 1
    </select>

    <!-- countSelectTask --> 
    <select id="countSelectTask" resultType="int">
        SELECT COUNT(DISTINCT ct.id)
        FROM tb_crontab_task ct
        <include refid="Permission_Filter" />
        WHERE ct.deleted = 0
            <if test="filter != null">
                <if test="filter.ID != null and filter.ID != ''">
                    AND ct.id = #{filter.ID}
                </if>
                <if test="filter.taskId != null and filter.taskId != ''">
                    AND ct.task_id = #{filter.taskId}
                </if>
                <if test="filter.taskName != null and filter.taskName != ''">
                    AND ct.task_name LIKE CONCAT('%', #{filter.taskName}, '%')
                </if>
                <if test="filter.taskGroup != null and filter.taskGroup != ''">
                    AND ct.task_group = #{filter.taskGroup}
                </if>
                <if test="filter.status != null">
                    AND ct.status = #{filter.status}
                </if>
            </if>
    </select>
</mapper>
