-- 用户站内消息
-- 复用现有 la_notice_record 表：scene_id 1001-1005 为社区互动、积分到账和后台系统消息。

SET @notice_index_exists := (
  SELECT COUNT(*)
  FROM information_schema.statistics
  WHERE table_schema = DATABASE()
    AND table_name = 'la_notice_record'
    AND index_name = 'idx_user_scene_read_id'
);
SET @notice_index_sql := IF(
  @notice_index_exists = 0,
  'ALTER TABLE `la_notice_record` ADD INDEX `idx_user_scene_read_id` (`user_id`, `scene_id`, `read`, `id`)',
  'SELECT 1'
);
PREPARE notice_index_stmt FROM @notice_index_sql;
EXECUTE notice_index_stmt;
DEALLOCATE PREPARE notice_index_stmt;

-- 管理后台：应用管理 > 消息管理 > 站内消息。
SET @message_parent_id := (
  SELECT `id`
  FROM `la_system_menu`
  WHERE `type` = 'M' AND `paths` = 'message'
  LIMIT 1
);

INSERT INTO `la_system_menu`
  (`pid`, `type`, `name`, `icon`, `sort`, `perms`, `paths`, `component`, `selected`, `params`, `is_cache`, `is_show`, `is_disable`, `create_time`, `update_time`)
SELECT
  @message_parent_id, 'C', '站内消息', '', 0, 'notice.userNotice/lists', 'user_notice', 'message/user_notice/index', '', '', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
WHERE @message_parent_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM `la_system_menu` WHERE `perms` = 'notice.userNotice/lists'
  );

SET @user_notice_menu_id := (
  SELECT `id`
  FROM `la_system_menu`
  WHERE `perms` = 'notice.userNotice/lists'
  LIMIT 1
);

INSERT INTO `la_system_menu`
  (`pid`, `type`, `name`, `icon`, `sort`, `perms`, `paths`, `component`, `selected`, `params`, `is_cache`, `is_show`, `is_disable`, `create_time`, `update_time`)
SELECT @user_notice_menu_id, permission.`name`, '', 0, permission.`perms`, '', '', '', '', 0, 0, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
FROM (
  SELECT '消息类型选项' AS `name`, 'notice.userNotice/options' AS `perms`
  UNION ALL SELECT '发布系统消息', 'notice.userNotice/send'
  UNION ALL SELECT '删除站内消息', 'notice.userNotice/delete'
) permission
WHERE @user_notice_menu_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM `la_system_menu` existing_menu WHERE existing_menu.`perms` = permission.`perms`
  );

INSERT INTO `la_system_role_menu` (`role_id`, `menu_id`)
SELECT 1, menu.`id`
FROM `la_system_menu` menu
WHERE menu.`perms` IN (
  'notice.userNotice/lists',
  'notice.userNotice/options',
  'notice.userNotice/send',
  'notice.userNotice/delete'
)
AND NOT EXISTS (
  SELECT 1
  FROM `la_system_role_menu` role_menu
  WHERE role_menu.`role_id` = 1
    AND role_menu.`menu_id` = menu.`id`
);
