-- ============================================================
-- Demo 租户初始化脚本（幂等，可重复执行）
-- 租户 ID: 1300000000888
-- Demo 管理员账号: DemoAdmin (密码同主租户 Admin.NET)
-- ============================================================

SET @demo_tid   = 1300000000888;
SET @demo_orgid = 1300000000888;
SET @demo_uid   = 1300000000888;
SET @demo_rid   = 1300000000888;

-- 复用主租户 Admin.NET 的密码哈希
SET @pwd_hash = (SELECT Password FROM SysUser WHERE Account = 'Admin.NET' AND TenantId = 1300000000001 LIMIT 1);

-- 预读主租户的连接信息
SET @main_conn   = (SELECT Connection FROM (SELECT Connection FROM SysTenant WHERE Id = 1300000000001) t);
SET @main_cfgid  = (SELECT ConfigId  FROM (SELECT ConfigId  FROM SysTenant WHERE Id = 1300000000001) t);

-- ── 1. 租户 ──
INSERT IGNORE INTO SysTenant (Id, UserId, OrgId, Host, TenantType, DbType, Connection, ConfigId,
    Logo, Title, ViceTitle, ViceDesc, Watermark, Copyright, Icp, IcpUrl,
    OrderNo, Remark, Status, CreateTime)
VALUES (@demo_tid, @demo_uid, @demo_orgid, '', 0, 0,
    @main_conn, @main_cfgid,
    '/upload/logo.png', 'Demo 演示租户', 'AiDOP Demo', '演示数据隔离', 'DEMO',
    'Demo Only', '', '', 10, 'Demo 租户，数据与正式隔离', 1, NOW());

-- ── 2. 组织 ──
INSERT IGNORE INTO SysOrg (Id, Pid, Name, Code, Level, OrderNo, Status, Remark, TenantId, CreateTime)
VALUES (@demo_orgid, 0, 'Demo默认组织', 'DEMO01', 1, 100, 1, 'Demo 租户根组织', @demo_tid, NOW());

-- ── 3. 角色（系统管理员） ──
INSERT IGNORE INTO SysRole (Id, Name, Code, OrderNo, DataScope, Remark, Status, TenantId, CreateTime)
VALUES (@demo_rid, '系统管理员', 'demo_admin', 100, 1, 'Demo 管理员角色', 1, @demo_tid, NOW());

-- ── 4. 角色菜单（复制主租户管理员的菜单权限） ──
DELETE FROM SysRoleMenu WHERE RoleId = @demo_rid;
SET @rn = 0;
INSERT INTO SysRoleMenu (Id, RoleId, MenuId)
SELECT 1300000888000 + (@rn := @rn + 1), @demo_rid, MenuId
FROM SysRoleMenu WHERE RoleId = 1300000000101;

-- ── 5. 租户菜单（复制主租户的菜单授权） ──
DELETE FROM SysTenantMenu WHERE TenantId = @demo_tid;
SET @tn = 0;
INSERT INTO SysTenantMenu (Id, TenantId, MenuId)
SELECT 1300008880000 + (@tn := @tn + 1), @demo_tid, MenuId
FROM SysTenantMenu WHERE TenantId = 1300000000001;

-- ── 6. 用户 ──
INSERT IGNORE INTO SysUser (Id, Account, Password, RealName, NickName, Sex, Age, CardType, OrderNo,
    Status, AccountType, OrgId, PosId, TenantId, CreateTime)
VALUES (@demo_uid, 'DemoAdmin', @pwd_hash, 'Demo管理员', 'Demo管理员',
    0, 0, 0, 100, 1, 888, @demo_orgid, 0, @demo_tid, NOW());

-- ── 7. 用户角色关联 ──
INSERT IGNORE INTO SysUserRole (UserId, RoleId)
VALUES (@demo_uid, @demo_rid);

SELECT 'Demo tenant setup complete.' AS result;
