-- ========================================
-- 用药管理模块 - PostgreSQL 建表语句
-- 依据：慢性病用药管理模块-功能规划文档
-- ========================================

-- ========================================
-- 1. 慢性疾病档案表
-- ========================================
DROP TABLE IF EXISTS chronic_disease_record;
CREATE TABLE chronic_disease_record (
    id                  BIGSERIAL       PRIMARY KEY,
    member_id           BIGINT          NOT NULL,
    disease_name        VARCHAR(100)    NOT NULL,
    disease_code        VARCHAR(20),
    diagnosis_date      DATE,
    disease_status      SMALLINT        NOT NULL DEFAULT 1,
    main_doctor         VARCHAR(50),
    hospital            VARCHAR(100),
    department          VARCHAR(50),
    notes               TEXT,
    -- 若依标准字段
    create_by           VARCHAR(64)     DEFAULT '',
    create_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    update_by           VARCHAR(64)     DEFAULT '',
    update_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    remark              VARCHAR(500)    DEFAULT '',
    del_flag            SMALLINT        DEFAULT 0
);

COMMENT ON TABLE chronic_disease_record IS '慢性疾病档案表';
COMMENT ON COLUMN chronic_disease_record.id IS '主键ID';
COMMENT ON COLUMN chronic_disease_record.member_id IS '关联成员ID';
COMMENT ON COLUMN chronic_disease_record.disease_name IS '疾病名称（高血压/糖尿病/冠心病等）';
COMMENT ON COLUMN chronic_disease_record.disease_code IS '疾病编码（ICD-10标准）';
COMMENT ON COLUMN chronic_disease_record.diagnosis_date IS '确诊日期';
COMMENT ON COLUMN chronic_disease_record.disease_status IS '状态：1-稳定 2-需关注 3-急性期';
COMMENT ON COLUMN chronic_disease_record.main_doctor IS '主治医生';
COMMENT ON COLUMN chronic_disease_record.hospital IS '就诊医院';
COMMENT ON COLUMN chronic_disease_record.department IS '科室';
COMMENT ON COLUMN chronic_disease_record.notes IS '备注说明';
COMMENT ON COLUMN chronic_disease_record.create_by IS '创建者';
COMMENT ON COLUMN chronic_disease_record.create_time IS '创建时间';
COMMENT ON COLUMN chronic_disease_record.update_by IS '更新者';
COMMENT ON COLUMN chronic_disease_record.update_time IS '更新时间';
COMMENT ON COLUMN chronic_disease_record.remark IS '备注';
COMMENT ON COLUMN chronic_disease_record.del_flag IS '删除标记：0-正常 1-删除';

CREATE INDEX idx_cdr_member_id ON chronic_disease_record(member_id);
CREATE INDEX idx_cdr_disease_status ON chronic_disease_record(disease_status);

-- ========================================
-- 2. 用药计划表
-- ========================================
DROP TABLE IF EXISTS medication_plan;
CREATE TABLE medication_plan (
    id                  BIGSERIAL       PRIMARY KEY,
    member_id           BIGINT          NOT NULL,
    chronic_disease_id  BIGINT,
    plan_name           VARCHAR(100)    NOT NULL,
    medicine_id         BIGINT          NOT NULL,
    medicine_name       VARCHAR(100)    NOT NULL,
    specification       VARCHAR(50),
    dosage_per_time     DECIMAL(10,2)   NOT NULL,
    dosage_unit         VARCHAR(20)     NOT NULL,
    frequency_type      SMALLINT        NOT NULL,
    frequency_config    JSONB           NOT NULL,
    time_slots          JSONB           NOT NULL,
    start_date          DATE            NOT NULL,
    end_date            DATE,
    remind_enabled       SMALLINT        NOT NULL DEFAULT 1,
    remind_advance_min   INTEGER,
    notify_family        SMALLINT        DEFAULT 0,
    family_member_ids    JSONB,
    status              SMALLINT        NOT NULL DEFAULT 1,
    -- 若依标准字段
    create_by           VARCHAR(64)     DEFAULT '',
    create_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    update_by           VARCHAR(64)     DEFAULT '',
    update_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    remark              VARCHAR(500)    DEFAULT '',
    del_flag            SMALLINT        DEFAULT 0
);

COMMENT ON TABLE medication_plan IS '用药计划表';
COMMENT ON COLUMN medication_plan.id IS '主键ID';
COMMENT ON COLUMN medication_plan.member_id IS '关联成员ID';
COMMENT ON COLUMN medication_plan.chronic_disease_id IS '关联慢性疾病ID';
COMMENT ON COLUMN medication_plan.plan_name IS '计划名称（如"降压药计划"）';
COMMENT ON COLUMN medication_plan.medicine_id IS '关联药品ID';
COMMENT ON COLUMN medication_plan.medicine_name IS '药品名称（冗余字段）';
COMMENT ON COLUMN medication_plan.specification IS '药品规格（如"10mg/片"）';
COMMENT ON COLUMN medication_plan.dosage_per_time IS '单次剂量';
COMMENT ON COLUMN medication_plan.dosage_unit IS '剂量单位（片/粒/毫升/喷）';
COMMENT ON COLUMN medication_plan.frequency_type IS '频次类型：1-每天 2-每周 3-隔天 4-自定义';
COMMENT ON COLUMN medication_plan.frequency_config IS '频次配置（JSON格式）';
COMMENT ON COLUMN medication_plan.time_slots IS '服药时段配置';
COMMENT ON COLUMN medication_plan.start_date IS '开始日期';
COMMENT ON COLUMN medication_plan.end_date IS '结束日期（空表示长期）';
COMMENT ON COLUMN medication_plan.remind_enabled IS '是否开启提醒：1-是 0-否';
COMMENT ON COLUMN medication_plan.remind_advance_min IS '提前提醒分钟数';
COMMENT ON COLUMN medication_plan.notify_family IS '漏服是否通知家属：1-是 0-否';
COMMENT ON COLUMN medication_plan.family_member_ids IS '通知家属成员ID列表';
COMMENT ON COLUMN medication_plan.status IS '状态：1-执行中 2-已暂停 3-已结束';
COMMENT ON COLUMN medication_plan.create_by IS '创建者';
COMMENT ON COLUMN medication_plan.create_time IS '创建时间';
COMMENT ON COLUMN medication_plan.update_by IS '更新者';
COMMENT ON COLUMN medication_plan.update_time IS '更新时间';
COMMENT ON COLUMN medication_plan.remark IS '备注';
COMMENT ON COLUMN medication_plan.del_flag IS '删除标记：0-正常 1-删除';

CREATE INDEX idx_mp_member_id ON medication_plan(member_id);
CREATE INDEX idx_mp_status ON medication_plan(status);
CREATE INDEX idx_mp_medicine_id ON medication_plan(medicine_id);

-- ========================================
-- 3. 服药任务表
-- ========================================
DROP TABLE IF EXISTS medication_task;
CREATE TABLE medication_task (
    id                  BIGSERIAL       PRIMARY KEY,
    plan_id             BIGINT          NOT NULL,
    member_id           BIGINT          NOT NULL,
    medicine_name       VARCHAR(100)    NOT NULL,
    planned_date        DATE            NOT NULL,
    planned_time        TIME            NOT NULL,
    planned_dosage      DECIMAL(10,2)   NOT NULL,
    actual_time         TIMESTAMP,
    actual_dosage       DECIMAL(10,2),
    status              SMALLINT        NOT NULL DEFAULT 0,
    confirm_type        SMALLINT,
    notes               VARCHAR(255),
    remind_status       SMALLINT        DEFAULT 0,
    remind_time         TIMESTAMP,
    -- 若依标准字段
    create_by           VARCHAR(64)     DEFAULT '',
    create_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    update_by           VARCHAR(64)     DEFAULT '',
    update_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    remark              VARCHAR(500)    DEFAULT '',
    del_flag            SMALLINT        DEFAULT 0
);

COMMENT ON TABLE medication_task IS '服药任务表';
COMMENT ON COLUMN medication_task.id IS '主键ID';
COMMENT ON COLUMN medication_task.plan_id IS '关联用药计划ID';
COMMENT ON COLUMN medication_task.member_id IS '关联成员ID';
COMMENT ON COLUMN medication_task.medicine_name IS '药品名称';
COMMENT ON COLUMN medication_task.planned_date IS '计划服药日期';
COMMENT ON COLUMN medication_task.planned_time IS '计划服药时间';
COMMENT ON COLUMN medication_task.planned_dosage IS '计划剂量';
COMMENT ON COLUMN medication_task.actual_time IS '实际服药时间';
COMMENT ON COLUMN medication_task.actual_dosage IS '实际剂量';
COMMENT ON COLUMN medication_task.status IS '状态：0-待服药 1-已服药 2-漏服 3-跳过';
COMMENT ON COLUMN medication_task.confirm_type IS '确认方式：1-用户确认 2-家属代确认 3-系统自动';
COMMENT ON COLUMN medication_task.notes IS '备注（如漏服原因）';
COMMENT ON COLUMN medication_task.remind_status IS '提醒状态：0-未提醒 1-已提醒 2-已超时提醒';
COMMENT ON COLUMN medication_task.remind_time IS '提醒时间';
COMMENT ON COLUMN medication_task.create_by IS '创建者';
COMMENT ON COLUMN medication_task.create_time IS '创建时间';
COMMENT ON COLUMN medication_task.update_by IS '更新者';
COMMENT ON COLUMN medication_task.update_time IS '更新时间';
COMMENT ON COLUMN medication_task.remark IS '备注';
COMMENT ON COLUMN medication_task.del_flag IS '删除标记：0-正常 1-删除';

CREATE INDEX idx_mt_plan_id ON medication_task(plan_id);
CREATE INDEX idx_mt_member_id ON medication_task(member_id);
CREATE INDEX idx_mt_planned_date ON medication_task(planned_date);
CREATE INDEX idx_mt_status ON medication_task(status);
CREATE INDEX idx_mt_planned_datetime ON medication_task(planned_date, planned_time);

-- ========================================
-- 4. 用药提醒日志表
-- ========================================
DROP TABLE IF EXISTS medication_remind_log;
CREATE TABLE medication_remind_log (
    id                  BIGSERIAL       PRIMARY KEY,
    task_id             BIGINT          NOT NULL,
    remind_type         SMALLINT        NOT NULL,
    remind_time         TIMESTAMP       NOT NULL,
    remind_channel      VARCHAR(20)     NOT NULL,
    remind_result       SMALLINT        NOT NULL,
    error_msg           VARCHAR(255),
    -- 若依标准字段
    create_by           VARCHAR(64)     DEFAULT '',
    create_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    update_by           VARCHAR(64)     DEFAULT '',
    update_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    remark              VARCHAR(500)    DEFAULT '',
    del_flag            SMALLINT        DEFAULT 0
);

COMMENT ON TABLE medication_remind_log IS '用药提醒日志表';
COMMENT ON COLUMN medication_remind_log.id IS '主键ID';
COMMENT ON COLUMN medication_remind_log.task_id IS '关联服药任务ID';
COMMENT ON COLUMN medication_remind_log.remind_type IS '提醒类型：1-按时提醒 2-超时提醒 3-漏服通知家属';
COMMENT ON COLUMN medication_remind_log.remind_time IS '提醒时间';
COMMENT ON COLUMN medication_remind_log.remind_channel IS '提醒渠道：app/sms/wechat';
COMMENT ON COLUMN medication_remind_log.remind_result IS '结果：1-成功 2-失败';
COMMENT ON COLUMN medication_remind_log.error_msg IS '错误信息';
COMMENT ON COLUMN medication_remind_log.create_by IS '创建者';
COMMENT ON COLUMN medication_remind_log.create_time IS '创建时间';
COMMENT ON COLUMN medication_remind_log.update_by IS '更新者';
COMMENT ON COLUMN medication_remind_log.update_time IS '更新时间';
COMMENT ON COLUMN medication_remind_log.remark IS '备注';
COMMENT ON COLUMN medication_remind_log.del_flag IS '删除标记：0-正常 1-删除';

CREATE INDEX idx_mrl_task_id ON medication_remind_log(task_id);
CREATE INDEX idx_mrl_remind_time ON medication_remind_log(remind_time);

-- ========================================
-- 5. 药品库存变动表
-- ========================================
DROP TABLE IF EXISTS medicine_stock_log;
CREATE TABLE medicine_stock_log (
    id                  BIGSERIAL       PRIMARY KEY,
    medicine_id         BIGINT          NOT NULL,
    member_id           BIGINT          NOT NULL,
    change_type         SMALLINT        NOT NULL,
    change_quantity     DECIMAL(10,2)   NOT NULL,
    before_quantity     DECIMAL(10,2)   NOT NULL,
    after_quantity      DECIMAL(10,2)   NOT NULL,
    relate_id           BIGINT,
    notes               VARCHAR(255),
    -- 若依标准字段
    create_by           VARCHAR(64)     DEFAULT '',
    create_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    update_by           VARCHAR(64)     DEFAULT '',
    update_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    remark              VARCHAR(500)    DEFAULT '',
    del_flag            SMALLINT        DEFAULT 0
);

COMMENT ON TABLE medicine_stock_log IS '药品库存变动表';
COMMENT ON COLUMN medicine_stock_log.id IS '主键ID';
COMMENT ON COLUMN medicine_stock_log.medicine_id IS '关联药品ID';
COMMENT ON COLUMN medicine_stock_log.member_id IS '关联成员ID';
COMMENT ON COLUMN medicine_stock_log.change_type IS '变动类型：1-入库 2-服药消耗 3-手动调整 4-过期报废';
COMMENT ON COLUMN medicine_stock_log.change_quantity IS '变动数量（正数为增，负数为减）';
COMMENT ON COLUMN medicine_stock_log.before_quantity IS '变动前库存';
COMMENT ON COLUMN medicine_stock_log.after_quantity IS '变动后库存';
COMMENT ON COLUMN medicine_stock_log.relate_id IS '关联ID（入库ID/任务ID等）';
COMMENT ON COLUMN medicine_stock_log.notes IS '备注';
COMMENT ON COLUMN medicine_stock_log.create_by IS '创建者';
COMMENT ON COLUMN medicine_stock_log.create_time IS '创建时间';
COMMENT ON COLUMN medicine_stock_log.update_by IS '更新者';
COMMENT ON COLUMN medicine_stock_log.update_time IS '更新时间';
COMMENT ON COLUMN medicine_stock_log.remark IS '备注';
COMMENT ON COLUMN medicine_stock_log.del_flag IS '删除标记：0-正常 1-删除';

CREATE INDEX idx_msl_medicine_id ON medicine_stock_log(medicine_id);
CREATE INDEX idx_msl_member_id ON medicine_stock_log(member_id);
CREATE INDEX idx_msl_create_time ON medicine_stock_log(create_time);

-- ========================================
-- 6. 依从性统计汇总表
-- ========================================
DROP TABLE IF EXISTS medication_adherence_stats;
CREATE TABLE medication_adherence_stats (
    id                  BIGSERIAL       PRIMARY KEY,
    member_id           BIGINT          NOT NULL,
    plan_id             BIGINT,
    stat_date           DATE            NOT NULL,
    total_tasks         INTEGER         NOT NULL DEFAULT 0,
    completed_tasks     INTEGER         NOT NULL DEFAULT 0,
    missed_tasks        INTEGER         NOT NULL DEFAULT 0,
    skipped_tasks       INTEGER         NOT NULL DEFAULT 0,
    ontime_tasks        INTEGER         NOT NULL DEFAULT 0,
    adherence_rate      DECIMAL(5,2)    NOT NULL DEFAULT 0.00,
    ontime_rate         DECIMAL(5,2)    NOT NULL DEFAULT 0.00,
    -- 若依标准字段
    create_by           VARCHAR(64)     DEFAULT '',
    create_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    update_by           VARCHAR(64)     DEFAULT '',
    update_time         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    remark              VARCHAR(500)    DEFAULT '',
    del_flag            SMALLINT        DEFAULT 0
);

COMMENT ON TABLE medication_adherence_stats IS '依从性统计汇总表';
COMMENT ON COLUMN medication_adherence_stats.id IS '主键ID';
COMMENT ON COLUMN medication_adherence_stats.member_id IS '关联成员ID';
COMMENT ON COLUMN medication_adherence_stats.plan_id IS '关联用药计划ID（为空表示该成员汇总）';
COMMENT ON COLUMN medication_adherence_stats.stat_date IS '统计日期';
COMMENT ON COLUMN medication_adherence_stats.total_tasks IS '总任务数';
COMMENT ON COLUMN medication_adherence_stats.completed_tasks IS '已完成任务数';
COMMENT ON COLUMN medication_adherence_stats.missed_tasks IS '漏服任务数';
COMMENT ON COLUMN medication_adherence_stats.skipped_tasks IS '跳过任务数';
COMMENT ON COLUMN medication_adherence_stats.ontime_tasks IS '准时服药任务数';
COMMENT ON COLUMN medication_adherence_stats.adherence_rate IS '服药率（%）';
COMMENT ON COLUMN medication_adherence_stats.ontime_rate IS '准时率（%）';

CREATE UNIQUE INDEX idx_mas_member_date ON medication_adherence_stats(member_id, stat_date, plan_id);
CREATE INDEX idx_mas_stat_date ON medication_adherence_stats(stat_date);