-- 跨域联合招聘会 - 联盟城市表
-- 用于「各地市就业信息」Tab 的联盟城市筛选与管理（替代前端硬编码 mock）。
-- 依赖：sys_menu 已存在 menu_id=2114「跨域联合招聘会管理」（parent_id=2055）。

CREATE SEQUENCE IF NOT EXISTS shz.cms_cross_city_alliance_id_seq
    START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;

CREATE TABLE IF NOT EXISTS shz.cms_cross_city_alliance (
    id          BIGINT       NOT NULL DEFAULT nextval('shz.cms_cross_city_alliance_id_seq'::regclass) PRIMARY KEY,
    name        VARCHAR(64)  NOT NULL,
    create_by   VARCHAR(64),
    create_time TIMESTAMP,
    update_by   VARCHAR(64),
    update_time TIMESTAMP,
    remark      VARCHAR(500),
    del_flag    CHAR(1)      DEFAULT '0'
);

COMMENT ON TABLE  shz.cms_cross_city_alliance IS '跨域联合招聘会-联盟城市表';
COMMENT ON COLUMN shz.cms_cross_city_alliance.id       IS '主键';
COMMENT ON COLUMN shz.cms_cross_city_alliance.name     IS '城市名称';
COMMENT ON COLUMN shz.cms_cross_city_alliance.del_flag IS '删除标志（0存在 2删除）';

-- 种子：8 个联盟城市（与原前端 mock 一致），仅在表为空时插入
INSERT INTO shz.cms_cross_city_alliance (name, create_by, create_time, del_flag)
SELECT * FROM (VALUES
    ('乌鲁木齐市',      'admin', now(), '0'),
    ('克拉玛依市',      'admin', now(), '0'),
    ('昌吉回族自治州',  'admin', now(), '0'),
    ('哈密市',          'admin', now(), '0'),
    ('吐鲁番市',        'admin', now(), '0'),
    ('喀什地区',        'admin', now(), '0'),
    ('阿克苏地区',      'admin', now(), '0'),
    ('伊犁哈萨克自治州','admin', now(), '0')
) AS seed(name, create_by, create_time, del_flag)
WHERE NOT EXISTS (SELECT 1 FROM shz.cms_cross_city_alliance);

-- 给已存在的页面菜单 2114 补上 perms（仅当为空时）
UPDATE sys_menu
SET perms = 'cms:crossCityFair:list', update_by = 'system', update_time = now()
WHERE menu_id = 2114 AND (perms IS NULL OR perms = '');

-- 新增 4 个按钮权限（仅在不存在时插入）
INSERT INTO sys_menu (menu_name, parent_id, order_num, path, component, query, route_name, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT btn.menu_name, 2114, btn.order_num, '', NULL, NULL, '', 1, 0, 'F', '0', '0', btn.perms, '#', 'system', now(), '跨域联合招聘会-按钮'
FROM (VALUES
    ('联盟城市查询', 1, 'cms:crossCityFair:query'),
    ('联盟城市新增', 2, 'cms:crossCityFair:add'),
    ('联盟城市修改', 3, 'cms:crossCityFair:edit'),
    ('联盟城市删除', 4, 'cms:crossCityFair:remove')
) AS btn(menu_name, order_num, perms)
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE perms = btn.perms);

-- 授权：把上述按钮权限授予拥有 menu_id=2114 的角色
WITH cross_roles AS (
    SELECT DISTINCT role_id FROM sys_role_menu WHERE menu_id = 2114
),
new_menus AS (
    SELECT menu_id FROM sys_menu
    WHERE perms IN ('cms:crossCityFair:query','cms:crossCityFair:add','cms:crossCityFair:edit','cms:crossCityFair:remove')
),
rows AS (
    SELECT cross_roles.role_id, new_menus.menu_id FROM cross_roles CROSS JOIN new_menus
)
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT rows.role_id, rows.menu_id FROM rows
WHERE NOT EXISTS (SELECT 1 FROM sys_role_menu ex WHERE ex.role_id = rows.role_id AND ex.menu_id = rows.menu_id);
