-- 平台字典类型管理：支持新增类型并维护字典项

CREATE TABLE IF NOT EXISTS platform_dictionary_type (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    dict_type VARCHAR(64) NOT NULL COMMENT '字典类型编码',
    dict_name VARCHAR(128) NOT NULL COMMENT '字典类型名称',
    sort_no INT NOT NULL DEFAULT 100 COMMENT '排序',
    status VARCHAR(32) NOT NULL DEFAULT 'ENABLED' COMMENT '状态：ENABLED/DISABLED',
    remark VARCHAR(500) DEFAULT NULL COMMENT '备注',
    is_deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除',
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '创建人',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '更新人',
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY uk_platform_dictionary_type (dict_type),
    KEY idx_platform_dictionary_type_status_sort (status, sort_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台共享字典类型';

-- 将已有字典项中的类型补齐到类型表（避免升级后历史数据丢失类型）
INSERT INTO platform_dictionary_type (dict_type, dict_name, sort_no, status, remark, created_by, updated_by)
SELECT t.dict_type, t.dict_type, 100, 'ENABLED', '从历史字典项自动补齐', 0, 0
FROM (
    SELECT DISTINCT dict_type
    FROM platform_dictionary_item
    WHERE is_deleted = 0
) t
ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP;

-- 覆盖默认种子类型展示名与排序
INSERT INTO platform_dictionary_type (dict_type, dict_name, sort_no, status, remark, created_by, updated_by)
VALUES
    ('EXPERT_TITLE', '专家职称', 10, 'ENABLED', '默认种子', 0, 0),
    ('EXPERT_HOSPITAL', '专家医院', 20, 'ENABLED', '默认种子', 0, 0)
ON DUPLICATE KEY UPDATE
    dict_name = VALUES(dict_name),
    sort_no = VALUES(sort_no),
    status = VALUES(status),
    remark = VALUES(remark),
    updated_at = CURRENT_TIMESTAMP;
