-- ========================================
-- 依从性统计功能 - SQL脚本
-- ========================================

-- 用药统计菜单
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
VALUES (
    nextval('seq_sys_menu'),
    '用药统计',
    (SELECT menu_id FROM sys_menu WHERE menu_name = '健康管理' LIMIT 1),
    12,
    'medicationStatistic',
    'health/medicationStatistic/index',
    NULL,
    1,
    0,
    'C',
    '0',
    '0',
    'health:medicationStatistic:query',
    'chart',
    'admin',
    NOW(),
    '用药统计菜单'
);

-- 用药统计按钮权限
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT nextval('seq_sys_menu'), '用药统计查询', m.menu_id, 1, '', NULL, NULL, 1, 0, 'F', '0', '0', 'health:medicationStatistic:query', '#', 'admin', NOW(), '' FROM sys_menu m WHERE m.perms = 'health:medicationStatistic:query';

-- ========================================
-- 添加依从性统计汇总表（可选，用于预计算性能优化）
-- ========================================
DROP TABLE IF EXISTS health_medication_adherence_stats;
CREATE TABLE health_medication_adherence_stats (
    id              BIGINT          NOT NULL,
    person_id       BIGINT          NOT NULL,
    plan_id         BIGINT          NULL,
    stat_date       DATE            NOT NULL,
    total_tasks     INT             DEFAULT 0,
    completed_tasks INT             DEFAULT 0,
    missed_tasks    INT             DEFAULT 0,
    skipped_tasks   INT             DEFAULT 0,
    ontime_tasks    INT             DEFAULT 0,
    adherence_rate  DECIMAL(5,2)    DEFAULT 0.00,
    ontime_rate     DECIMAL(5,2)    DEFAULT 0.00,
    create_time     DATETIME        DEFAULT CURRENT_TIMESTAMP,
    update_time     DATETIME        DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE=InnoDB COMMENT='依从性统计汇总表';

CREATE UNIQUE INDEX idx_hmas_person_date ON health_medication_adherence_stats(person_id, stat_date, plan_id);
CREATE INDEX idx_hmas_stat_date ON health_medication_adherence_stats(stat_date);