-- 智能分诊排队：队列持久化表（与 TriageQueueItem.java 字段一致）
-- 注意：必须在后端实际连接的 schema 中执行（dev环境是 hisdev，test环境是 histest，prd环境是 hisprd）
-- 执行前请先确认：SET search_path TO hisdev; （或对应的 schema）

CREATE TABLE IF NOT EXISTS triage_queue_item (
    id               BIGSERIAL PRIMARY KEY,
    tenant_id        INTEGER      NOT NULL,
    queue_date       DATE         NOT NULL,
    organization_id  BIGINT       NOT NULL,
    organization_name VARCHAR(255),
    encounter_id     BIGINT       NOT NULL,
    patient_id       BIGINT,
    patient_name     VARCHAR(255),
    healthcare_name  VARCHAR(255),
    practitioner_name VARCHAR(255),
    status           INTEGER      NOT NULL DEFAULT 0, -- 分诊队列状态: 0=WAITING(等待), 10=CALLING(叫号中), 20=IN_CLINIC(诊中), 30=COMPLETED(已完成), 40=SKIPPED(已跳过)
    queue_order      INTEGER      NOT NULL,
    create_time      TIMESTAMP,
    update_time      TIMESTAMP,
    delete_flag      CHAR(1)      NOT NULL DEFAULT '0'
);

-- 常用查询索引：按租户/科室/日期/状态/顺序取队列
CREATE INDEX IF NOT EXISTS idx_triage_queue_item_list
    ON triage_queue_item (tenant_id, queue_date, organization_id, delete_flag, status, queue_order);

-- 防重复：同一天同租户同科室同就诊记录只能在队列里一条（未删除）
CREATE UNIQUE INDEX IF NOT EXISTS uq_triage_queue_item_encounter
    ON triage_queue_item (tenant_id, queue_date, organization_id, encounter_id, delete_flag)
    WHERE delete_flag = '0';

-- 就诊记录ID索引（用于关联查询）
CREATE INDEX IF NOT EXISTS idx_triage_queue_item_encounter_id
    ON triage_queue_item (encounter_id);

