-- 执行状态：测试环境已执行，功能验证已通过，正式环境待执行
-- 测试环境：test
-- 测试执行时间：2026-07-24 09:39:31 +0800
-- 功能验证时间：2026-07-24 09:56:15 +0800
-- 正式环境：待明确授权后执行
-- 招聘会机构管理及场地所属机构多选关联。
-- 依赖：招聘会管理目录（menu_name='招聘会管理'）和场地信息维护权限已存在。
-- 可重复执行；正式环境仅在功能验收通过并获单独授权后执行。

BEGIN;

SET LOCAL search_path = shz, public;

CREATE SEQUENCE IF NOT EXISTS cms_job_fair_institution_id_seq
    START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;

CREATE SEQUENCE IF NOT EXISTS cms_venue_institution_id_seq
    START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;

CREATE TABLE IF NOT EXISTS cms_job_fair_institution (
    id                  BIGINT NOT NULL DEFAULT nextval('cms_job_fair_institution_id_seq') PRIMARY KEY,
    institution_name    VARCHAR(200) NOT NULL,
    institution_intro   TEXT,
    create_by           VARCHAR(64) DEFAULT '',
    create_time         TIMESTAMP(0),
    update_by           VARCHAR(64) DEFAULT '',
    update_time         TIMESTAMP(0),
    remark              VARCHAR(500),
    del_flag            CHAR(1) DEFAULT '0'
);

COMMENT ON TABLE cms_job_fair_institution IS '招聘会机构管理表';
COMMENT ON COLUMN cms_job_fair_institution.institution_name IS '机构名称';
COMMENT ON COLUMN cms_job_fair_institution.institution_intro IS '机构简介';
COMMENT ON COLUMN cms_job_fair_institution.del_flag IS '删除标志（0代表存在 2代表删除）';

CREATE UNIQUE INDEX IF NOT EXISTS uk_cms_job_fair_institution_name
    ON cms_job_fair_institution (institution_name) WHERE del_flag = '0';

CREATE TABLE IF NOT EXISTS cms_venue_institution (
    id              BIGINT NOT NULL DEFAULT nextval('cms_venue_institution_id_seq') PRIMARY KEY,
    venue_id        BIGINT NOT NULL,
    institution_id  BIGINT NOT NULL
);

COMMENT ON TABLE cms_venue_institution IS '场地与招聘会机构关联表';
COMMENT ON COLUMN cms_venue_institution.venue_id IS '场地ID';
COMMENT ON COLUMN cms_venue_institution.institution_id IS '机构ID';

CREATE UNIQUE INDEX IF NOT EXISTS uk_cms_venue_institution
    ON cms_venue_institution (venue_id, institution_id);
CREATE INDEX IF NOT EXISTS idx_cms_venue_institution_institution
    ON cms_venue_institution (institution_id);

WITH parent_menu AS (
    SELECT menu_id
    FROM sys_menu
    WHERE menu_name = '招聘会管理' AND parent_id = 0
    ORDER BY menu_id
    LIMIT 1
), inserted_page AS (
    INSERT INTO sys_menu (
        menu_id, 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
        (SELECT COALESCE(MAX(menu_id), 0) + 1 FROM sys_menu),
        '机构管理', parent_menu.menu_id, 3, 'institution', 'jobfair/institution/index', NULL, '',
        1, 0, 'C', '0', '0', 'cms:jobFairInstitution:list', '#',
        'system', NOW(), '招聘会机构管理菜单'
    FROM parent_menu
    WHERE NOT EXISTS (
        SELECT 1
        FROM sys_menu existing
        WHERE existing.parent_id = parent_menu.menu_id
          AND existing.menu_name = '机构管理'
    )
    RETURNING menu_id
), institution_page AS (
    SELECT menu_id FROM inserted_page
    UNION
    SELECT menu_id
    FROM sys_menu
    WHERE menu_name = '机构管理'
      AND parent_id = (SELECT menu_id FROM parent_menu)
), button_seed(menu_name, order_num, perms) AS (
    VALUES
        ('机构查询', 1, 'cms:jobFairInstitution:query'),
        ('机构新增', 2, 'cms:jobFairInstitution:add'),
        ('机构修改', 3, 'cms:jobFairInstitution:edit'),
        ('机构删除', 4, 'cms:jobFairInstitution:remove')
), max_menu AS (
    SELECT COALESCE(MAX(menu_id), 0) AS menu_id FROM sys_menu
)
INSERT INTO sys_menu (
    menu_id, 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
    max_menu.menu_id + 1 + ROW_NUMBER() OVER (ORDER BY button_seed.order_num),
    button_seed.menu_name, institution_page.menu_id, button_seed.order_num, '', NULL, NULL, '',
    1, 0, 'F', '0', '0', button_seed.perms, '#',
    'system', NOW(), '招聘会机构管理按钮权限'
FROM institution_page
CROSS JOIN button_seed
CROSS JOIN max_menu
WHERE NOT EXISTS (
    SELECT 1 FROM sys_menu existing WHERE existing.perms = button_seed.perms
);

WITH institution_menus AS (
    SELECT menu_id
    FROM sys_menu
    WHERE perms IN (
        'cms:jobFairInstitution:list',
        'cms:jobFairInstitution:query',
        'cms:jobFairInstitution:add',
        'cms:jobFairInstitution:edit',
        'cms:jobFairInstitution:remove'
    )
    UNION
    SELECT menu_id
    FROM sys_menu
    WHERE menu_name = '机构管理'
      AND parent_id = (SELECT menu_id FROM sys_menu WHERE menu_name = '招聘会管理' AND parent_id = 0 ORDER BY menu_id LIMIT 1)
), venue_roles AS (
    SELECT DISTINCT role_id
    FROM sys_role_menu
    WHERE menu_id IN (
        SELECT menu_id FROM sys_menu WHERE perms = 'cms:venueInfo:list'
    )
), role_menu_rows AS (
    SELECT venue_roles.role_id, institution_menus.menu_id
    FROM venue_roles
    CROSS JOIN institution_menus
)
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT role_menu_rows.role_id, role_menu_rows.menu_id
FROM role_menu_rows
WHERE NOT EXISTS (
    SELECT 1
    FROM sys_role_menu existing
    WHERE existing.role_id = role_menu_rows.role_id
      AND existing.menu_id = role_menu_rows.menu_id
);

COMMIT;
