-- 2026年03月自动采集分表触发器
-- 说明：
-- 1. 本脚本是 base_device_param_val_partition_trigger_template.sql 的 202603 实例化版本。
-- 2. 挂载表：BASE_DEVICE_PARAM_VAL_202603
-- 3. 仅处理自动采集设备；OLD 设备 RT 累计由 Java Service 同步完成。

CREATE OR REPLACE TRIGGER TRG_BDPV_202603_RT
AFTER INSERT ON BASE_DEVICE_PARAM_VAL_202603
FOR EACH ROW
DECLARE
    V_PROD_DATE   DATE;
    V_NEW_VAL     NUMBER(18,4);
    V_LAST_VAL    NUMBER(18,4);
    V_CUR_TOTAL   NUMBER(18,4);
    V_RESET_COUNT NUMBER(10);
    V_DELTA       NUMBER(18,4);
BEGIN
    IF :NEW.PARAM_NAME <> '机台状态-实际产出数量' THEN
        RETURN;
    END IF;

    IF :NEW.DEVICE_CODE LIKE 'OLD-%' THEN
        RETURN;
    END IF;

    BEGIN
        V_NEW_VAL := TO_NUMBER(:NEW.PARAM_VALUE);
    EXCEPTION
        WHEN OTHERS THEN
            RETURN;
    END;

    V_PROD_DATE := TRUNC(:NEW.COLLECT_TIME);

    BEGIN
        SELECT LAST_PARAM_VAL,
               CURRENT_TOTAL,
               RESET_COUNT
          INTO V_LAST_VAL,
               V_CUR_TOTAL,
               V_RESET_COUNT
          FROM RT_DAILY_PROD_STATE
         WHERE PROD_DATE = V_PROD_DATE
           AND DEVICE_CODE = :NEW.DEVICE_CODE
           AND PARAM_NAME = :NEW.PARAM_NAME
         FOR UPDATE;

        IF V_NEW_VAL > V_LAST_VAL THEN
            V_DELTA := V_NEW_VAL - V_LAST_VAL;
        ELSIF V_NEW_VAL < V_LAST_VAL THEN
            V_DELTA := V_NEW_VAL;
            V_RESET_COUNT := NVL(V_RESET_COUNT, 0) + 1;
        ELSE
            V_DELTA := 0;
        END IF;

        UPDATE RT_DAILY_PROD_STATE
           SET LAST_PARAM_VAL    = V_NEW_VAL,
               CURRENT_TOTAL     = NVL(V_CUR_TOTAL, 0) + NVL(V_DELTA, 0),
               RESET_COUNT       = NVL(V_RESET_COUNT, 0),
               LAST_COLLECT_TIME = :NEW.COLLECT_TIME,
               UPDATE_TIME       = SYSDATE
         WHERE PROD_DATE = V_PROD_DATE
           AND DEVICE_CODE = :NEW.DEVICE_CODE
           AND PARAM_NAME = :NEW.PARAM_NAME;
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO RT_DAILY_PROD_STATE (
                PROD_DATE, DEVICE_CODE, PARAM_NAME, LAST_PARAM_VAL,
                CURRENT_TOTAL, RESET_COUNT, DIRTY_FLAG, LAST_COLLECT_TIME, UPDATE_TIME
            ) VALUES (
                V_PROD_DATE, :NEW.DEVICE_CODE, :NEW.PARAM_NAME, V_NEW_VAL,
                0, 0, 0, :NEW.COLLECT_TIME, SYSDATE
            );
    END;
END;
/
