CREATE TABLE call_number_voice (
                                   id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
                                   play_count INT NOT NULL CHECK (play_count BETWEEN 1 AND 5),
                                   call_prefix VARCHAR(20),
                                   call_suffix VARCHAR(50),
                                   speed VARCHAR(10) NOT NULL CHECK (speed IN ('较慢', '正常', '较快')),
                                   volume INT NOT NULL CHECK (volume BETWEEN 0 AND 100),
                                   interval_seconds INT NOT NULL,
                                   cycle_broadcast BOOLEAN NOT NULL DEFAULT false,
                                   create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                                   update_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    -- 核心约束：循环播放与间隔的逻辑关联
                                   CONSTRAINT chk_cycle_interval
                                       CHECK (
                                           (cycle_broadcast = false AND interval_seconds = 0)
                                               OR
                                           (cycle_broadcast = true AND interval_seconds > 0)
                                           )
);

-- 1. 添加表注释（PostgreSQL 语法）
COMMENT ON TABLE call_number_voice IS '叫号语音配置表';

-- 2. 逐个添加字段注释（PostgreSQL 语法）
COMMENT ON COLUMN call_number_voice.id IS '主键ID，自增';
COMMENT ON COLUMN call_number_voice.play_count IS '播放次数（1-5次）';
COMMENT ON COLUMN call_number_voice.call_prefix IS '叫号前缀（如“请”）';
COMMENT ON COLUMN call_number_voice.call_suffix IS '叫号后缀（如“到1号窗口就诊”）';
COMMENT ON COLUMN call_number_voice.speed IS '语速（较慢/正常/较快）';
COMMENT ON COLUMN call_number_voice.volume IS '音量（0-100%）';
COMMENT ON COLUMN call_number_voice.interval_seconds IS '播报间隔（秒）';
COMMENT ON COLUMN call_number_voice.cycle_broadcast IS '是否循环播报（默认关闭）';
COMMENT ON COLUMN call_number_voice.create_time IS '创建时间（自动填充当前时间）';
COMMENT ON COLUMN call_number_voice.update_time IS '更新时间（自动更新）';

-- 实现update_time自动更新（PostgreSQL需通过触发器）
CREATE OR REPLACE FUNCTION update_call_number_voice_time()
RETURNS TRIGGER AS $$
BEGIN
    NEW.update_time = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_call_number_voice_update
    BEFORE UPDATE ON call_number_voice
    FOR EACH ROW
    EXECUTE FUNCTION update_call_number_voice_time();

INSERT INTO call_number_voice (play_count, call_prefix, call_suffix, speed, volume, interval_seconds, cycle_broadcast) VALUES (2,'请','到诊室就诊','正常',80,10,TRUE);