<?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.algorithm.mapper.AlgorithmParamsMapper">

    <select id="getAlgorithmParamsList" resultType="java.util.Map">
        SELECT
        ap.algorithm_id,
        ap.param_type,
        ap.param_unit,
        ap.param_range,
        ap.param_name,
        ap.param_desc,
        ap.param_fixed,
        ap.default_values,
        ap.description,
        ad.param_value,
        ad.component_id,
        ad.source_type,
        ad.device_id,
        ad.device_name,
        ap.id paramId,
        ad.id
        FROM
        iis_algorithm_params ap
        LEFT JOIN iis_algorithm_device ad
        ON ap.id = ad.param_id
        <!-- 动态添加 component_id 匹配条件 -->
        <if test="componentId != null and componentId != ''">
            AND ad.component_id = #{componentId}
        </if>
        WHERE 1=1
        <if test="algorithmId != null and algorithmId != ''">
            AND ap.algorithm_id = #{algorithmId}
        </if>
    </select>
    <select id="getAlgorithmParamsNameList" resultType="java.util.Map">
        SELECT
        ap.param_unit,
        ap.param_name,
        ap.id
        FROM
        iis_algorithm_params ap
        LEFT JOIN iis_algorithm_device ad
        ON ap.id = ad.param_id
        <!-- 动态添加 component_id 匹配条件 -->
        <if test="componentId != null and componentId != ''">
            AND ad.component_id = #{componentId}
        </if>
        WHERE 1=1 AND ap.param_fixed='0'
        <if test="algorithmId != null and algorithmId != ''">
            AND ap.algorithm_id = #{algorithmId}
        </if>
    </select>
    <select id="getAnalyseParams" resultType="java.util.Map">
    SELECT
    ap.id paramId,
		ad.device_id,
    ap.param_unit,
    ap.param_name,
    CASE
        WHEN ap.param_fixed = '1' THEN ad.param_value
        ELSE
            CASE ad.source_type
                WHEN '1' THEN (
                    SELECT tr.value
                    FROM iis_task_result tr
                    WHERE tr.device_id = ad.device_id
                    ORDER BY tr.patroldevice_date DESC
                    LIMIT 1
                )
                WHEN '2' THEN (
                    SELECT dwd.value
                    FROM fk_device_work_data dwd
                    WHERE dwd.signal_id = ad.device_id
										ORDER BY dwd.start_time DESC
                    LIMIT 1
                )
                ELSE NULL
            END
    END AS param_value,
    ap.algorithm_id,
    ad.component_id,
    ap.param_fixed
FROM
    iis_algorithm_params ap
LEFT JOIN iis_algorithm_device ad
    ON ap.id = ad.param_id
    AND ad.component_id = #{componentId}
WHERE

     ap.algorithm_id = #{id};
    </select>
</mapper>
