-- -------------------------------------------------
-- RuoYi-Vue complete database script
-- Generated for this repository by merging sql/ base scripts
-- and adding generator-platform extension tables required by current Mapper files.
-- -------------------------------------------------

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- =================================================
-- RuoYi base tables and seed data
-- Source: sql/ry_20240629.sql
-- =================================================
-- ----------------------------
-- 1、部门表
-- ----------------------------
drop table if exists sys_dept;
create table sys_dept (
  dept_id           bigint(20)      not null auto_increment    comment '部门id',
  parent_id         bigint(20)      default 0                  comment '父部门id',
  ancestors         varchar(50)     default ''                 comment '祖级列表',
  dept_name         varchar(30)     default ''                 comment '部门名称',
  order_num         int(4)          default 0                  comment '显示顺序',
  leader            varchar(20)     default null               comment '负责人',
  phone             varchar(11)     default null               comment '联系电话',
  email             varchar(50)     default null               comment '邮箱',
  status            char(1)         default '0'                comment '部门状态（0正常 1停用）',
  del_flag          char(1)         default '0'                comment '删除标志（0代表存在 2代表删除）',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time 	    datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  primary key (dept_id)
) engine=innodb auto_increment=200 comment = '部门表';

-- ----------------------------
-- 初始化-部门表数据
-- ----------------------------
insert into sys_dept values(100,  0,   '0',          '若依科技',   0, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(101,  100, '0,100',      '深圳总公司', 1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(102,  100, '0,100',      '长沙分公司', 2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(103,  101, '0,100,101',  '研发部门',   1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(104,  101, '0,100,101',  '市场部门',   2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(105,  101, '0,100,101',  '测试部门',   3, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(106,  101, '0,100,101',  '财务部门',   4, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(107,  101, '0,100,101',  '运维部门',   5, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(108,  102, '0,100,102',  '市场部门',   1, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);
insert into sys_dept values(109,  102, '0,100,102',  '财务部门',   2, '若依', '15888888888', 'ry@qq.com', '0', '0', 'admin', sysdate(), '', null);


-- ----------------------------
-- 2、用户信息表
-- ----------------------------
drop table if exists sys_user;
create table sys_user (
  user_id           bigint(20)      not null auto_increment    comment '用户ID',
  dept_id           bigint(20)      default null               comment '部门ID',
  user_name         varchar(30)     not null                   comment '用户账号',
  nick_name         varchar(30)     not null                   comment '用户昵称',
  user_type         varchar(2)      default '00'               comment '用户类型（00系统用户）',
  email             varchar(50)     default ''                 comment '用户邮箱',
  phonenumber       varchar(11)     default ''                 comment '手机号码',
  sex               char(1)         default '0'                comment '用户性别（0男 1女 2未知）',
  avatar            varchar(100)    default ''                 comment '头像地址',
  password          varchar(100)    default ''                 comment '密码',
  status            char(1)         default '0'                comment '帐号状态（0正常 1停用）',
  del_flag          char(1)         default '0'                comment '删除标志（0代表存在 2代表删除）',
  login_ip          varchar(128)    default ''                 comment '最后登录IP',
  login_date        datetime                                   comment '最后登录时间',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time       datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  remark            varchar(500)    default null               comment '备注',
  primary key (user_id)
) engine=innodb auto_increment=100 comment = '用户信息表';

-- ----------------------------
-- 初始化-用户信息表数据
-- ----------------------------
insert into sys_user values(1,  103, 'admin', '若依', '00', 'ry@163.com', '15888888888', '1', '', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null, '管理员');
insert into sys_user values(2,  105, 'ry',    '若依', '00', 'ry@qq.com',  '15666666666', '1', '', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null, '测试员');


-- ----------------------------
-- 3、岗位信息表
-- ----------------------------
drop table if exists sys_post;
create table sys_post
(
  post_id       bigint(20)      not null auto_increment    comment '岗位ID',
  post_code     varchar(64)     not null                   comment '岗位编码',
  post_name     varchar(50)     not null                   comment '岗位名称',
  post_sort     int(4)          not null                   comment '显示顺序',
  status        char(1)         not null                   comment '状态（0正常 1停用）',
  create_by     varchar(64)     default ''                 comment '创建者',
  create_time   datetime                                   comment '创建时间',
  update_by     varchar(64)     default ''			       comment '更新者',
  update_time   datetime                                   comment '更新时间',
  remark        varchar(500)    default null               comment '备注',
  primary key (post_id)
) engine=innodb comment = '岗位信息表';

-- ----------------------------
-- 初始化-岗位信息表数据
-- ----------------------------
insert into sys_post values(1, 'ceo',  '董事长',    1, '0', 'admin', sysdate(), '', null, '');
insert into sys_post values(2, 'se',   '项目经理',  2, '0', 'admin', sysdate(), '', null, '');
insert into sys_post values(3, 'hr',   '人力资源',  3, '0', 'admin', sysdate(), '', null, '');
insert into sys_post values(4, 'user', '普通员工',  4, '0', 'admin', sysdate(), '', null, '');


-- ----------------------------
-- 4、角色信息表
-- ----------------------------
drop table if exists sys_role;
create table sys_role (
  role_id              bigint(20)      not null auto_increment    comment '角色ID',
  role_name            varchar(30)     not null                   comment '角色名称',
  role_key             varchar(100)    not null                   comment '角色权限字符串',
  role_sort            int(4)          not null                   comment '显示顺序',
  data_scope           char(1)         default '1'                comment '数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限）',
  menu_check_strictly  tinyint(1)      default 1                  comment '菜单树选择项是否关联显示',
  dept_check_strictly  tinyint(1)      default 1                  comment '部门树选择项是否关联显示',
  status               char(1)         not null                   comment '角色状态（0正常 1停用）',
  del_flag             char(1)         default '0'                comment '删除标志（0代表存在 2代表删除）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  remark               varchar(500)    default null               comment '备注',
  primary key (role_id)
) engine=innodb auto_increment=100 comment = '角色信息表';

-- ----------------------------
-- 初始化-角色信息表数据
-- ----------------------------
insert into sys_role values('1', '超级管理员',  'admin',  1, 1, 1, 1, '0', '0', 'admin', sysdate(), '', null, '超级管理员');
insert into sys_role values('2', '普通角色',    'common', 2, 2, 1, 1, '0', '0', 'admin', sysdate(), '', null, '普通角色');


-- ----------------------------
-- 5、菜单权限表
-- ----------------------------
drop table if exists sys_menu;
create table sys_menu (
  menu_id           bigint(20)      not null auto_increment    comment '菜单ID',
  menu_name         varchar(50)     not null                   comment '菜单名称',
  parent_id         bigint(20)      default 0                  comment '父菜单ID',
  order_num         int(4)          default 0                  comment '显示顺序',
  path              varchar(200)    default ''                 comment '路由地址',
  component         varchar(255)    default null               comment '组件路径',
  query             varchar(255)    default null               comment '路由参数',
  route_name        varchar(50)     default ''                 comment '路由名称',
  is_frame          int(1)          default 1                  comment '是否为外链（0是 1否）',
  is_cache          int(1)          default 0                  comment '是否缓存（0缓存 1不缓存）',
  menu_type         char(1)         default ''                 comment '菜单类型（M目录 C菜单 F按钮）',
  visible           char(1)         default 0                  comment '菜单状态（0显示 1隐藏）',
  status            char(1)         default 0                  comment '菜单状态（0正常 1停用）',
  perms             varchar(100)    default null               comment '权限标识',
  icon              varchar(100)    default '#'                comment '菜单图标',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time       datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  remark            varchar(500)    default ''                 comment '备注',
  primary key (menu_id)
) engine=innodb auto_increment=2000 comment = '菜单权限表';

-- ----------------------------
-- 初始化-菜单信息表数据
-- ----------------------------
-- 一级菜单
insert into sys_menu values('1', '系统管理', '0', '1', 'system',           null, '', '', 1, 0, 'M', '0', '0', '', 'system',   'admin', sysdate(), '', null, '系统管理目录');
insert into sys_menu values('2', '系统监控', '0', '2', 'monitor',          null, '', '', 1, 0, 'M', '0', '0', '', 'monitor',  'admin', sysdate(), '', null, '系统监控目录');
insert into sys_menu values('3', '系统工具', '0', '3', 'tool',             null, '', '', 1, 0, 'M', '0', '0', '', 'tool',     'admin', sysdate(), '', null, '系统工具目录');
insert into sys_menu values('4', '若依官网', '0', '4', 'http://ruoyi.vip', null, '', '', 0, 0, 'M', '0', '0', '', 'guide',    'admin', sysdate(), '', null, '若依官网地址');
-- 二级菜单
insert into sys_menu values('100',  '用户管理', '1',   '1', 'user',       'system/user/index',        '', '', 1, 0, 'C', '0', '0', 'system:user:list',        'user',          'admin', sysdate(), '', null, '用户管理菜单');
insert into sys_menu values('101',  '角色管理', '1',   '2', 'role',       'system/role/index',        '', '', 1, 0, 'C', '0', '0', 'system:role:list',        'peoples',       'admin', sysdate(), '', null, '角色管理菜单');
insert into sys_menu values('102',  '菜单管理', '1',   '3', 'menu',       'system/menu/index',        '', '', 1, 0, 'C', '0', '0', 'system:menu:list',        'tree-table',    'admin', sysdate(), '', null, '菜单管理菜单');
insert into sys_menu values('103',  '部门管理', '1',   '4', 'dept',       'system/dept/index',        '', '', 1, 0, 'C', '0', '0', 'system:dept:list',        'tree',          'admin', sysdate(), '', null, '部门管理菜单');
insert into sys_menu values('104',  '岗位管理', '1',   '5', 'post',       'system/post/index',        '', '', 1, 0, 'C', '0', '0', 'system:post:list',        'post',          'admin', sysdate(), '', null, '岗位管理菜单');
insert into sys_menu values('105',  '字典管理', '1',   '6', 'dict',       'system/dict/index',        '', '', 1, 0, 'C', '0', '0', 'system:dict:list',        'dict',          'admin', sysdate(), '', null, '字典管理菜单');
insert into sys_menu values('106',  '参数设置', '1',   '7', 'config',     'system/config/index',      '', '', 1, 0, 'C', '0', '0', 'system:config:list',      'edit',          'admin', sysdate(), '', null, '参数设置菜单');
insert into sys_menu values('107',  '通知公告', '1',   '8', 'notice',     'system/notice/index',      '', '', 1, 0, 'C', '0', '0', 'system:notice:list',      'message',       'admin', sysdate(), '', null, '通知公告菜单');
insert into sys_menu values('108',  '日志管理', '1',   '9', 'log',        '',                         '', '', 1, 0, 'M', '0', '0', '',                        'log',           'admin', sysdate(), '', null, '日志管理菜单');
insert into sys_menu values('109',  '在线用户', '2',   '1', 'online',     'monitor/online/index',     '', '', 1, 0, 'C', '0', '0', 'monitor:online:list',     'online',        'admin', sysdate(), '', null, '在线用户菜单');
insert into sys_menu values('110',  '定时任务', '2',   '2', 'job',        'monitor/job/index',        '', '', 1, 0, 'C', '0', '0', 'monitor:job:list',        'job',           'admin', sysdate(), '', null, '定时任务菜单');
insert into sys_menu values('111',  '数据监控', '2',   '3', 'druid',      'monitor/druid/index',      '', '', 1, 0, 'C', '0', '0', 'monitor:druid:list',      'druid',         'admin', sysdate(), '', null, '数据监控菜单');
insert into sys_menu values('112',  '服务监控', '2',   '4', 'server',     'monitor/server/index',     '', '', 1, 0, 'C', '0', '0', 'monitor:server:list',     'server',        'admin', sysdate(), '', null, '服务监控菜单');
insert into sys_menu values('113',  '缓存监控', '2',   '5', 'cache',      'monitor/cache/index',      '', '', 1, 0, 'C', '0', '0', 'monitor:cache:list',      'redis',         'admin', sysdate(), '', null, '缓存监控菜单');
insert into sys_menu values('114',  '缓存列表', '2',   '6', 'cacheList',  'monitor/cache/list',       '', '', 1, 0, 'C', '0', '0', 'monitor:cache:list',      'redis-list',    'admin', sysdate(), '', null, '缓存列表菜单');
insert into sys_menu values('115',  '表单构建', '3',   '1', 'build',      'tool/build/index',         '', '', 1, 0, 'C', '0', '0', 'tool:build:list',         'build',         'admin', sysdate(), '', null, '表单构建菜单');
insert into sys_menu values('116',  '代码生成', '3',   '2', 'gen',        'tool/gen/index',           '', '', 1, 0, 'C', '0', '0', 'tool:gen:list',           'code',          'admin', sysdate(), '', null, '代码生成菜单');
insert into sys_menu values('117',  '系统接口', '3',   '3', 'swagger',    'tool/swagger/index',       '', '', 1, 0, 'C', '0', '0', 'tool:swagger:list',       'swagger',       'admin', sysdate(), '', null, '系统接口菜单');
insert into sys_menu values('118',  '代码生成平台', '0',   '5', 'generator',  null,                       '', '', 1, 0, 'M', '0', '0', '',                        'code',          'admin', sysdate(), '', null, '代码生成平台目录');
insert into sys_menu values('119',  '项目管理', '118', '1', 'project',    'generator/project/index',   '', '', 1, 0, 'C', '0', '0', 'generator:project:list',    'project',       'admin', sysdate(), '', null, '项目管理菜单');
insert into sys_menu values('120',  '数据源管理', '118', '2', 'datasource', 'generator/datasource/index','', '', 1, 0, 'C', '0', '0', 'generator:datasource:list', 'druid',         'admin', sysdate(), '', null, '数据源管理菜单');
insert into sys_menu values('121',  '模板管理', '118', '3', 'template',   'generator/template/index',  '', '', 1, 0, 'C', '0', '0', 'generator:template:list',   'code',          'admin', sysdate(), '', null, '模板管理菜单');
insert into sys_menu values('122',  '项目结构', '118', '4', 'structure',  'generator/structure/index', '', '', 1, 0, 'C', '0', '0', 'generator:structure:list',  'tree',          'admin', sysdate(), '', null, '项目结构菜单');
insert into sys_menu values('123',  '功能模块', '118', '5', 'module',     'generator/module/index',    '', '', 1, 0, 'C', '0', '0', 'generator:module:list',     'tree-table',    'admin', sysdate(), '', null, '功能模块菜单');
insert into sys_menu values('124',  '代码片段', '118', '6', 'snippet',    'generator/snippet/index',   '', '', 1, 0, 'C', '0', '0', 'generator:snippet:list',    'list',          'admin', sysdate(), '', null, '代码片段菜单');
insert into sys_menu values('125',  '源码库管理', '118', '7', 'sourceProject', 'generator/sourceProject/index', '', '', 1, 0, 'C', '0', '0', 'generator:sourceProject:list', 'code', 'admin', sysdate(), '', null, '源码库管理菜单');
insert into sys_menu values('126',  '源码购买记录', '118', '8', 'sourcePurchase', 'generator/sourcePurchase/index', '', '', 1, 0, 'C', '0', '0', 'generator:sourcePurchase:list', 'money', 'admin', sysdate(), '', null, '源码购买记录菜单');
-- 三级菜单
insert into sys_menu values('500',  '操作日志', '108', '1', 'operlog',    'monitor/operlog/index',    '', '', 1, 0, 'C', '0', '0', 'monitor:operlog:list',    'form',          'admin', sysdate(), '', null, '操作日志菜单');
insert into sys_menu values('501',  '登录日志', '108', '2', 'logininfor', 'monitor/logininfor/index', '', '', 1, 0, 'C', '0', '0', 'monitor:logininfor:list', 'logininfor',    'admin', sysdate(), '', null, '登录日志菜单');
-- 用户管理按钮
insert into sys_menu values('1000', '用户查询', '100', '1',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1001', '用户新增', '100', '2',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1002', '用户修改', '100', '3',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1003', '用户删除', '100', '4',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:remove',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1004', '用户导出', '100', '5',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:export',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1005', '用户导入', '100', '6',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:import',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1006', '重置密码', '100', '7',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:user:resetPwd',       '#', 'admin', sysdate(), '', null, '');
-- 角色管理按钮
insert into sys_menu values('1007', '角色查询', '101', '1',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:role:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1008', '角色新增', '101', '2',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:role:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1009', '角色修改', '101', '3',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:role:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1010', '角色删除', '101', '4',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:role:remove',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1011', '角色导出', '101', '5',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:role:export',         '#', 'admin', sysdate(), '', null, '');
-- 菜单管理按钮
insert into sys_menu values('1012', '菜单查询', '102', '1',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:menu:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1013', '菜单新增', '102', '2',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:menu:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1014', '菜单修改', '102', '3',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:menu:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1015', '菜单删除', '102', '4',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:menu:remove',         '#', 'admin', sysdate(), '', null, '');
-- 部门管理按钮
insert into sys_menu values('1016', '部门查询', '103', '1',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:dept:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1017', '部门新增', '103', '2',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:dept:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1018', '部门修改', '103', '3',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:dept:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1019', '部门删除', '103', '4',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:dept:remove',         '#', 'admin', sysdate(), '', null, '');
-- 岗位管理按钮
insert into sys_menu values('1020', '岗位查询', '104', '1',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:post:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1021', '岗位新增', '104', '2',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:post:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1022', '岗位修改', '104', '3',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:post:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1023', '岗位删除', '104', '4',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:post:remove',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1024', '岗位导出', '104', '5',  '', '', '', '', 1, 0, 'F', '0', '0', 'system:post:export',         '#', 'admin', sysdate(), '', null, '');
-- 字典管理按钮
insert into sys_menu values('1025', '字典查询', '105', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:dict:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1026', '字典新增', '105', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:dict:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1027', '字典修改', '105', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:dict:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1028', '字典删除', '105', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:dict:remove',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1029', '字典导出', '105', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:dict:export',         '#', 'admin', sysdate(), '', null, '');
-- 参数设置按钮
insert into sys_menu values('1030', '参数查询', '106', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:config:query',        '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1031', '参数新增', '106', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:config:add',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1032', '参数修改', '106', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:config:edit',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1033', '参数删除', '106', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:config:remove',       '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1034', '参数导出', '106', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:config:export',       '#', 'admin', sysdate(), '', null, '');
-- 通知公告按钮
insert into sys_menu values('1035', '公告查询', '107', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:notice:query',        '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1036', '公告新增', '107', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:notice:add',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1037', '公告修改', '107', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:notice:edit',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1038', '公告删除', '107', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:notice:remove',       '#', 'admin', sysdate(), '', null, '');
-- 操作日志按钮
insert into sys_menu values('1039', '操作查询', '500', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:operlog:query',      '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1040', '操作删除', '500', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:operlog:remove',     '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1041', '日志导出', '500', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:operlog:export',     '#', 'admin', sysdate(), '', null, '');
-- 登录日志按钮
insert into sys_menu values('1042', '登录查询', '501', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:logininfor:query',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1043', '登录删除', '501', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:logininfor:remove',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1044', '日志导出', '501', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:logininfor:export',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1045', '账户解锁', '501', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:logininfor:unlock',  '#', 'admin', sysdate(), '', null, '');
-- 在线用户按钮
insert into sys_menu values('1046', '在线查询', '109', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:online:query',       '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1047', '批量强退', '109', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:online:batchLogout', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1048', '单条强退', '109', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:online:forceLogout', '#', 'admin', sysdate(), '', null, '');
-- 定时任务按钮
insert into sys_menu values('1049', '任务查询', '110', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:job:query',          '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1050', '任务新增', '110', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:job:add',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1051', '任务修改', '110', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:job:edit',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1052', '任务删除', '110', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:job:remove',         '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1053', '状态修改', '110', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:job:changeStatus',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1054', '任务导出', '110', '6', '#', '', '', '', 1, 0, 'F', '0', '0', 'monitor:job:export',         '#', 'admin', sysdate(), '', null, '');
-- 代码生成按钮
insert into sys_menu values('1055', '生成查询', '116', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'tool:gen:query',             '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1056', '生成修改', '116', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'tool:gen:edit',              '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1057', '生成删除', '116', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'tool:gen:remove',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1058', '导入代码', '116', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'tool:gen:import',            '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1059', '预览代码', '116', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'tool:gen:preview',           '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1060', '生成代码', '116', '6', '#', '', '', '', 1, 0, 'F', '0', '0', 'tool:gen:code',              '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-项目管理按钮
insert into sys_menu values('1061', '项目查询', '119', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:query',    '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1062', '项目新增', '119', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:add',      '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1063', '项目修改', '119', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:edit',     '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1064', '项目删除', '119', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:remove',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1065', '项目导出', '119', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:export',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1066', '代码预览', '119', '6', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:preview',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1067', '代码下载', '119', '7', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:project:download', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1068', '项目表查询', '119', '8', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:list',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1069', '项目表详情', '119', '9', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:query', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1070', '项目表新增', '119', '10', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:add',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1071', '项目表修改', '119', '11', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:edit', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1072', '项目表删除', '119', '12', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:remove', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1073', '按项目移除表', '119', '13', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:removeByProjectId', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1074', '按表移除项目', '119', '14', '#', '', '', '', 1, 0, 'F', '0', '0', 'system:projectTable:removeByTableId', '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-数据源管理按钮
insert into sys_menu values('1075', '数据源查询', '120', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:datasource:query', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1076', '数据源新增', '120', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:datasource:add',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1077', '数据源修改', '120', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:datasource:edit',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1078', '数据源删除', '120', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:datasource:remove','#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1079', '数据源导出', '120', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:datasource:export','#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1080', '连接测试', '120', '6', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:datasource:test',   '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-模板管理按钮
insert into sys_menu values('1081', '模板查询', '121', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:template:query',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1082', '模板新增', '121', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:template:add',     '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1083', '模板修改', '121', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:template:edit',    '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1084', '模板删除', '121', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:template:remove',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1085', '模板导出', '121', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:template:export',  '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-项目结构按钮
insert into sys_menu values('1086', '结构查询', '122', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:structure:query',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1087', '结构新增', '122', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:structure:add',    '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1088', '结构修改', '122', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:structure:edit',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1089', '结构删除', '122', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:structure:remove', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1090', '结构导出', '122', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:structure:export', '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-功能模块按钮
insert into sys_menu values('1091', '模块查询', '123', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:module:query',     '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1092', '模块新增', '123', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:module:add',       '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1093', '模块修改', '123', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:module:edit',      '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1094', '模块删除', '123', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:module:remove',    '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1095', '模块导出', '123', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:module:export',    '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-代码片段按钮
insert into sys_menu values('1096', '片段查询', '124', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:snippet:query',    '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1097', '片段新增', '124', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:snippet:add',      '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1098', '片段修改', '124', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:snippet:edit',     '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1099', '片段删除', '124', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:snippet:remove',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1100', '片段导出', '124', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:snippet:export',   '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-源码库管理按钮
insert into sys_menu values('1101', '源码查询', '125', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourceProject:query',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1102', '源码新增', '125', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourceProject:add',    '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1103', '源码修改', '125', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourceProject:edit',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1104', '源码删除', '125', '4', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourceProject:remove', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1105', '源码导出', '125', '5', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourceProject:export', '#', 'admin', sysdate(), '', null, '');
-- 代码生成平台-源码购买记录按钮
insert into sys_menu values('1106', '购买查询', '126', '1', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourcePurchase:query',  '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1107', '购买修改', '126', '2', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourcePurchase:edit',   '#', 'admin', sysdate(), '', null, '');
insert into sys_menu values('1108', '购买导出', '126', '3', '#', '', '', '', 1, 0, 'F', '0', '0', 'generator:sourcePurchase:export', '#', 'admin', sysdate(), '', null, '');


-- ----------------------------
-- 6、用户和角色关联表  用户N-1角色
-- ----------------------------
drop table if exists sys_user_role;
create table sys_user_role (
  user_id   bigint(20) not null comment '用户ID',
  role_id   bigint(20) not null comment '角色ID',
  primary key(user_id, role_id)
) engine=innodb comment = '用户和角色关联表';

-- ----------------------------
-- 初始化-用户和角色关联表数据
-- ----------------------------
insert into sys_user_role values ('1', '1');
insert into sys_user_role values ('2', '2');


-- ----------------------------
-- 7、角色和菜单关联表  角色1-N菜单
-- ----------------------------
drop table if exists sys_role_menu;
create table sys_role_menu (
  role_id   bigint(20) not null comment '角色ID',
  menu_id   bigint(20) not null comment '菜单ID',
  primary key(role_id, menu_id)
) engine=innodb comment = '角色和菜单关联表';

-- ----------------------------
-- 初始化-角色和菜单关联表数据
-- ----------------------------
insert into sys_role_menu values ('2', '1');
insert into sys_role_menu values ('2', '2');
insert into sys_role_menu values ('2', '3');
insert into sys_role_menu values ('2', '4');
insert into sys_role_menu values ('2', '100');
insert into sys_role_menu values ('2', '101');
insert into sys_role_menu values ('2', '102');
insert into sys_role_menu values ('2', '103');
insert into sys_role_menu values ('2', '104');
insert into sys_role_menu values ('2', '105');
insert into sys_role_menu values ('2', '106');
insert into sys_role_menu values ('2', '107');
insert into sys_role_menu values ('2', '108');
insert into sys_role_menu values ('2', '109');
insert into sys_role_menu values ('2', '110');
insert into sys_role_menu values ('2', '111');
insert into sys_role_menu values ('2', '112');
insert into sys_role_menu values ('2', '113');
insert into sys_role_menu values ('2', '114');
insert into sys_role_menu values ('2', '115');
insert into sys_role_menu values ('2', '116');
insert into sys_role_menu values ('2', '117');
insert into sys_role_menu values ('2', '118');
insert into sys_role_menu values ('2', '119');
insert into sys_role_menu values ('2', '120');
insert into sys_role_menu values ('2', '121');
insert into sys_role_menu values ('2', '122');
insert into sys_role_menu values ('2', '123');
insert into sys_role_menu values ('2', '124');
insert into sys_role_menu values ('2', '500');
insert into sys_role_menu values ('2', '501');
insert into sys_role_menu values ('2', '1000');
insert into sys_role_menu values ('2', '1001');
insert into sys_role_menu values ('2', '1002');
insert into sys_role_menu values ('2', '1003');
insert into sys_role_menu values ('2', '1004');
insert into sys_role_menu values ('2', '1005');
insert into sys_role_menu values ('2', '1006');
insert into sys_role_menu values ('2', '1007');
insert into sys_role_menu values ('2', '1008');
insert into sys_role_menu values ('2', '1009');
insert into sys_role_menu values ('2', '1010');
insert into sys_role_menu values ('2', '1011');
insert into sys_role_menu values ('2', '1012');
insert into sys_role_menu values ('2', '1013');
insert into sys_role_menu values ('2', '1014');
insert into sys_role_menu values ('2', '1015');
insert into sys_role_menu values ('2', '1016');
insert into sys_role_menu values ('2', '1017');
insert into sys_role_menu values ('2', '1018');
insert into sys_role_menu values ('2', '1019');
insert into sys_role_menu values ('2', '1020');
insert into sys_role_menu values ('2', '1021');
insert into sys_role_menu values ('2', '1022');
insert into sys_role_menu values ('2', '1023');
insert into sys_role_menu values ('2', '1024');
insert into sys_role_menu values ('2', '1025');
insert into sys_role_menu values ('2', '1026');
insert into sys_role_menu values ('2', '1027');
insert into sys_role_menu values ('2', '1028');
insert into sys_role_menu values ('2', '1029');
insert into sys_role_menu values ('2', '1030');
insert into sys_role_menu values ('2', '1031');
insert into sys_role_menu values ('2', '1032');
insert into sys_role_menu values ('2', '1033');
insert into sys_role_menu values ('2', '1034');
insert into sys_role_menu values ('2', '1035');
insert into sys_role_menu values ('2', '1036');
insert into sys_role_menu values ('2', '1037');
insert into sys_role_menu values ('2', '1038');
insert into sys_role_menu values ('2', '1039');
insert into sys_role_menu values ('2', '1040');
insert into sys_role_menu values ('2', '1041');
insert into sys_role_menu values ('2', '1042');
insert into sys_role_menu values ('2', '1043');
insert into sys_role_menu values ('2', '1044');
insert into sys_role_menu values ('2', '1045');
insert into sys_role_menu values ('2', '1046');
insert into sys_role_menu values ('2', '1047');
insert into sys_role_menu values ('2', '1048');
insert into sys_role_menu values ('2', '1049');
insert into sys_role_menu values ('2', '1050');
insert into sys_role_menu values ('2', '1051');
insert into sys_role_menu values ('2', '1052');
insert into sys_role_menu values ('2', '1053');
insert into sys_role_menu values ('2', '1054');
insert into sys_role_menu values ('2', '1055');
insert into sys_role_menu values ('2', '1056');
insert into sys_role_menu values ('2', '1057');
insert into sys_role_menu values ('2', '1058');
insert into sys_role_menu values ('2', '1059');
insert into sys_role_menu values ('2', '1060');
insert into sys_role_menu values ('2', '1061');
insert into sys_role_menu values ('2', '1062');
insert into sys_role_menu values ('2', '1063');
insert into sys_role_menu values ('2', '1064');
insert into sys_role_menu values ('2', '1065');
insert into sys_role_menu values ('2', '1066');
insert into sys_role_menu values ('2', '1067');
insert into sys_role_menu values ('2', '1068');
insert into sys_role_menu values ('2', '1069');
insert into sys_role_menu values ('2', '1070');
insert into sys_role_menu values ('2', '1071');
insert into sys_role_menu values ('2', '1072');
insert into sys_role_menu values ('2', '1073');
insert into sys_role_menu values ('2', '1074');
insert into sys_role_menu values ('2', '1075');
insert into sys_role_menu values ('2', '1076');
insert into sys_role_menu values ('2', '1077');
insert into sys_role_menu values ('2', '1078');
insert into sys_role_menu values ('2', '1079');
insert into sys_role_menu values ('2', '1080');
insert into sys_role_menu values ('2', '1081');
insert into sys_role_menu values ('2', '1082');
insert into sys_role_menu values ('2', '1083');
insert into sys_role_menu values ('2', '1084');
insert into sys_role_menu values ('2', '1085');
insert into sys_role_menu values ('2', '1086');
insert into sys_role_menu values ('2', '1087');
insert into sys_role_menu values ('2', '1088');
insert into sys_role_menu values ('2', '1089');
insert into sys_role_menu values ('2', '1090');
insert into sys_role_menu values ('2', '1091');
insert into sys_role_menu values ('2', '1092');
insert into sys_role_menu values ('2', '1093');
insert into sys_role_menu values ('2', '1094');
insert into sys_role_menu values ('2', '1095');
insert into sys_role_menu values ('2', '1096');
insert into sys_role_menu values ('2', '1097');
insert into sys_role_menu values ('2', '1098');
insert into sys_role_menu values ('2', '1099');
insert into sys_role_menu values ('2', '1100');

-- ----------------------------
-- 8、角色和部门关联表  角色1-N部门
-- ----------------------------
drop table if exists sys_role_dept;
create table sys_role_dept (
  role_id   bigint(20) not null comment '角色ID',
  dept_id   bigint(20) not null comment '部门ID',
  primary key(role_id, dept_id)
) engine=innodb comment = '角色和部门关联表';

-- ----------------------------
-- 初始化-角色和部门关联表数据
-- ----------------------------
insert into sys_role_dept values ('2', '100');
insert into sys_role_dept values ('2', '101');
insert into sys_role_dept values ('2', '105');


-- ----------------------------
-- 9、用户与岗位关联表  用户1-N岗位
-- ----------------------------
drop table if exists sys_user_post;
create table sys_user_post
(
  user_id   bigint(20) not null comment '用户ID',
  post_id   bigint(20) not null comment '岗位ID',
  primary key (user_id, post_id)
) engine=innodb comment = '用户与岗位关联表';

-- ----------------------------
-- 初始化-用户与岗位关联表数据
-- ----------------------------
insert into sys_user_post values ('1', '1');
insert into sys_user_post values ('2', '2');


-- ----------------------------
-- 10、操作日志记录
-- ----------------------------
drop table if exists sys_oper_log;
create table sys_oper_log (
  oper_id           bigint(20)      not null auto_increment    comment '日志主键',
  title             varchar(50)     default ''                 comment '模块标题',
  business_type     int(2)          default 0                  comment '业务类型（0其它 1新增 2修改 3删除）',
  method            varchar(200)    default ''                 comment '方法名称',
  request_method    varchar(10)     default ''                 comment '请求方式',
  operator_type     int(1)          default 0                  comment '操作类别（0其它 1后台用户 2手机端用户）',
  oper_name         varchar(50)     default ''                 comment '操作人员',
  dept_name         varchar(50)     default ''                 comment '部门名称',
  oper_url          varchar(255)    default ''                 comment '请求URL',
  oper_ip           varchar(128)    default ''                 comment '主机地址',
  oper_location     varchar(255)    default ''                 comment '操作地点',
  oper_param        varchar(2000)   default ''                 comment '请求参数',
  json_result       varchar(2000)   default ''                 comment '返回参数',
  status            int(1)          default 0                  comment '操作状态（0正常 1异常）',
  error_msg         varchar(2000)   default ''                 comment '错误消息',
  oper_time         datetime                                   comment '操作时间',
  cost_time         bigint(20)      default 0                  comment '消耗时间',
  primary key (oper_id),
  key idx_sys_oper_log_bt (business_type),
  key idx_sys_oper_log_s  (status),
  key idx_sys_oper_log_ot (oper_time)
) engine=innodb auto_increment=100 comment = '操作日志记录';


-- ----------------------------
-- 11、字典类型表
-- ----------------------------
drop table if exists sys_dict_type;
create table sys_dict_type
(
  dict_id          bigint(20)      not null auto_increment    comment '字典主键',
  dict_name        varchar(100)    default ''                 comment '字典名称',
  dict_type        varchar(100)    default ''                 comment '字典类型',
  status           char(1)         default '0'                comment '状态（0正常 1停用）',
  create_by        varchar(64)     default ''                 comment '创建者',
  create_time      datetime                                   comment '创建时间',
  update_by        varchar(64)     default ''                 comment '更新者',
  update_time      datetime                                   comment '更新时间',
  remark           varchar(500)    default null               comment '备注',
  primary key (dict_id),
  unique (dict_type)
) engine=innodb auto_increment=100 comment = '字典类型表';

insert into sys_dict_type values(1,  '用户性别', 'sys_user_sex',        '0', 'admin', sysdate(), '', null, '用户性别列表');
insert into sys_dict_type values(2,  '菜单状态', 'sys_show_hide',       '0', 'admin', sysdate(), '', null, '菜单状态列表');
insert into sys_dict_type values(3,  '系统开关', 'sys_normal_disable',  '0', 'admin', sysdate(), '', null, '系统开关列表');
insert into sys_dict_type values(4,  '任务状态', 'sys_job_status',      '0', 'admin', sysdate(), '', null, '任务状态列表');
insert into sys_dict_type values(5,  '任务分组', 'sys_job_group',       '0', 'admin', sysdate(), '', null, '任务分组列表');
insert into sys_dict_type values(6,  '系统是否', 'sys_yes_no',          '0', 'admin', sysdate(), '', null, '系统是否列表');
insert into sys_dict_type values(7,  '通知类型', 'sys_notice_type',     '0', 'admin', sysdate(), '', null, '通知类型列表');
insert into sys_dict_type values(8,  '通知状态', 'sys_notice_status',   '0', 'admin', sysdate(), '', null, '通知状态列表');
insert into sys_dict_type values(9,  '操作类型', 'sys_oper_type',       '0', 'admin', sysdate(), '', null, '操作类型列表');
insert into sys_dict_type values(10, '系统状态', 'sys_common_status',   '0', 'admin', sysdate(), '', null, '登录状态列表');
insert into sys_dict_type values(11, '源码分类', 'source_project_category', '0', 'admin', sysdate(), '', null, '源码库分类列表');


-- ----------------------------
-- 12、字典数据表
-- ----------------------------
drop table if exists sys_dict_data;
create table sys_dict_data
(
  dict_code        bigint(20)      not null auto_increment    comment '字典编码',
  dict_sort        int(4)          default 0                  comment '字典排序',
  dict_label       varchar(100)    default ''                 comment '字典标签',
  dict_value       varchar(100)    default ''                 comment '字典键值',
  dict_type        varchar(100)    default ''                 comment '字典类型',
  css_class        varchar(100)    default null               comment '样式属性（其他样式扩展）',
  list_class       varchar(100)    default null               comment '表格回显样式',
  is_default       char(1)         default 'N'                comment '是否默认（Y是 N否）',
  status           char(1)         default '0'                comment '状态（0正常 1停用）',
  create_by        varchar(64)     default ''                 comment '创建者',
  create_time      datetime                                   comment '创建时间',
  update_by        varchar(64)     default ''                 comment '更新者',
  update_time      datetime                                   comment '更新时间',
  remark           varchar(500)    default null               comment '备注',
  primary key (dict_code)
) engine=innodb auto_increment=100 comment = '字典数据表';

insert into sys_dict_data values(1,  1,  '男',       '0',       'sys_user_sex',        '',   '',        'Y', '0', 'admin', sysdate(), '', null, '性别男');
insert into sys_dict_data values(2,  2,  '女',       '1',       'sys_user_sex',        '',   '',        'N', '0', 'admin', sysdate(), '', null, '性别女');
insert into sys_dict_data values(3,  3,  '未知',     '2',       'sys_user_sex',        '',   '',        'N', '0', 'admin', sysdate(), '', null, '性别未知');
insert into sys_dict_data values(4,  1,  '显示',     '0',       'sys_show_hide',       '',   'primary', 'Y', '0', 'admin', sysdate(), '', null, '显示菜单');
insert into sys_dict_data values(5,  2,  '隐藏',     '1',       'sys_show_hide',       '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '隐藏菜单');
insert into sys_dict_data values(6,  1,  '正常',     '0',       'sys_normal_disable',  '',   'primary', 'Y', '0', 'admin', sysdate(), '', null, '正常状态');
insert into sys_dict_data values(7,  2,  '停用',     '1',       'sys_normal_disable',  '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '停用状态');
insert into sys_dict_data values(8,  1,  '正常',     '0',       'sys_job_status',      '',   'primary', 'Y', '0', 'admin', sysdate(), '', null, '正常状态');
insert into sys_dict_data values(9,  2,  '暂停',     '1',       'sys_job_status',      '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '停用状态');
insert into sys_dict_data values(10, 1,  '默认',     'DEFAULT', 'sys_job_group',       '',   '',        'Y', '0', 'admin', sysdate(), '', null, '默认分组');
insert into sys_dict_data values(11, 2,  '系统',     'SYSTEM',  'sys_job_group',       '',   '',        'N', '0', 'admin', sysdate(), '', null, '系统分组');
insert into sys_dict_data values(12, 1,  '是',       'Y',       'sys_yes_no',          '',   'primary', 'Y', '0', 'admin', sysdate(), '', null, '系统默认是');
insert into sys_dict_data values(13, 2,  '否',       'N',       'sys_yes_no',          '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '系统默认否');
insert into sys_dict_data values(14, 1,  '通知',     '1',       'sys_notice_type',     '',   'warning', 'Y', '0', 'admin', sysdate(), '', null, '通知');
insert into sys_dict_data values(15, 2,  '公告',     '2',       'sys_notice_type',     '',   'success', 'N', '0', 'admin', sysdate(), '', null, '公告');
insert into sys_dict_data values(16, 1,  '正常',     '0',       'sys_notice_status',   '',   'primary', 'Y', '0', 'admin', sysdate(), '', null, '正常状态');
insert into sys_dict_data values(17, 2,  '关闭',     '1',       'sys_notice_status',   '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '关闭状态');
insert into sys_dict_data values(18, 99, '其他',     '0',       'sys_oper_type',       '',   'info',    'N', '0', 'admin', sysdate(), '', null, '其他操作');
insert into sys_dict_data values(19, 1,  '新增',     '1',       'sys_oper_type',       '',   'info',    'N', '0', 'admin', sysdate(), '', null, '新增操作');
insert into sys_dict_data values(20, 2,  '修改',     '2',       'sys_oper_type',       '',   'info',    'N', '0', 'admin', sysdate(), '', null, '修改操作');
insert into sys_dict_data values(21, 3,  '删除',     '3',       'sys_oper_type',       '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '删除操作');
insert into sys_dict_data values(22, 4,  '授权',     '4',       'sys_oper_type',       '',   'primary', 'N', '0', 'admin', sysdate(), '', null, '授权操作');
insert into sys_dict_data values(23, 5,  '导出',     '5',       'sys_oper_type',       '',   'warning', 'N', '0', 'admin', sysdate(), '', null, '导出操作');
insert into sys_dict_data values(24, 6,  '导入',     '6',       'sys_oper_type',       '',   'warning', 'N', '0', 'admin', sysdate(), '', null, '导入操作');
insert into sys_dict_data values(25, 7,  '强退',     '7',       'sys_oper_type',       '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '强退操作');
insert into sys_dict_data values(26, 8,  '生成代码', '8',       'sys_oper_type',       '',   'warning', 'N', '0', 'admin', sysdate(), '', null, '生成操作');
insert into sys_dict_data values(27, 9,  '清空数据', '9',       'sys_oper_type',       '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '清空操作');
insert into sys_dict_data values(28, 1,  '成功',     '0',       'sys_common_status',   '',   'primary', 'N', '0', 'admin', sysdate(), '', null, '正常状态');
insert into sys_dict_data values(29, 2,  '失败',     '1',       'sys_common_status',   '',   'danger',  'N', '0', 'admin', sysdate(), '', null, '停用状态');
insert into sys_dict_data values(30, 1,  '企业管理系统', 'enterprise',    'source_project_category', '', 'primary', 'Y', '0', 'admin', sysdate(), '', null, '源码分类-企业管理系统');
insert into sys_dict_data values(31, 2,  '商城系统',     'mall',          'source_project_category', '', 'success', 'N', '0', 'admin', sysdate(), '', null, '源码分类-商城系统');
insert into sys_dict_data values(32, 3,  'OA 办公',      'office',        'source_project_category', '', 'info',    'N', '0', 'admin', sysdate(), '', null, '源码分类-OA 办公');
insert into sys_dict_data values(33, 4,  '低代码平台',   'lowcode',       'source_project_category', '', 'warning', 'N', '0', 'admin', sysdate(), '', null, '源码分类-低代码平台');
insert into sys_dict_data values(34, 5,  '微服务脚手架', 'microservice',  'source_project_category', '', 'danger',  'N', '0', 'admin', sysdate(), '', null, '源码分类-微服务脚手架');


-- ----------------------------
-- 13、参数配置表
-- ----------------------------
drop table if exists sys_config;
create table sys_config (
  config_id         int(5)          not null auto_increment    comment '参数主键',
  config_name       varchar(100)    default ''                 comment '参数名称',
  config_key        varchar(100)    default ''                 comment '参数键名',
  config_value      varchar(500)    default ''                 comment '参数键值',
  config_type       char(1)         default 'N'                comment '系统内置（Y是 N否）',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time       datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  remark            varchar(500)    default null               comment '备注',
  primary key (config_id)
) engine=innodb auto_increment=100 comment = '参数配置表';

insert into sys_config values(1, '主框架页-默认皮肤样式名称',     'sys.index.skinName',            'skin-blue',     'Y', 'admin', sysdate(), '', null, '蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow' );
insert into sys_config values(2, '用户管理-账号初始密码',         'sys.user.initPassword',         '123456',        'Y', 'admin', sysdate(), '', null, '初始化密码 123456' );
insert into sys_config values(3, '主框架页-侧边栏主题',           'sys.index.sideTheme',           'theme-dark',    'Y', 'admin', sysdate(), '', null, '深色主题theme-dark，浅色主题theme-light' );
insert into sys_config values(4, '账号自助-验证码开关',           'sys.account.captchaEnabled',    'true',          'Y', 'admin', sysdate(), '', null, '是否开启验证码功能（true开启，false关闭）');
insert into sys_config values(5, '账号自助-是否开启用户注册功能', 'sys.account.registerUser',      'false',         'Y', 'admin', sysdate(), '', null, '是否开启注册用户功能（true开启，false关闭）');
insert into sys_config values(6, '用户登录-黑名单列表',           'sys.login.blackIPList',         '',              'Y', 'admin', sysdate(), '', null, '设置登录IP黑名单限制，多个匹配项以;分隔，支持匹配（*通配、网段）');


-- ----------------------------
-- 14、系统访问记录
-- ----------------------------
drop table if exists sys_logininfor;
create table sys_logininfor (
  info_id        bigint(20)     not null auto_increment   comment '访问ID',
  user_name      varchar(50)    default ''                comment '用户账号',
  ipaddr         varchar(128)   default ''                comment '登录IP地址',
  login_location varchar(255)   default ''                comment '登录地点',
  browser        varchar(50)    default ''                comment '浏览器类型',
  os             varchar(50)    default ''                comment '操作系统',
  status         char(1)        default '0'               comment '登录状态（0成功 1失败）',
  msg            varchar(255)   default ''                comment '提示消息',
  login_time     datetime                                 comment '访问时间',
  primary key (info_id),
  key idx_sys_logininfor_s  (status),
  key idx_sys_logininfor_lt (login_time)
) engine=innodb auto_increment=100 comment = '系统访问记录';


-- ----------------------------
-- 15、定时任务调度表
-- ----------------------------
drop table if exists sys_job;
create table sys_job (
  job_id              bigint(20)    not null auto_increment    comment '任务ID',
  job_name            varchar(64)   default ''                 comment '任务名称',
  job_group           varchar(64)   default 'DEFAULT'          comment '任务组名',
  invoke_target       varchar(500)  not null                   comment '调用目标字符串',
  cron_expression     varchar(255)  default ''                 comment 'cron执行表达式',
  misfire_policy      varchar(20)   default '3'                comment '计划执行错误策略（1立即执行 2执行一次 3放弃执行）',
  concurrent          char(1)       default '1'                comment '是否并发执行（0允许 1禁止）',
  status              char(1)       default '0'                comment '状态（0正常 1暂停）',
  create_by           varchar(64)   default ''                 comment '创建者',
  create_time         datetime                                 comment '创建时间',
  update_by           varchar(64)   default ''                 comment '更新者',
  update_time         datetime                                 comment '更新时间',
  remark              varchar(500)  default ''                 comment '备注信息',
  primary key (job_id, job_name, job_group)
) engine=innodb auto_increment=100 comment = '定时任务调度表';

insert into sys_job values(1, '系统默认（无参）', 'DEFAULT', 'ryTask.ryNoParams',        '0/10 * * * * ?', '3', '1', '1', 'admin', sysdate(), '', null, '');
insert into sys_job values(2, '系统默认（有参）', 'DEFAULT', 'ryTask.ryParams(\'ry\')',  '0/15 * * * * ?', '3', '1', '1', 'admin', sysdate(), '', null, '');
insert into sys_job values(3, '系统默认（多参）', 'DEFAULT', 'ryTask.ryMultipleParams(\'ry\', true, 2000L, 316.50D, 100)',  '0/20 * * * * ?', '3', '1', '1', 'admin', sysdate(), '', null, '');


-- ----------------------------
-- 16、定时任务调度日志表
-- ----------------------------
drop table if exists sys_job_log;
create table sys_job_log (
  job_log_id          bigint(20)     not null auto_increment    comment '任务日志ID',
  job_name            varchar(64)    not null                   comment '任务名称',
  job_group           varchar(64)    not null                   comment '任务组名',
  invoke_target       varchar(500)   not null                   comment '调用目标字符串',
  job_message         varchar(500)                              comment '日志信息',
  status              char(1)        default '0'                comment '执行状态（0正常 1失败）',
  exception_info      varchar(2000)  default ''                 comment '异常信息',
  create_time         datetime                                  comment '创建时间',
  primary key (job_log_id)
) engine=innodb comment = '定时任务调度日志表';


-- ----------------------------
-- 17、通知公告表
-- ----------------------------
drop table if exists sys_notice;
create table sys_notice (
  notice_id         int(4)          not null auto_increment    comment '公告ID',
  notice_title      varchar(50)     not null                   comment '公告标题',
  notice_type       char(1)         not null                   comment '公告类型（1通知 2公告）',
  notice_content    longblob        default null               comment '公告内容',
  status            char(1)         default '0'                comment '公告状态（0正常 1关闭）',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time       datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  remark            varchar(255)    default null               comment '备注',
  primary key (notice_id)
) engine=innodb auto_increment=10 comment = '通知公告表';

-- ----------------------------
-- 初始化-公告信息表数据
-- ----------------------------
insert into sys_notice values('1', '温馨提醒：2018-07-01 若依新版本发布啦', '2', '新版本内容', '0', 'admin', sysdate(), '', null, '管理员');
insert into sys_notice values('2', '维护通知：2018-07-01 若依系统凌晨维护', '1', '维护内容',   '0', 'admin', sysdate(), '', null, '管理员');


-- ----------------------------
-- 18、代码生成业务表
-- ----------------------------
drop table if exists gen_table;
create table gen_table (
  table_id          bigint(20)      not null auto_increment    comment '编号',
  table_name        varchar(200)    default ''                 comment '表名称',
  table_comment     varchar(500)    default ''                 comment '表描述',
  sub_table_name    varchar(64)     default null               comment '关联子表的表名',
  sub_table_fk_name varchar(64)     default null               comment '子表关联的外键名',
  class_name        varchar(100)    default ''                 comment '实体类名称',
  tpl_category      varchar(200)    default 'crud'             comment '使用的模板（crud单表操作 tree树表操作）',
  tpl_web_type      varchar(30)     default ''                 comment '前端模板类型（element-ui模版 element-plus模版）',
  package_name      varchar(100)                               comment '生成包路径',
  module_name       varchar(30)                                comment '生成模块名',
  business_name     varchar(30)                                comment '生成业务名',
  function_name     varchar(50)                                comment '生成功能名',
  function_author   varchar(50)                                comment '生成功能作者',
  gen_type          char(1)         default '0'                comment '生成代码方式（0zip压缩包 1自定义路径）',
  gen_path          varchar(200)    default '/'                comment '生成路径（不填默认项目路径）',
  create_table_sql  longtext                                   comment '建表SQL语句',
  admin_menu_name   varchar(100)     default ''                 comment '后台菜单名称',
  allow_add         char(1)          default '1'                comment '是否允许新增（1是 0否）',
  allow_edit        char(1)          default '1'                comment '是否允许修改（1是 0否）',
  allow_remove      char(1)          default '1'                comment '是否允许删除（1是 0否）',
  remove_type       varchar(20)      default 'physical'         comment '删除方式（none不允许 logical逻辑删除 physical物理删除）',
  operation_note    varchar(500)     default ''                 comment '操作能力说明',
  options           varchar(1000)                              comment '其它生成选项',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time 	    datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  remark            varchar(500)    default null               comment '备注',
  primary key (table_id)
) engine=innodb auto_increment=1 comment = '代码生成业务表';


-- ----------------------------
-- 19、代码生成业务表字段
-- ----------------------------
drop table if exists gen_table_column;
create table gen_table_column (
  column_id         bigint(20)      not null auto_increment    comment '编号',
  table_id          bigint(20)                                 comment '归属表编号',
  column_name       varchar(200)                               comment '列名称',
  column_comment    varchar(500)                               comment '列描述',
  column_type       varchar(100)                               comment '列类型',
  java_type         varchar(500)                               comment 'JAVA类型',
  java_field        varchar(200)                               comment 'JAVA字段名',
  is_pk             char(1)                                    comment '是否主键（1是）',
  is_increment      char(1)                                    comment '是否自增（1是）',
  is_required       char(1)                                    comment '是否必填（1是）',
  is_insert         char(1)                                    comment '是否为插入字段（1是）',
  is_edit           char(1)                                    comment '是否编辑字段（1是）',
  is_list           char(1)                                    comment '是否列表字段（1是）',
  is_query          char(1)                                    comment '是否查询字段（1是）',
  query_type        varchar(200)    default 'EQ'               comment '查询方式（等于、不等于、大于、小于、范围）',
  html_type         varchar(200)                               comment '显示类型（文本框、文本域、下拉框、复选框、单选框、日期控件）',
  dict_type         varchar(200)    default ''                 comment '字典类型',
  sort              int                                        comment '排序',
  create_by         varchar(64)     default ''                 comment '创建者',
  create_time 	    datetime                                   comment '创建时间',
  update_by         varchar(64)     default ''                 comment '更新者',
  update_time       datetime                                   comment '更新时间',
  primary key (column_id)
) engine=innodb auto_increment=1 comment = '代码生成业务表字段';

-- =================================================
-- Quartz scheduler tables
-- Source: sql/quartz.sql
-- =================================================
DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;
DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;
DROP TABLE IF EXISTS QRTZ_LOCKS;
DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_TRIGGERS;
DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;
DROP TABLE IF EXISTS QRTZ_CALENDARS;

-- ----------------------------
-- 1、存储每一个已配置的 jobDetail 的详细信息
-- ----------------------------
create table QRTZ_JOB_DETAILS (
    sched_name           varchar(120)    not null            comment '调度名称',
    job_name             varchar(200)    not null            comment '任务名称',
    job_group            varchar(200)    not null            comment '任务组名',
    description          varchar(250)    null                comment '相关介绍',
    job_class_name       varchar(250)    not null            comment '执行任务类名称',
    is_durable           varchar(1)      not null            comment '是否持久化',
    is_nonconcurrent     varchar(1)      not null            comment '是否并发',
    is_update_data       varchar(1)      not null            comment '是否更新数据',
    requests_recovery    varchar(1)      not null            comment '是否接受恢复执行',
    job_data             blob            null                comment '存放持久化job对象',
    primary key (sched_name, job_name, job_group)
) engine=innodb comment = '任务详细信息表';

-- ----------------------------
-- 2、 存储已配置的 Trigger 的信息
-- ----------------------------
create table QRTZ_TRIGGERS (
    sched_name           varchar(120)    not null            comment '调度名称',
    trigger_name         varchar(200)    not null            comment '触发器的名字',
    trigger_group        varchar(200)    not null            comment '触发器所属组的名字',
    job_name             varchar(200)    not null            comment 'qrtz_job_details表job_name的外键',
    job_group            varchar(200)    not null            comment 'qrtz_job_details表job_group的外键',
    description          varchar(250)    null                comment '相关介绍',
    next_fire_time       bigint(13)      null                comment '上一次触发时间（毫秒）',
    prev_fire_time       bigint(13)      null                comment '下一次触发时间（默认为-1表示不触发）',
    priority             integer         null                comment '优先级',
    trigger_state        varchar(16)     not null            comment '触发器状态',
    trigger_type         varchar(8)      not null            comment '触发器的类型',
    start_time           bigint(13)      not null            comment '开始时间',
    end_time             bigint(13)      null                comment '结束时间',
    calendar_name        varchar(200)    null                comment '日程表名称',
    misfire_instr        smallint(2)     null                comment '补偿执行的策略',
    job_data             blob            null                comment '存放持久化job对象',
    primary key (sched_name, trigger_name, trigger_group),
    foreign key (sched_name, job_name, job_group) references QRTZ_JOB_DETAILS(sched_name, job_name, job_group)
) engine=innodb comment = '触发器详细信息表';

-- ----------------------------
-- 3、 存储简单的 Trigger，包括重复次数，间隔，以及已触发的次数
-- ----------------------------
create table QRTZ_SIMPLE_TRIGGERS (
    sched_name           varchar(120)    not null            comment '调度名称',
    trigger_name         varchar(200)    not null            comment 'qrtz_triggers表trigger_name的外键',
    trigger_group        varchar(200)    not null            comment 'qrtz_triggers表trigger_group的外键',
    repeat_count         bigint(7)       not null            comment '重复的次数统计',
    repeat_interval      bigint(12)      not null            comment '重复的间隔时间',
    times_triggered      bigint(10)      not null            comment '已经触发的次数',
    primary key (sched_name, trigger_name, trigger_group),
    foreign key (sched_name, trigger_name, trigger_group) references QRTZ_TRIGGERS(sched_name, trigger_name, trigger_group)
) engine=innodb comment = '简单触发器的信息表';

-- ----------------------------
-- 4、 存储 Cron Trigger，包括 Cron 表达式和时区信息
-- ----------------------------
create table QRTZ_CRON_TRIGGERS (
    sched_name           varchar(120)    not null            comment '调度名称',
    trigger_name         varchar(200)    not null            comment 'qrtz_triggers表trigger_name的外键',
    trigger_group        varchar(200)    not null            comment 'qrtz_triggers表trigger_group的外键',
    cron_expression      varchar(200)    not null            comment 'cron表达式',
    time_zone_id         varchar(80)                         comment '时区',
    primary key (sched_name, trigger_name, trigger_group),
    foreign key (sched_name, trigger_name, trigger_group) references QRTZ_TRIGGERS(sched_name, trigger_name, trigger_group)
) engine=innodb comment = 'Cron类型的触发器表';

-- ----------------------------
-- 5、 Trigger 作为 Blob 类型存储(用于 Quartz 用户用 JDBC 创建他们自己定制的 Trigger 类型，JobStore 并不知道如何存储实例的时候)
-- ----------------------------
create table QRTZ_BLOB_TRIGGERS (
    sched_name           varchar(120)    not null            comment '调度名称',
    trigger_name         varchar(200)    not null            comment 'qrtz_triggers表trigger_name的外键',
    trigger_group        varchar(200)    not null            comment 'qrtz_triggers表trigger_group的外键',
    blob_data            blob            null                comment '存放持久化Trigger对象',
    primary key (sched_name, trigger_name, trigger_group),
    foreign key (sched_name, trigger_name, trigger_group) references QRTZ_TRIGGERS(sched_name, trigger_name, trigger_group)
) engine=innodb comment = 'Blob类型的触发器表';

-- ----------------------------
-- 6、 以 Blob 类型存储存放日历信息， quartz可配置一个日历来指定一个时间范围
-- ----------------------------
create table QRTZ_CALENDARS (
    sched_name           varchar(120)    not null            comment '调度名称',
    calendar_name        varchar(200)    not null            comment '日历名称',
    calendar             blob            not null            comment '存放持久化calendar对象',
    primary key (sched_name, calendar_name)
) engine=innodb comment = '日历信息表';

-- ----------------------------
-- 7、 存储已暂停的 Trigger 组的信息
-- ----------------------------
create table QRTZ_PAUSED_TRIGGER_GRPS (
    sched_name           varchar(120)    not null            comment '调度名称',
    trigger_group        varchar(200)    not null            comment 'qrtz_triggers表trigger_group的外键',
    primary key (sched_name, trigger_group)
) engine=innodb comment = '暂停的触发器表';

-- ----------------------------
-- 8、 存储与已触发的 Trigger 相关的状态信息，以及相联 Job 的执行信息
-- ----------------------------
create table QRTZ_FIRED_TRIGGERS (
    sched_name           varchar(120)    not null            comment '调度名称',
    entry_id             varchar(95)     not null            comment '调度器实例id',
    trigger_name         varchar(200)    not null            comment 'qrtz_triggers表trigger_name的外键',
    trigger_group        varchar(200)    not null            comment 'qrtz_triggers表trigger_group的外键',
    instance_name        varchar(200)    not null            comment '调度器实例名',
    fired_time           bigint(13)      not null            comment '触发的时间',
    sched_time           bigint(13)      not null            comment '定时器制定的时间',
    priority             integer         not null            comment '优先级',
    state                varchar(16)     not null            comment '状态',
    job_name             varchar(200)    null                comment '任务名称',
    job_group            varchar(200)    null                comment '任务组名',
    is_nonconcurrent     varchar(1)      null                comment '是否并发',
    requests_recovery    varchar(1)      null                comment '是否接受恢复执行',
    primary key (sched_name, entry_id)
) engine=innodb comment = '已触发的触发器表';

-- ----------------------------
-- 9、 存储少量的有关 Scheduler 的状态信息，假如是用于集群中，可以看到其他的 Scheduler 实例
-- ----------------------------
create table QRTZ_SCHEDULER_STATE (
    sched_name           varchar(120)    not null            comment '调度名称',
    instance_name        varchar(200)    not null            comment '实例名称',
    last_checkin_time    bigint(13)      not null            comment '上次检查时间',
    checkin_interval     bigint(13)      not null            comment '检查间隔时间',
    primary key (sched_name, instance_name)
) engine=innodb comment = '调度器状态表';

-- ----------------------------
-- 10、 存储程序的悲观锁的信息(假如使用了悲观锁)
-- ----------------------------
create table QRTZ_LOCKS (
    sched_name           varchar(120)    not null            comment '调度名称',
    lock_name            varchar(40)     not null            comment '悲观锁名称',
    primary key (sched_name, lock_name)
) engine=innodb comment = '存储的悲观锁信息表';

-- ----------------------------
-- 11、 Quartz集群实现同步机制的行锁表
-- ----------------------------
create table QRTZ_SIMPROP_TRIGGERS (
    sched_name           varchar(120)    not null            comment '调度名称',
    trigger_name         varchar(200)    not null            comment 'qrtz_triggers表trigger_name的外键',
    trigger_group        varchar(200)    not null            comment 'qrtz_triggers表trigger_group的外键',
    str_prop_1           varchar(512)    null                comment 'String类型的trigger的第一个参数',
    str_prop_2           varchar(512)    null                comment 'String类型的trigger的第二个参数',
    str_prop_3           varchar(512)    null                comment 'String类型的trigger的第三个参数',
    int_prop_1           int             null                comment 'int类型的trigger的第一个参数',
    int_prop_2           int             null                comment 'int类型的trigger的第二个参数',
    long_prop_1          bigint          null                comment 'long类型的trigger的第一个参数',
    long_prop_2          bigint          null                comment 'long类型的trigger的第二个参数',
    dec_prop_1           numeric(13,4)   null                comment 'decimal类型的trigger的第一个参数',
    dec_prop_2           numeric(13,4)   null                comment 'decimal类型的trigger的第二个参数',
    bool_prop_1          varchar(1)      null                comment 'Boolean类型的trigger的第一个参数',
    bool_prop_2          varchar(1)      null                comment 'Boolean类型的trigger的第二个参数',
    primary key (sched_name, trigger_name, trigger_group),
    foreign key (sched_name, trigger_name, trigger_group) references QRTZ_TRIGGERS(sched_name, trigger_name, trigger_group)
) engine=innodb comment = '同步机制的行锁表';

commit;

-- =================================================
-- Generator-platform extension tables
-- =================================================

-- ----------------------------
-- 代码生成扩展表
-- ----------------------------

-- ----------------------------
-- 1、项目表
-- ----------------------------
drop table if exists gen_project;
create table gen_project (
  project_id           bigint(20)      not null auto_increment    comment '项目ID',
  project_name         varchar(50)     not null                   comment '项目名称',
  project_file_name    varchar(100)    default ''                 comment '项目文件名称',
  package_name         varchar(100)    not null                   comment '包名',
  version              varchar(20)     not null                   comment '版本号',
  project_desc         varchar(500)    default null               comment '项目描述',
  author               varchar(50)     not null                   comment '作者',
  front_framework      varchar(50)     not null                   comment '前端框架',
  back_framework       varchar(50)     not null                   comment '后端框架',
  status               char(1)         default '0'                comment '状态（0正常 1停用）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  remark               varchar(500)    default null               comment '备注',
  primary key (project_id)
) engine=innodb auto_increment=100 comment = '项目表';

-- ----------------------------
-- 2、数据源信息表
-- ----------------------------
drop table if exists sys_datasource;
create table sys_datasource (
  datasource_id        bigint(20)      not null auto_increment    comment '数据源ID',
  datasource_name      varchar(100)    not null                   comment '数据源名称',
  driver               varchar(255)    default 'com.mysql.cj.jdbc.Driver' comment '数据库驱动',
  url                  varchar(1000)   not null                   comment '数据源URL',
  user                 varchar(100)    not null                   comment '用户名',
  password             varchar(255)    default null               comment '密码',
  primary key (datasource_id)
) engine=innodb auto_increment=100 comment = '数据源信息表';

-- ----------------------------
-- 3、功能模块表
-- ----------------------------
drop table if exists sys_module;
create table sys_module (
  module_id            bigint(20)      not null auto_increment    comment '模块ID',
  module_name          varchar(50)     not null                   comment '模块名称',
  module_alias         varchar(50)     default ''                 comment '模块别名',
  module_desc          varchar(500)    default ''                 comment '模块描述',
  status               char(1)         default '0'                comment '状态（0正常 1停用）',
  del_flag             char(1)         default '0'                comment '删除标志（0代表存在 2代表删除）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  remark               varchar(500)    default null               comment '备注',
  primary key (module_id)
) engine=innodb auto_increment=100 comment = '功能模块表';

-- ----------------------------
-- 4、代码模板表
-- ----------------------------
drop table if exists sys_template;
create table sys_template (
  template_id          bigint(20)      not null auto_increment    comment '模板ID',
  template_name        varchar(100)    not null                   comment '模板名称',
  template_path        varchar(255)    default ''                 comment '模板路径',
  template_desc        varchar(500)    default null               comment '模板描述',
  template_type        varchar(50)     default ''                 comment '模板类型',
  template_status      bigint(20)      default 0                  comment '模板状态（0正常 1停用）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  remark               varchar(500)    default null               comment '备注',
  primary key (template_id)
) engine=innodb auto_increment=100 comment = '代码模板表';

-- ----------------------------
-- 5、代码模板文件表
-- ----------------------------
drop table if exists sys_template_file;
create table sys_template_file (
  template_file_id     bigint(20)      not null auto_increment    comment '模板文件ID',
  template_id          bigint(20)      not null                   comment '模板ID',
  file_name            varchar(255)    not null                   comment '文件名称',
  module_id            bigint(20)      default null               comment '功能模块ID',
  file_path            varchar(500)    default ''                 comment '文件路径',
  file_content         longtext                                   comment '文件内容',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  primary key (template_file_id),
  key idx_template_file_template_id (template_id),
  key idx_template_file_module_id (module_id),
  constraint fk_template_file_template foreign key (template_id) references sys_template(template_id),
  constraint fk_template_file_module foreign key (module_id) references sys_module(module_id)
) engine=innodb auto_increment=100 comment = '代码模板文件表';

-- ----------------------------
-- 6、代码片段管理表
-- ----------------------------
drop table if exists sys_code_snippet;
create table sys_code_snippet (
  snippet_id           bigint(20)      not null auto_increment    comment '代码片段ID',
  module_id            bigint(20)      default null               comment '功能模块ID',
  snippet_content      text            not null                   comment '代码片段内容',
  insert_point         varchar(255)    default ''                 comment '插入点',
  param1               varchar(255)    default null               comment '参数1',
  param2               varchar(255)    default null               comment '参数2',
  param3               varchar(255)    default null               comment '参数3',
  param4               varchar(255)    default null               comment '参数4',
  param5               varchar(255)    default null               comment '参数5',
  template_file_name   varchar(255)    default ''                 comment '模板文件名称',
  relation_table_name  varchar(255)    default ''                 comment '关联表名称',
  status               char(1)         default '0'                comment '状态（0正常 1停用）',
  del_flag             char(1)         default '0'                comment '删除标志（0代表存在 2代表删除）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  remark               varchar(500)    default null               comment '备注',
  primary key (snippet_id),
  key idx_code_snippet_module_id (module_id),
  constraint fk_code_snippet_module foreign key (module_id) references sys_module(module_id)
) engine=innodb auto_increment=100 comment = '代码片段管理表';

-- ----------------------------
-- 7、代码片段与功能模块关系表
-- ----------------------------
drop table if exists sys_code_snippet_module;
create table sys_code_snippet_module (
  snippet_id           bigint(20)      not null                   comment '代码片段ID',
  module_id            bigint(20)      not null                   comment '功能模块ID',
  primary key (snippet_id, module_id),
  key idx_snippet_module_module_id (module_id),
  constraint fk_snippet_module_snippet foreign key (snippet_id) references sys_code_snippet(snippet_id),
  constraint fk_snippet_module_module foreign key (module_id) references sys_module(module_id)
) engine=innodb comment = '代码片段与功能模块关系表';

-- ----------------------------
-- 8、项目与功能模块关系表
-- ----------------------------
drop table if exists sys_project_module;
create table sys_project_module (
  id                   bigint(20)      not null auto_increment    comment 'ID',
  project_id           bigint(20)      not null                   comment '项目ID',
  module_id            bigint(20)      not null                   comment '功能模块ID',
  status               char(1)         default '0'                comment '状态（0正常 1停用）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  remark               varchar(500)    default null               comment '备注',
  primary key (id),
  unique key idx_project_module (project_id, module_id),
  key idx_project_module_module_id (module_id),
  constraint fk_project_module_project foreign key (project_id) references gen_project(project_id),
  constraint fk_project_module_module foreign key (module_id) references sys_module(module_id)
) engine=innodb auto_increment=100 comment = '项目与功能模块关系表';

-- ----------------------------
-- 9、项目与生成表关系表
-- ----------------------------
drop table if exists sys_project_table;
create table sys_project_table (
  id                   bigint(20)      not null auto_increment    comment 'ID',
  table_id             bigint(20)      not null                   comment '表ID',
  project_id           bigint(20)      not null                   comment '项目ID',
  primary key (id),
  unique key idx_project_table (project_id, table_id),
  key idx_project_table_table_id (table_id),
  constraint fk_project_table_project foreign key (project_id) references gen_project(project_id),
  constraint fk_project_table_table foreign key (table_id) references gen_table(table_id)
) engine=innodb auto_increment=100 comment = '项目与生成表关系表';

-- 兼容旧脚本 gen_table_project_rel.sql；当前源码实际使用 sys_project_table
drop table if exists gen_table_project_rel;
create table gen_table_project_rel (
  id                   bigint(20)      not null auto_increment    comment 'ID',
  table_id             bigint(20)      not null                   comment '表ID',
  project_id           bigint(20)      not null                   comment '项目ID',
  primary key (id),
  unique key idx_gen_table_project_rel (project_id, table_id)
) engine=innodb auto_increment=100 comment = '项目与生成表关系表（旧版兼容）';

-- ----------------------------
-- 10、项目模板配置表
-- ----------------------------
drop table if exists sys_project_template;
create table sys_project_template (
  id                   bigint(20)      not null auto_increment    comment 'ID',
  project_id           bigint(20)      not null                   comment '项目ID',
  template_id          bigint(20)      not null                   comment '模板ID',
  template_type        varchar(50)     default ''                 comment '模板类型',
  primary key (id),
  unique key idx_project_template_type (project_id, template_type),
  key idx_project_template_template_id (template_id),
  constraint fk_project_template_project foreign key (project_id) references gen_project(project_id),
  constraint fk_project_template_template foreign key (template_id) references sys_template(template_id)
) engine=innodb auto_increment=100 comment = '项目模板配置表';

-- ----------------------------
-- 11、项目结构节点表
-- ----------------------------
drop table if exists sys_project_structure;
create table sys_project_structure (
  node_id              bigint(20)      not null auto_increment    comment '节点ID',
  parent_id            bigint(20)      default 0                  comment '父节点ID',
  node_name            varchar(50)     not null                   comment '节点名称',
  node_type            varchar(20)     not null                   comment '节点类型(folder/file)',
  module               varchar(100)    default ''                 comment '功能模块',
  template_id          bigint(20)      default null               comment '模板ID',
  table_id             bigint(20)      default null               comment '关联表ID',
  category             varchar(50)     default null               comment '文件类别',
  sort_order           int(4)          default 0                  comment '显示顺序',
  status               char(1)         default '0'                comment '状态（0正常 1停用）',
  create_by            varchar(64)     default ''                 comment '创建者',
  create_time          datetime                                   comment '创建时间',
  update_by            varchar(64)     default ''                 comment '更新者',
  update_time          datetime                                   comment '更新时间',
  primary key (node_id),
  key idx_project_structure_parent_id (parent_id),
  key idx_project_structure_template_id (template_id),
  key idx_project_structure_table_id (table_id)
) engine=innodb auto_increment=100 comment = '项目结构节点表';

insert into sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) values
(1, 0, '项目根目录', 'folder', '根模块', null, null, null, 1, '0', 'admin', sysdate(), '', null),
(2, 1, 'src', 'folder', '源码', null, null, null, 1, '0', 'admin', sysdate(), '', null),
(3, 2, 'main', 'folder', '主目录', null, null, null, 1, '0', 'admin', sysdate(), '', null),
(4, 3, 'java', 'folder', '源代码', null, null, null, 1, '0', 'admin', sysdate(), '', null),
(5, 3, 'resources', 'folder', '资源', null, null, null, 2, '0', 'admin', sysdate(), '', null),
(6, 1, 'pom.xml', 'file', '依赖管理', null, null, 'xml', 2, '0', 'admin', sysdate(), '', null),
(7, 1, 'README.md', 'file', '说明文档', null, null, 'markdown', 3, '0', 'admin', sysdate(), '', null);

-- =================================================
-- EasyCode front workbench tables
-- Import after sql/db.sql, or use the copy appended to sql/db.sql
-- =================================================

drop table if exists front_project_file;
drop table if exists front_ai_usage_ledger;
drop table if exists front_ai_generation_task;
drop table if exists front_ai_quota_bucket;
drop table if exists front_project_generation;
drop table if exists front_project_column;
drop table if exists front_project_table;
drop table if exists front_project_page_design;
drop table if exists front_project_module;
drop table if exists front_project;
drop table if exists front_user;

create table front_user (
  user_id              bigint(20)      not null auto_increment comment '前台用户ID',
  username             varchar(50)     not null comment '用户名',
  password             varchar(100)    not null comment '密码',
  nickname             varchar(50)     default '' comment '昵称',
  email                varchar(100)    default '' comment '邮箱',
  phone                varchar(20)     default '' comment '手机号',
  status               char(1)         default '0' comment '状态（0正常 1停用）',
  del_flag             char(1)         default '0' comment '删除标志（0存在 2删除）',
  last_login_time      datetime        default null comment '最后登录时间',
  create_time          datetime        default null comment '创建时间',
  update_time          datetime        default null comment '更新时间',
  remark               varchar(500)    default null comment '备注',
  primary key (user_id),
  unique key uk_front_user_username (username),
  key idx_front_user_email (email),
  key idx_front_user_phone (phone)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台用户表';

create table front_project (
  project_id           bigint(20)      not null auto_increment comment '前台项目ID',
  user_id              bigint(20)      not null comment '前台用户ID',
  project_name         varchar(100)    not null comment '项目名称',
  project_file_name    varchar(100)    default '' comment '项目文件名',
  package_name         varchar(100)    default 'com.easycode.generated' comment '包名',
  version              varchar(20)     default '1.0.0' comment '版本号',
  project_desc         varchar(1000)   default '' comment '项目描述',
  requirement_keyword  varchar(1000)   default '' comment '需求关键词',
  industry_template    varchar(50)     default '' comment '行业模板',
  front_framework      varchar(50)     default 'Vue3 + Element Plus' comment '前台框架',
  back_framework       varchar(50)     default 'Spring Boot + MyBatis' comment '后端框架',
  frontend_enabled     char(1)         default '1' comment '是否生成前台前端（1是 0否）',
  generate_status      char(1)         default '0' comment '数据库生成状态（0未生成 1生成中 2已生成 3失败）',
  preview_status       char(1)         default '0' comment '预览状态（0未预览 1已预览 2失败）',
  app_blueprint        longtext        comment '系统模块设计草稿JSON',
  er_diagram           longtext        comment 'ER图草稿JSON',
  business_blueprint   longtext        comment '业务流程设计草稿JSON',
  status               char(1)         default '0' comment '状态（0正常 1停用）',
  create_time          datetime        default null comment '创建时间',
  update_time          datetime        default null comment '更新时间',
  remark               varchar(500)    default null comment '备注',
  primary key (project_id),
  key idx_front_project_user_id (user_id),
  constraint fk_front_project_user foreign key (user_id) references front_user(user_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台项目草稿表';

create table front_project_module (
  id                   bigint(20)      not null auto_increment comment 'id',
  project_id           bigint(20)      not null comment '前台项目ID',
  module_id            bigint(20)      not null comment '功能模块ID',
  status               char(1)         default '0' comment '状态（0正常 1停用）',
  create_time          datetime        default null comment '创建时间',
  update_time          datetime        default null comment '更新时间',
  remark               varchar(500)    default null comment '备注',
  primary key (id),
  unique key uk_front_project_module (project_id, module_id),
  key idx_front_project_module_project_id (project_id),
  key idx_front_project_module_module_id (module_id),
  constraint fk_front_project_module_project foreign key (project_id) references front_project(project_id),
  constraint fk_front_project_module_module foreign key (module_id) references sys_module(module_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台项目功能模块关系';

create table front_project_page_design (
  design_id            bigint(20)      not null auto_increment comment 'Page design ID',
  project_id           bigint(20)      not null comment 'Project ID',
  user_id              bigint(20)      not null comment 'Front user ID',
  page_scope           varchar(20)     not null default 'frontend' comment 'Page scope: frontend/admin',
  page_code            varchar(100)    not null comment 'Page code',
  menu_code            varchar(100)    default '' comment 'Menu code',
  page_name            varchar(100)    not null comment 'Page name',
  route_path           varchar(255)    not null comment 'Route path',
  page_type            varchar(50)     not null comment 'Page type',
  table_name           varchar(100)    default '' comment 'Bound table name',
  layout_json          longtext        comment 'Layout JSON',
  action_json          longtext        comment 'Action JSON',
  status               char(1)         default '0' comment 'Status',
  version              int             default 1 comment 'Version',
  create_time          datetime        default null comment 'Create time',
  update_time          datetime        default null comment 'Update time',
  remark               varchar(500)    default null comment 'Remark',
  primary key (design_id),
  unique key uk_front_project_page_design (project_id, page_scope, page_code),
  key idx_front_page_design_menu (project_id, menu_code),
  key idx_front_page_design_table (project_id, table_name),
  constraint fk_front_page_design_project foreign key (project_id) references front_project(project_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='Frontend page design';

create table front_project_table (
  table_id             bigint(20)      not null auto_increment comment '表设计ID',
  project_id           bigint(20)      not null comment '项目ID',
  user_id              bigint(20)      not null comment '前台用户ID',
  table_name           varchar(200)    not null comment '表名称',
  table_comment        varchar(500)    default '' comment '表描述',
  class_name           varchar(100)    default '' comment '实体类名称',
  module_name          varchar(30)     default '' comment '生成模块名',
  business_name        varchar(30)     default '' comment '生成业务名',
  function_name        varchar(50)     default '' comment '生成功能名',
  admin_menu_name      varchar(100)    default '' comment '后台菜单名称',
  allow_add            char(1)         default '1' comment '是否允许新增（1是 0否）',
  allow_edit           char(1)         default '1' comment '是否允许修改（1是 0否）',
  allow_remove         char(1)         default '1' comment '是否允许删除（1是 0否）',
  remove_type          varchar(20)     default 'physical' comment '删除方式（none不允许 logical逻辑删除 physical物理删除）',
  operation_note       varchar(500)    default '' comment '操作能力说明',
  tpl_category         varchar(200)    default 'crud' comment '模板类型',
  tpl_web_type         varchar(30)     default 'element-plus' comment '前端模板类型',
  options              varchar(1000)   default '' comment '生成选项',
  create_table_sql     longtext        comment '建表SQL',
  sort                 int             default 0 comment '排序',
  status               char(1)         default '0' comment '状态（0正常 1停用）',
  create_time          datetime        default null comment '创建时间',
  update_time          datetime        default null comment '更新时间',
  primary key (table_id),
  unique key uk_front_project_table (project_id, table_name),
  key idx_front_project_table_project_id (project_id),
  constraint fk_front_project_table_project foreign key (project_id) references front_project(project_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台项目表设计';

create table front_project_column (
  column_id            bigint(20)      not null auto_increment comment '字段设计ID',
  table_id             bigint(20)      not null comment '表设计ID',
  project_id           bigint(20)      not null comment '项目ID',
  column_name          varchar(200)    not null comment '字段名称',
  column_comment       varchar(500)    default '' comment '字段描述',
  column_type          varchar(100)    not null comment '字段类型',
  java_type            varchar(500)    default 'String' comment 'Java类型',
  java_field           varchar(200)    default '' comment 'Java字段名',
  is_pk                char(1)         default '0' comment '是否主键（1是）',
  is_increment         char(1)         default '0' comment '是否自增（1是）',
  is_required          char(1)         default '0' comment '是否必填（1是）',
  is_insert            char(1)         default '1' comment '是否插入字段（1是）',
  is_edit              char(1)         default '1' comment '是否编辑字段（1是）',
  is_list              char(1)         default '1' comment '是否列表字段（1是）',
  is_query             char(1)         default '0' comment '是否查询字段（1是）',
  query_type           varchar(200)    default 'EQ' comment '查询方式',
  html_type            varchar(200)    default 'input' comment '显示类型',
  dict_type            varchar(200)    default '' comment '字典类型',
  default_value        varchar(200)    default null comment '默认值',
  sort                 int             default 0 comment '排序',
  create_time          datetime        default null comment '创建时间',
  update_time          datetime        default null comment '更新时间',
  primary key (column_id),
  key idx_front_project_column_table_id (table_id),
  key idx_front_project_column_project_id (project_id),
  constraint fk_front_project_column_table foreign key (table_id) references front_project_table(table_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台项目字段设计';

create table front_project_generation (
  generation_id        bigint(20)      not null auto_increment comment '生成记录ID',
  project_id           bigint(20)      not null comment '项目ID',
  user_id              bigint(20)      not null comment '前台用户ID',
  generate_type        varchar(50)     not null comment '生成类型',
  provider             varchar(50)     default 'deepseek' comment 'AI提供方',
  prompt_summary       varchar(500)    default '' comment 'Prompt摘要',
  request_payload      longtext        comment '请求内容',
  response_payload     longtext        comment '响应内容',
  success              char(1)         default '0' comment '是否成功（1成功 0失败）',
  error_message        varchar(1000)   default '' comment '错误信息',
  token_usage          int             default 0 comment 'Token用量',
  elapsed_ms           bigint(20)      default 0 comment '耗时毫秒',
  create_time          datetime        default null comment '创建时间',
  primary key (generation_id),
  key idx_front_project_generation_project_id (project_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台项目生成记录';

create table front_ai_generation_task (
  task_id              bigint(20)      not null auto_increment comment 'AI task ID',
  generation_id        bigint(20)      default null comment 'Generation record ID',
  project_id           bigint(20)      not null comment 'Project ID',
  user_id              bigint(20)      not null comment 'Front user ID',
  generate_type        varchar(50)     not null comment 'Generation type',
  provider             varchar(50)     default 'deepseek' comment 'AI provider',
  model                varchar(100)    default 'deepseek-chat' comment 'AI model',
  status               varchar(30)     not null default 'QUEUED' comment 'Task status',
  request_hash         varchar(64)     not null comment 'Request idempotency hash',
  request_payload      longtext        comment 'Request JSON',
  result_payload       longtext        comment 'Result JSON',
  error_code           varchar(100)    default '' comment 'Error code',
  error_message        varchar(1000)   default '' comment 'Error message',
  attempts             int             default 0 comment 'Attempt count',
  max_attempts         int             default 3 comment 'Max attempts',
  next_retry_time      datetime        default null comment 'Next retry time',
  locked_by            varchar(100)    default '' comment 'Worker lock owner',
  locked_until         datetime        default null comment 'Worker lock expiry',
  progress             int             default 0 comment 'Progress percent',
  current_step         varchar(100)    default '' comment 'Current step',
  input_tokens         int             default 0 comment 'Input tokens',
  output_tokens        int             default 0 comment 'Output tokens',
  total_tokens         int             default 0 comment 'Total tokens',
  cost_cents           int             default 0 comment 'Estimated cost in cents',
  started_at           datetime        default null comment 'Started time',
  finished_at          datetime        default null comment 'Finished time',
  create_time          datetime        default null comment 'Create time',
  update_time          datetime        default null comment 'Update time',
  primary key (task_id),
  key idx_front_ai_task_project (user_id, project_id),
  key idx_front_ai_task_status (status, next_retry_time),
  key idx_front_ai_task_generation (generation_id),
  key idx_front_ai_task_hash (user_id, project_id, request_hash)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='Front AI generation task';

create table front_ai_quota_bucket (
  bucket_id            bigint(20)      not null auto_increment comment 'Quota bucket ID',
  user_id              bigint(20)      not null comment 'Front user ID',
  period_type          varchar(20)     not null comment 'DAY or MONTH',
  period_key           varchar(20)     not null comment 'Period key',
  task_limit           int             default 0 comment 'Task limit',
  task_used            int             default 0 comment 'Used tasks',
  token_limit          int             default 0 comment 'Token limit',
  token_used           int             default 0 comment 'Used tokens',
  cost_limit_cents     int             default 0 comment 'Cost limit in cents',
  cost_used_cents      int             default 0 comment 'Used cost in cents',
  running_limit        int             default 1 comment 'Running task limit',
  running_count        int             default 0 comment 'Running task count',
  create_time          datetime        default null comment 'Create time',
  update_time          datetime        default null comment 'Update time',
  primary key (bucket_id),
  unique key uk_front_ai_quota_bucket (user_id, period_type, period_key)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='Front AI quota bucket';

create table front_ai_usage_ledger (
  ledger_id            bigint(20)      not null auto_increment comment 'Usage ledger ID',
  task_id              bigint(20)      default null comment 'Task ID',
  generation_id        bigint(20)      default null comment 'Generation record ID',
  project_id           bigint(20)      not null comment 'Project ID',
  user_id              bigint(20)      not null comment 'Front user ID',
  generate_type        varchar(50)     not null comment 'Generation type',
  provider             varchar(50)     default 'deepseek' comment 'AI provider',
  model                varchar(100)    default 'deepseek-chat' comment 'AI model',
  input_tokens         int             default 0 comment 'Input tokens',
  output_tokens        int             default 0 comment 'Output tokens',
  total_tokens         int             default 0 comment 'Total tokens',
  cost_cents           int             default 0 comment 'Estimated cost in cents',
  success              char(1)         default '0' comment 'Success flag',
  error_message        varchar(1000)   default '' comment 'Error message',
  create_time          datetime        default null comment 'Create time',
  primary key (ledger_id),
  key idx_front_ai_usage_user (user_id, create_time),
  key idx_front_ai_usage_task (task_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='Front AI usage ledger';

create table front_project_file (
  file_id              bigint(20)      not null auto_increment comment '文件缓存ID',
  project_id           bigint(20)      not null comment '项目ID',
  template_type        varchar(50)     not null comment '模板类型',
  node_id              varchar(100)    default '' comment '结构节点ID',
  table_id             bigint(20)      default null comment '表设计ID',
  file_name            varchar(255)    not null comment '文件名',
  file_path            varchar(500)    default '' comment '文件路径',
  file_content         longtext        comment '文件内容',
  content_hash         varchar(64)     default '' comment '内容哈希',
  create_time          datetime        default null comment '创建时间',
  update_time          datetime        default null comment '更新时间',
  primary key (file_id),
  key idx_front_project_file_project_id (project_id),
  key idx_front_project_file_lookup (project_id, template_type, table_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='前台项目预览文件缓存';

-- =================================================
-- EasyCode source store tables
-- =================================================

drop table if exists source_purchase;
drop table if exists source_project;

create table source_project (
  project_id           bigint(20)      not null auto_increment comment '源码项目ID',
  slug                 varchar(100)    not null comment '前台访问标识',
  project_name         varchar(120)    not null comment '项目名称',
  category             varchar(50)     default '' comment '分类',
  cover_text           varchar(30)     default '' comment '封面标识',
  summary              varchar(500)    default '' comment '项目摘要',
  description_md       longtext        comment 'Markdown项目描述',
  price                bigint(20)      default 0 comment '价格，单位分',
  view_count           bigint(20)      default 0 comment '浏览量',
  tags                 longtext        comment '技术标签JSON',
  modules              longtext        comment '功能模块JSON',
  scenes               longtext        comment '适用场景JSON',
  resource_name        varchar(200)    default '' comment '源码资源名称',
  resource_url         varchar(500)    default '' comment '源码资源地址',
  resource_version     varchar(50)     default '' comment '源码资源版本',
  resource_size        varchar(50)     default '' comment '源码资源大小',
  sort                 int             default 0 comment '排序',
  status               char(1)         default '0' comment '状态（0上架 1下架）',
  del_flag             char(1)         default '0' comment '删除标志（0存在 2删除）',
  create_by            varchar(64)     default '' comment '创建者',
  create_time          datetime        default null comment '创建时间',
  update_by            varchar(64)     default '' comment '更新者',
  update_time          datetime        default null comment '更新时间',
  remark               varchar(500)    default null comment '备注',
  primary key (project_id),
  unique key uk_source_project_slug (slug),
  key idx_source_project_category (category),
  key idx_source_project_status (status, del_flag)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='源码库项目表';

create table source_purchase (
  purchase_id          bigint(20)      not null auto_increment comment '购买记录ID',
  project_id           bigint(20)      not null comment '源码项目ID',
  user_id              bigint(20)      not null comment '前台用户ID',
  order_no             varchar(64)     not null comment '订单号',
  amount               bigint(20)      default 0 comment '金额，单位分',
  pay_status           char(1)         default '0' comment '支付状态（0待支付 1已支付 2已取消）',
  resource_status      char(1)         default '0' comment '资源状态（0未发放 1已发放）',
  purchase_time        datetime        default null comment '购买时间',
  create_by            varchar(64)     default '' comment '创建者',
  create_time          datetime        default null comment '创建时间',
  update_by            varchar(64)     default '' comment '更新者',
  update_time          datetime        default null comment '更新时间',
  remark               varchar(500)    default null comment '备注',
  primary key (purchase_id),
  unique key uk_source_purchase_order_no (order_no),
  key idx_source_purchase_user (user_id),
  key idx_source_purchase_project (project_id),
  constraint fk_source_purchase_project foreign key (project_id) references source_project(project_id),
  constraint fk_source_purchase_user foreign key (user_id) references front_user(user_id)
) engine=innodb auto_increment=100 default charset=utf8mb4 comment='源码购买记录表';

insert into source_project
(project_id, slug, project_name, category, cover_text, summary, description_md, price, view_count, tags, modules, scenes, resource_name, resource_url, resource_version, resource_size, sort, status, del_flag, create_by, create_time, update_by, update_time, remark)
values
(100, 'dms-platform', '商用车 DMS 管理系统', 'enterprise', 'DMS', '覆盖经销商、维修工单、索赔、配件库存、服务活动和结算的商用车售后管理源码。',
'# 商用车 DMS 管理系统\n\n这套源码面向商用车售后服务场景，提供经销商、车辆档案、维修工单、索赔流程、配件库存和结算对账等核心能力。\n\n## 核心功能\n\n- 经销商档案、服务站和维修技师管理\n- 车辆档案、保养提醒和维修历史追踪\n- 维修工单、派工、完工质检和费用结算\n- 配件入库、出库、调拨和库存预警\n- 索赔申请、审核、结算和统计报表', 39900, 2860,
'["Spring Boot","Vue2","MySQL"]', '["经销商管理","维修工单","配件库存","索赔结算","服务活动"]', '["汽车后市场","商用车售后","经销商协同"]', '', '', '1.0.0', '', 1, '0', '0', 'admin', sysdate(), 'admin', sysdate(), null),
(101, 'mall-order-system', '商城订单管理系统', 'mall', 'MALL', '包含商品、订单、支付、库存、优惠券、会员和后台统计模块的商城管理源码。',
'# 商城订单管理系统\n\n项目提供从商品上架到订单履约的完整后台管理能力，适合作为中小型商城或订单中台的启动源码。\n\n## 功能模块\n\n- 商品分类、SKU、库存和上下架\n- 购物车、订单、支付记录和售后单\n- 优惠券、满减活动和会员等级\n- 后台统计看板和经营数据导出', 29900, 1980,
'["Spring Cloud","Redis","Vue3"]', '["商品中心","订单中心","支付记录","会员体系","营销活动"]', '["电商后台","订单运营","会员营销"]', '', '', '1.0.0', '', 2, '0', '0', 'admin', sysdate(), 'admin', sysdate(), null),
(102, 'oa-approval-suite', 'OA 办公审批系统', 'office', 'OA', '集成用户、角色、菜单、审批流、请假、报销、公告和文件管理的办公源码。',
'# OA 办公审批系统\n\n这是一套偏企业内网办公的基础源码，重点覆盖审批、公告、文件与权限管理。\n\n## 亮点\n\n- 可配置审批节点和审批人\n- 请假、报销、外出等常见办公流程\n- 公告通知、附件上传和文件归档\n- 角色、菜单、按钮级权限控制', 26800, 1750,
'["Sa-Token","Element UI","工作流"]', '["审批流程","请假报销","公告通知","文件管理","权限菜单"]', '["企业内网","行政审批","协同办公"]', '', '', '1.0.0', '', 3, '0', '0', 'admin', sysdate(), 'admin', sysdate(), null),
(103, 'erp-warehouse', 'ERP 仓储管理系统', 'enterprise', 'ERP', '提供采购、销售、入库、出库、盘点、供应商和库存报表模块的仓储源码。',
'# ERP 仓储管理系统\n\n源码聚焦进销存和仓储管理，适合小型供应链、仓库和贸易公司快速搭建业务后台。\n\n## 模块清单\n\n- 采购订单、采购入库和供应商档案\n- 销售订单、销售出库和客户档案\n- 库存流水、库存盘点和预警规则\n- Excel 导入导出与库存报表', 19900, 1320,
'["ERP","MyBatis-Plus","Excel"]', '["采购入库","销售出库","库存盘点","供应商管理","报表导出"]', '["仓储管理","进销存","供应链后台"]', '', '', '1.0.0', '', 4, '0', '0', 'admin', sysdate(), 'admin', sysdate(), null),
(104, 'lowcode-form-platform', '低代码表单平台', 'lowcode', 'FORM', '支持动态表单、拖拽布局、字段配置、数据字典和在线设计的低代码源码。',
'# 低代码表单平台\n\n项目用于构建配置化表单和数据采集页面，包含设计器、字段配置、预览和提交数据管理。\n\n## 能力范围\n\n- 拖拽式表单组件编排\n- 字段属性、校验规则和选项配置\n- 字典数据联动\n- 表单预览与数据提交记录', 49900, 980,
'["Vue3","Element Plus","拖拽设计"]', '["表单设计器","字段配置","动态校验","数据字典","表单预览"]', '["低代码平台","动态表单","配置化后台"]', '', '', '1.0.0', '', 5, '0', '0', 'admin', sysdate(), 'admin', sysdate(), null),
(105, 'microservice-auth-starter', '微服务权限脚手架', 'microservice', 'MS', '集成网关、认证中心、系统服务、日志服务、文件服务和监控基础能力的脚手架源码。',
'# 微服务权限脚手架\n\n这套源码适合从单体后台升级到微服务架构的团队，预置认证、网关、系统权限和基础监控能力。\n\n## 服务组成\n\n- Gateway 网关统一鉴权和路由\n- Auth 认证中心\n- System 系统权限服务\n- Log 操作日志服务\n- File 文件服务', 59900, 2560,
'["Spring Cloud","Nacos","Gateway"]', '["网关服务","认证中心","系统服务","日志中心","文件服务"]', '["微服务基础架构","权限平台","多服务治理"]', '', '', '1.0.0', '', 6, '0', '0', 'admin', sysdate(), 'admin', sysdate(), null);

SET FOREIGN_KEY_CHECKS = 1;

-- Business blueprint Velocity templates
-- Import this script after sql/db.sql.
-- Template ids:
-- 9101 backend: RuoYi Spring Boot + MyBatis
-- 9102 admin_frontend: Vue2 + Element UI for RuoYi admin
-- 9103 frontend: Vue3 + Element Plus portal

SET FOREIGN_KEY_CHECKS = 0;

DELETE FROM sys_project_template WHERE template_id IN (9101, 9102, 9103);
DELETE FROM sys_project_structure WHERE template_id IN (9101, 9102, 9103) OR node_id BETWEEN 910100 AND 910399;
DELETE FROM sys_template_file WHERE template_id IN (9101, 9102, 9103) OR template_file_id BETWEEN 910100 AND 910399;
DELETE FROM sys_template WHERE template_id IN (9101, 9102, 9103);

INSERT INTO sys_template (template_id, template_name, template_path, template_desc, template_type, template_status, create_by, create_time, remark) VALUES
(9101, 'Business Blueprint Backend', '/blueprint/backend', 'RuoYi backend with CRUD and executable blueprint effects', 'backend', 0, 'admin', sysdate(), 'business blueprint'),
(9102, 'Business Blueprint Admin Frontend', '/blueprint/admin_frontend', 'Vue2 Element UI admin pages with blueprint action buttons', 'admin_frontend', 0, 'admin', sysdate(), 'business blueprint'),
(9103, 'Business Blueprint Portal Frontend', '/blueprint/frontend', 'Vue3 Element Plus portal pages with blueprint action buttons', 'frontend', 0, 'admin', sysdate(), 'business blueprint');

-- Backend template files
INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910101, 9101, 'pom.xml.vm', NULL, 'pom.xml.vm',
'<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.15</version>
    <relativePath/>
  </parent>

  <groupId>${packageName}</groupId>
  <artifactId>${projectFileName}-backend</artifactId>
  <version>1.0.0</version>
  <name>${projectName}</name>
  <description>Generated backend with business blueprint actions</description>

  <properties>
    <java.version>1.8</java.version>
    <ruoyi.version>3.8.8</ruoyi.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.ruoyi</groupId>
      <artifactId>ruoyi-common</artifactId>
      <version>${ruoyi.version}</version>
    </dependency>
    <dependency>
      <groupId>com.ruoyi</groupId>
      <artifactId>ruoyi-framework</artifactId>
      <version>${ruoyi.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
', 'admin', sysdate()),
(910102, 9101, 'application.yml.vm', NULL, 'application.yml.vm',
'#set($d = ''$'')
server:
  port: ${d}{SERVER_PORT:8080}

spring:
  application:
    name: ${projectFileName}-backend
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: ${d}{DB_URL:jdbc:mysql://localhost:3306/vip?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8}
    username: ${d}{DB_USERNAME:root}
    password: ${d}{DB_PASSWORD:[REDACTED]

mybatis:
  typeAliasesPackage: ${packageName}.domain
  mapperLocations: classpath:mapper/**/*.xml
', 'admin', sysdate()),
(910110, 9101, 'Application.java.vm', NULL, 'Application.java.vm',
'package ${packageName};

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@MapperScan("${packageName}.mapper")
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class ${projectClassName}Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(${projectClassName}Application.class, args);
    }
}
', 'admin', sysdate()),
(910103, 9101, 'README.md.vm', NULL, 'README.md.vm',
'# ${projectName} Backend

Generated from EasyCode business blueprint templates.

Create table SQL:

```sql
${createTableSql}
```

# Business Actions

#if($hasBusinessActions)
#foreach($action in $businessActions)
- ${action.name} `${action.code}` `${action.method} ${action.path}` owner `${action.ownerTable}`
#end
#else
No business actions in blueprint.
#end
', 'admin', sysdate()),
(910104, 9101, 'domain.java.vm', NULL, 'domain.java.vm',
'package ${packageName}.domain;

import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * ${functionName} object ${tableName}
 *
 * @author ${author}
 * @date ${datetime}
 */
public class ${ClassName} extends BaseEntity
{
    private static final long serialVersionUID = 1L;

#foreach($column in $columns)
#if(!$table.isSuperColumn($column.javaField))
    /** ${column.columnComment} */
#if($column.javaType == "Date")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#end
#if($column.isList == "1")
    @Excel(name = "${column.columnComment}")
#end
    private ${column.javaType} ${column.javaField};

#end
#end
#foreach($column in $columns)
#if(!$table.isSuperColumn($column.javaField))
    public void set${column.capJavaField}(${column.javaType} ${column.javaField})
    {
        this.${column.javaField} = ${column.javaField};
    }

    public ${column.javaType} get${column.capJavaField}()
    {
        return ${column.javaField};
    }

#end
#end
    @Override
    public String toString()
    {
        return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
#foreach($column in $columns)
#if(!$table.isSuperColumn($column.javaField))
            .append("${column.javaField}", get${column.capJavaField}())
#end
#end
            .toString();
    }
}
', 'admin', sysdate()),
(910105, 9101, 'mapper.java.vm', NULL, 'mapper.java.vm',
'package ${packageName}.mapper;

import java.util.List;
import ${packageName}.domain.${ClassName};

/**
 * ${functionName} Mapper
 */
public interface ${ClassName}Mapper
{
    public ${ClassName} select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField});

    public List<${ClassName}> select${ClassName}List(${ClassName} ${className});

    public int insert${ClassName}(${ClassName} ${className});

    public int update${ClassName}(${ClassName} ${className});

    public int delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField});

    public int delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s);
}
', 'admin', sysdate()),
(910106, 9101, 'mapper.xml.vm', NULL, 'mapper.xml.vm',
'<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${packageName}.mapper.${ClassName}Mapper">

    <resultMap type="${packageName}.domain.${ClassName}" id="${ClassName}Result">
#foreach($column in $columns)
#if($column.isPk == "1")
        <id property="${column.javaField}" column="${column.columnName}" />
#else
        <result property="${column.javaField}" column="${column.columnName}" />
#end
#end
    </resultMap>

    <sql id="select${ClassName}Vo">
        select
#foreach($column in $columns)
            ${column.columnName}#if($foreach.hasNext),#end
#end
        from ${tableName}
    </sql>

    <select id="select${ClassName}List" parameterType="${packageName}.domain.${ClassName}" resultMap="${ClassName}Result">
        <include refid="select${ClassName}Vo"/>
        <where>
#foreach($column in $columns)
#if($column.isQuery == "1")
            <if test="${column.javaField} != null"> and ${column.columnName} = #{${column.javaField}}</if>
#end
#end
        </where>
    </select>

    <select id="select${ClassName}By${pkColumn.capJavaField}" parameterType="${pkColumn.javaType}" resultMap="${ClassName}Result">
        <include refid="select${ClassName}Vo"/>
        where ${pkColumn.columnName} = #{${pkColumn.javaField}}
    </select>

    <insert id="insert${ClassName}" parameterType="${packageName}.domain.${ClassName}"#if($pkColumn.increment) useGeneratedKeys="true" keyProperty="${pkColumn.javaField}"#end>
        insert into ${tableName}
        <trim prefix="(" suffix=")" suffixOverrides=",">
#foreach($column in $columns)
#if($column.isInsert == "1" && $column.isIncrement != "1")
            <if test="${column.javaField} != null">${column.columnName},</if>
#end
#end
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
#foreach($column in $columns)
#if($column.isInsert == "1" && $column.isIncrement != "1")
            <if test="${column.javaField} != null">#{${column.javaField}},</if>
#end
#end
        </trim>
    </insert>

    <update id="update${ClassName}" parameterType="${packageName}.domain.${ClassName}">
        update ${tableName}
        <trim prefix="SET" suffixOverrides=",">
#foreach($column in $columns)
#if($column.isEdit == "1" && $column.isPk != "1")
            <if test="${column.javaField} != null">${column.columnName} = #{${column.javaField}},</if>
#end
#end
        </trim>
        where ${pkColumn.columnName} = #{${pkColumn.javaField}}
    </update>

    <delete id="delete${ClassName}By${pkColumn.capJavaField}" parameterType="${pkColumn.javaType}">
        delete from ${tableName} where ${pkColumn.columnName} = #{${pkColumn.javaField}}
    </delete>

    <delete id="delete${ClassName}By${pkColumn.capJavaField}s" parameterType="String">
        delete from ${tableName} where ${pkColumn.columnName} in
        <foreach item="${pkColumn.javaField}" collection="array" open="(" separator="," close=")">
            #{${pkColumn.javaField}}
        </foreach>
    </delete>
</mapper>
', 'admin', sysdate()),
(910107, 9101, 'service.java.vm', NULL, 'service.java.vm',
'package ${packageName}.service;

import java.util.List;
import java.util.Map;
import ${packageName}.domain.${ClassName};

/**
 * ${functionName} Service
 */
public interface I${ClassName}Service
{
    public ${ClassName} select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField});

    public List<${ClassName}> select${ClassName}List(${ClassName} ${className});

    public int insert${ClassName}(${ClassName} ${className});

    public int update${ClassName}(${ClassName} ${className});

    public int delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s);

    public int delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField});

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
    public int ${action.code}(Map<String, Object> params);

#end
#end
}
', 'admin', sysdate()),
(910108, 9101, 'serviceImpl.java.vm', NULL, 'serviceImpl.java.vm',
'package ${packageName}.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import ${packageName}.domain.${ClassName};
import ${packageName}.mapper.${ClassName}Mapper;
import ${packageName}.service.I${ClassName}Service;

/**
 * ${functionName} Service implementation
 */
@Service
public class ${ClassName}ServiceImpl implements I${ClassName}Service
{
    @Resource
    private ${ClassName}Mapper ${className}Mapper;
#if($hasTableBusinessActions)
    @Resource
    private JdbcTemplate jdbcTemplate;
#end

    @Override
    public ${ClassName} select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField})
    {
        return ${className}Mapper.select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField});
    }

    @Override
    public List<${ClassName}> select${ClassName}List(${ClassName} ${className})
    {
        return ${className}Mapper.select${ClassName}List(${className});
    }

    @Override
    public int insert${ClassName}(${ClassName} ${className})
    {
        return ${className}Mapper.insert${ClassName}(${className});
    }

    @Override
    public int update${ClassName}(${ClassName} ${className})
    {
        return ${className}Mapper.update${ClassName}(${className});
    }

    @Override
    public int delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s)
    {
        return ${className}Mapper.delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaField}s);
    }

    @Override
    public int delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField})
    {
        return ${className}Mapper.delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField});
    }

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
    /**
     * ${action.name}
#if($action.requestFields)
     * Request fields:
#foreach($field in $action.requestFields)
     * - ${field}
#end
#end
#if($action.rules)
     * Rules:
#foreach($rule in $action.rules)
     * - ${rule}
#end
#end
#if($action.effects)
     * Effects:
#foreach($effect in $action.effects)
     * - ${effect.type} ${effect.targetTable}.${effect.targetField} ${effect.value} ${effect.description}
#end
#end
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int ${action.code}(Map<String, Object> params)
    {
        if (params == null) {
            throw new ServiceException("涓氬姟鍔ㄤ綔鍙傛暟涓嶈兘涓虹┖");
        }
#if($action.requestFields)
#foreach($field in $action.requestFields)
        requireBusinessParam(params, "${field}");
#end
#end
 #if($action.ruleChecks)
#foreach($rule in $action.ruleChecks)
#set($conditionFields = $rule.conditionFields)
#if($rule.type == "EXISTS")
        assertExists(params, "${rule.targetTable}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "NOT_EXISTS")
        assertNotExists(params, "${rule.targetTable}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "FIELD_EQUALS")
        assertFieldEquals(params, "${rule.targetTable}", "${rule.targetField}", "${rule.expectedValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "FIELD_NOT_EQUALS")
        assertFieldNotEquals(params, "${rule.targetTable}", "${rule.targetField}", "${rule.expectedValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "FIELD_IN")
        assertFieldIn(params, "${rule.targetTable}", "${rule.targetField}", new String[] {#foreach($value in $rule.expectedValues)"${value}"#if($foreach.hasNext), #end#end}, new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "NUMBER_GTE")
        assertNumberGte(params, "${rule.targetTable}", "${rule.targetField}", "${rule.compareValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#end
#end
#end
        int rows = 0;
#if($action.effects)
#foreach($effect in $action.effects)
#if($effect.type == "UPDATE_FIELD")
#set($conditionFields = $effect.conditionFields)
        rows += executeUpdateFieldEffect(params, "${effect.targetTable}", "${effect.targetField}", "${effect.value}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "INSERT_ROW")
#set($effectIndex = $foreach.index)
        Map<String, Object> insertValues${effectIndex} = new java.util.LinkedHashMap<String, Object>();
#foreach($entry in $effect.values.entrySet())
        insertValues${effectIndex}.put("${entry.key}", resolveBusinessValue(params, "${entry.value}"));
#end
        rows += insertRow("${effect.targetTable}", insertValues${effectIndex});
#elseif($effect.type == "UPDATE_FIELDS")
#set($conditionFields = $effect.conditionFields)
#set($effectIndex = $foreach.index)
        Map<String, Object> updateValues${effectIndex} = new java.util.LinkedHashMap<String, Object>();
#foreach($entry in $effect.values.entrySet())
        updateValues${effectIndex}.put("${entry.key}", resolveBusinessValue(params, "${entry.value}"));
#end
        rows += updateFields(params, "${effect.targetTable}", updateValues${effectIndex}, new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "SET_STATUS")
#set($conditionFields = $effect.conditionFields)
        rows += setStatus(params, "${effect.targetTable}", "${effect.targetField}", resolveBusinessValue(params, "${effect.value}"), new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "INCREASE_NUMBER")
#set($conditionFields = $effect.conditionFields)
        rows += increaseNumberField(params, "${effect.targetTable}", "${effect.targetField}", "${effect.amount}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "DECREASE_NUMBER")
#set($conditionFields = $effect.conditionFields)
        rows += decreaseNumberField(params, "${effect.targetTable}", "${effect.targetField}", "${effect.amount}", "${effect.minValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${effect.message}");
#else
        // Unsupported effect type ${effect.type}: ${effect.description}
#end
#end
#end
        return rows;
    }

#end
    private void requireBusinessParam(Map<String, Object> params, String field)
    {
        if (!params.containsKey(field) || params.get(field) == null) {
            throw new ServiceException("缂哄皯涓氬姟鍔ㄤ綔鍙傛暟锛? + field);
        }
    }

    private void assertExists(Map<String, Object> params, String tableName, String[] conditionFields, String message)
    {
        if (countRows(params, tableName, conditionFields) <= 0) {
            throw new ServiceException(defaultMessage(message, "Business record does not exist"));
        }
    }

    private void assertNotExists(Map<String, Object> params, String tableName, String[] conditionFields, String message)
    {
        if (countRows(params, tableName, conditionFields) > 0) {
            throw new ServiceException(defaultMessage(message, "Business record already exists"));
        }
    }

    private void assertFieldEquals(Map<String, Object> params, String tableName, String targetField, String expectedValue,
                                   String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        if (value == null || !String.valueOf(resolveBusinessValue(params, expectedValue)).equals(String.valueOf(value))) {
            throw new ServiceException(defaultMessage(message, "Business rule check failed"));
        }
    }

    private void assertFieldNotEquals(Map<String, Object> params, String tableName, String targetField, String expectedValue,
                                      String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        if (value != null && String.valueOf(resolveBusinessValue(params, expectedValue)).equals(String.valueOf(value))) {
            throw new ServiceException(defaultMessage(message, "Business rule check failed"));
        }
    }

    private void assertFieldIn(Map<String, Object> params, String tableName, String targetField, String[] expectedValues,
                               String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        String current = value == null ? "" : String.valueOf(value);
        for (String expectedValue : expectedValues) {
            if (String.valueOf(resolveBusinessValue(params, expectedValue)).equals(current)) {
                return;
            }
        }
        throw new ServiceException(defaultMessage(message, "Business rule check failed"));
    }

    private void assertNumberGte(Map<String, Object> params, String tableName, String targetField, String compareValue,
                                 String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        BigDecimal current = toBigDecimal(value, "Business numeric value is invalid");
        BigDecimal expected = resolveBusinessNumber(params, compareValue);
        if (current.compareTo(expected) < 0) {
            throw new ServiceException(defaultMessage(message, "Business numeric rule check failed"));
        }
    }

    private int insertRow(String tableName, Map<String, Object> values)
    {
        String safeTableName = requireSafeIdentifier(tableName, "Business effect target table is invalid");
        if (values == null || values.isEmpty()) {
            throw new ServiceException("Business insert values cannot be empty");
        }
        StringBuilder fields = new StringBuilder();
        StringBuilder placeholders = new StringBuilder();
        List<Object> args = new ArrayList<Object>();
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            if (fields.length() > 0) {
                fields.append(", ");
                placeholders.append(", ");
            }
            fields.append(requireSafeIdentifier(entry.getKey(), "Business effect value field is invalid"));
            placeholders.append("?");
            args.add(entry.getValue());
        }
        return jdbcTemplate.update("insert into " + safeTableName + " (" + fields + ") values (" + placeholders + ")", args.toArray());
    }

    private int updateFields(Map<String, Object> params, String tableName, Map<String, Object> values, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "Business effect target table is invalid");
        if (values == null || values.isEmpty()) {
            throw new ServiceException("Business update values cannot be empty");
        }
        StringBuilder sets = new StringBuilder();
        List<Object> args = new ArrayList<Object>();
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            if (sets.length() > 0) {
                sets.append(", ");
            }
            sets.append(requireSafeIdentifier(entry.getKey(), "Business effect value field is invalid")).append(" = ?");
            args.add(entry.getValue());
        }
        String whereClause = buildWhereClause(params, conditionFields);
        appendConditionValues(args, params, conditionFields);
        return jdbcTemplate.update("update " + safeTableName + " set " + sets + " where " + whereClause, args.toArray());
    }

    private int setStatus(Map<String, Object> params, String tableName, String targetField, Object value, String[] conditionFields)
    {
        Map<String, Object> values = new java.util.LinkedHashMap<String, Object>();
        values.put(targetField, value);
        return updateFields(params, tableName, values, conditionFields);
    }

    private int increaseNumberField(Map<String, Object> params, String tableName, String targetField, String amountExpression,
                                    String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "Business effect target table is invalid");
        String safeTargetField = requireSafeIdentifier(targetField, "Business effect target field is invalid");
        BigDecimal amount = resolveBusinessNumber(params, amountExpression);
        String whereClause = buildWhereClause(params, conditionFields);
        List<Object> args = new ArrayList<Object>();
        args.add(amount);
        appendConditionValues(args, params, conditionFields);
        return jdbcTemplate.update("update " + safeTableName + " set " + safeTargetField + " = " + safeTargetField + " + ? where " + whereClause, args.toArray());
    }

    private int decreaseNumberField(Map<String, Object> params, String tableName, String targetField, String amountExpression,
                                    String minValueExpression, String[] conditionFields, String message)
    {
        String safeTableName = requireSafeIdentifier(tableName, "Business effect target table is invalid");
        String safeTargetField = requireSafeIdentifier(targetField, "Business effect target field is invalid");
        BigDecimal amount = resolveBusinessNumber(params, amountExpression);
        BigDecimal minValue = resolveBusinessNumber(params, minValueExpression == null || minValueExpression.length() == 0 ? "0" : minValueExpression);
        String whereClause = buildWhereClause(params, conditionFields);
        List<Object> args = new ArrayList<Object>();
        args.add(amount);
        appendConditionValues(args, params, conditionFields);
        args.add(amount);
        args.add(minValue);
        int rows = jdbcTemplate.update("update " + safeTableName + " set " + safeTargetField + " = " + safeTargetField + " - ? where " + whereClause + " and " + safeTargetField + " - ? >= ?", args.toArray());
        if (rows == 0) {
            throw new ServiceException(defaultMessage(message, "Business numeric decrease failed"));
        }
        return rows;
    }

    private int executeUpdateFieldEffect(Map<String, Object> params, String tableName, String targetField,
                                         String valueExpression, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "涓氬姟褰卞搷鐩爣琛ㄤ笉鍚堟硶");
        String safeTargetField = requireSafeIdentifier(targetField, "涓氬姟褰卞搷鐩爣瀛楁涓嶅悎娉?);
        String safeValueExpression = requireSafeExpression(valueExpression);
        String whereClause = buildWhereClause(params, conditionFields);
        Object[] values = conditionValues(params, conditionFields);
        String sql = "update " + safeTableName + " set " + safeTargetField + " = " + safeValueExpression + " where " + whereClause;
        return jdbcTemplate.update(sql, values);
    }

    private String buildWhereClause(Map<String, Object> params, String[] conditionFields)
    {
        if (conditionFields == null || conditionFields.length == 0) {
            throw new ServiceException("涓氬姟褰卞搷缂哄皯鏉′欢瀛楁");
        }
        StringBuilder where = new StringBuilder();
        for (String field : conditionFields) {
            String safeField = requireSafeIdentifier(field, "涓氬姟褰卞搷鏉′欢瀛楁涓嶅悎娉?);
            requireBusinessParam(params, safeField);
            if (where.length() > 0) {
                where.append(" and ");
            }
            where.append(safeField).append(" = ?");
        }
        return where.toString();
    }

    private Object[] conditionValues(Map<String, Object> params, String[] conditionFields)
    {
        Object[] values = new Object[conditionFields.length];
        for (int i = 0; i < conditionFields.length; i++) {
            values[i] = params.get(conditionFields[i]);
        }
        return values;
    }

    private int countRows(Map<String, Object> params, String tableName, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "Business rule target table is invalid");
        String whereClause = buildWhereClause(params, conditionFields);
        Integer count = jdbcTemplate.queryForObject("select count(1) from " + safeTableName + " where " + whereClause, conditionValues(params, conditionFields), Integer.class);
        return count == null ? 0 : count.intValue();
    }

    private Object querySingleField(Map<String, Object> params, String tableName, String targetField, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "Business rule target table is invalid");
        String safeTargetField = requireSafeIdentifier(targetField, "Business rule target field is invalid");
        String whereClause = buildWhereClause(params, conditionFields);
        List<Map<String, Object>> rows = jdbcTemplate.queryForList("select " + safeTargetField + " from " + safeTableName + " where " + whereClause + " limit 1", conditionValues(params, conditionFields));
        if (rows.isEmpty()) {
            return null;
        }
        return rows.get(0).get(safeTargetField);
    }

    private void appendConditionValues(List<Object> args, Map<String, Object> params, String[] conditionFields)
    {
        for (Object value : conditionValues(params, conditionFields)) {
            args.add(value);
        }
    }

    private Object resolveBusinessValue(Map<String, Object> params, String valueExpression)
    {
        if (valueExpression == null) {
            return null;
        }
        if ("#[[${now}]]#".equals(valueExpression)) {
            return new Date();
        }
        if (valueExpression.startsWith("#[[${param.]]#") && valueExpression.endsWith("}")) {
            String field = valueExpression.substring(8, valueExpression.length() - 1);
            requireBusinessParam(params, field);
            return params.get(field);
        }
        return valueExpression;
    }

    private BigDecimal resolveBusinessNumber(Map<String, Object> params, String valueExpression)
    {
        return toBigDecimal(resolveBusinessValue(params, valueExpression), "Business numeric expression is invalid");
    }

    private BigDecimal toBigDecimal(Object value, String message)
    {
        try {
            return new BigDecimal(String.valueOf(value));
        } catch (RuntimeException e) {
            throw new ServiceException(message);
        }
    }

    private String defaultMessage(String message, String fallback)
    {
        return message == null || message.length() == 0 ? fallback : message;
    }

    private String requireSafeIdentifier(String value, String message)
    {
        if (value == null || !value.matches("[A-Za-z][A-Za-z0-9_]*")) {
            throw new ServiceException(message);
        }
        return value;
    }

    private String requireSafeExpression(String valueExpression)
    {
        if (valueExpression == null || !valueExpression.matches("[A-Za-z0-9_ +*/().-]{1,200}")
                || valueExpression.contains(";") || valueExpression.contains("--")) {
            throw new ServiceException("涓氬姟褰卞搷瀛楁琛ㄨ揪寮忎笉鍚堟硶");
        }
        return valueExpression;
    }
#end
}
', 'admin', sysdate()),
(910109, 9101, 'controller.java.vm', NULL, 'controller.java.vm',
'package ${packageName}.controller;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import ${packageName}.domain.${ClassName};
import ${packageName}.service.I${ClassName}Service;

/**
 * ${functionName} Controller
 */
@RestController
@RequestMapping("/${moduleName}/${businessName}")
public class ${ClassName}Controller extends BaseController
{
    @Resource
    private I${ClassName}Service ${className}Service;

    @GetMapping("/list")
    public TableDataInfo list(${ClassName} ${className})
    {
        startPage();
        List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
        return getDataTable(list);
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, ${ClassName} ${className})
    {
        List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
        ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}.class);
        util.exportExcel(response, list, "${functionName}");
    }

    @GetMapping(value = "/{${pkColumn.javaField}}")
    public AjaxResult getInfo(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField})
    {
        return success(${className}Service.select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField}));
    }

    @Log(title = "${functionName}", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ${ClassName} ${className})
    {
        return toAjax(${className}Service.insert${ClassName}(${className}));
    }

    @Log(title = "${functionName}", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ${ClassName} ${className})
    {
        return toAjax(${className}Service.update${ClassName}(${className}));
    }

    @Log(title = "${functionName}", businessType = BusinessType.DELETE)
    @DeleteMapping("/{${pkColumn.javaField}s}")
    public AjaxResult remove(@PathVariable ${pkColumn.javaType}[] ${pkColumn.javaField}s)
    {
        return toAjax(${className}Service.delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaField}s));
    }

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
    @Log(title = "${action.name}", businessType = BusinessType.OTHER)
#if($action.method == "GET")
    @GetMapping("${action.path}")
    public AjaxResult ${action.code}(@RequestParam Map<String, Object> params)
    {
        return toAjax(${className}Service.${action.code}(params));
    }
#elseif($action.method == "PUT")
    @PutMapping("${action.path}")
    public AjaxResult ${action.code}(@RequestBody Map<String, Object> params)
    {
        return toAjax(${className}Service.${action.code}(params));
    }
#elseif($action.method == "DELETE")
    @DeleteMapping("${action.path}")
    public AjaxResult ${action.code}(@RequestBody(required = false) Map<String, Object> params)
    {
        return toAjax(${className}Service.${action.code}(params));
    }
#else
    @PostMapping("${action.path}")
    public AjaxResult ${action.code}(@RequestBody Map<String, Object> params)
    {
        return toAjax(${className}Service.${action.code}(params));
    }
#end

#end
#end
}
', 'admin', sysdate());

-- Admin frontend template files
INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910201, 9102, 'package.json.vm', NULL, 'package.json.vm',
'{
  "name": "${projectFileName}-admin",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "vue-cli-service serve --host 0.0.0.0",
    "serve": "vue-cli-service serve --host 0.0.0.0",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "axios": "1.7.2",
    "core-js": "3.37.1",
    "element-ui": "2.15.14",
    "vue": "2.6.14",
    "vue-router": "3.6.5",
    "vuex": "3.6.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "5.0.8",
    "@vue/cli-service": "5.0.8",
    "vue-template-compiler": "2.6.14"
  }
}
', 'admin', sysdate()),
(910202, 9102, 'api.js.vm', NULL, 'api.js.vm',
'import request from "@/utils/request"

const baseUrl = "/${moduleName}/${businessName}"

export function list${ClassName}(query) {
  return request({
    url: baseUrl + "/list",
    method: "get",
    params: query
  })
}

export function get${ClassName}(${pkColumn.javaField}) {
  return request({
    url: baseUrl + "/" + ${pkColumn.javaField},
    method: "get"
  })
}

export function add${ClassName}(data) {
  return request({
    url: baseUrl,
    method: "post",
    data
  })
}

export function update${ClassName}(data) {
  return request({
    url: baseUrl,
    method: "put",
    data
  })
}

export function del${ClassName}(${pkColumn.javaField}) {
  return request({
    url: baseUrl + "/" + ${pkColumn.javaField},
    method: "delete"
  })
}

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
export function ${action.code}(data) {
  return request({
    url: baseUrl + "${action.path}",
    method: "${action.method.toLowerCase()}",
#if($action.method == "GET")
    params: data
#else
    data
#end
  })
}

#end
#end
', 'admin', sysdate()),
(910203, 9102, 'index.vue.vm', NULL, 'index.vue.vm',
'<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
#foreach($column in $columns)
#if($column.isQuery == "1")
      <el-form-item label="${column.columnComment}" prop="${column.javaField}">
        <el-input
          v-model="queryParams.${column.javaField}"
          placeholder="璇疯緭鍏?{column.columnComment}"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
#end
#end
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">鎼滅储</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">閲嶇疆</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">鏂板</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="rows" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
#foreach($column in $columns)
#if($column.isList == "1")
      <el-table-column label="${column.columnComment}" align="center" prop="${column.javaField}" />
#end
#end
      <el-table-column label="鎿嶄綔" align="center" class-name="small-padding fixed-width" width="260">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">淇敼</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">鍒犻櫎</el-button>
#if($hasTableBusinessActions)
          <el-dropdown size="mini" @command="command => handleBusinessAction(scope.row, command)">
            <el-button type="text" size="mini">涓氬姟<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu slot="dropdown">
#foreach($action in $tableBusinessActions)
              <el-dropdown-item command="${action.code}">${action.name}</el-dropdown-item>
#end
            </el-dropdown-menu>
          </el-dropdown>
#end
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
#foreach($column in $columns)
#if($column.isEdit == "1" && $column.isPk != "1")
        <el-form-item label="${column.columnComment}" prop="${column.javaField}">
          <el-input v-model="form.${column.javaField}" placeholder="璇疯緭鍏?{column.columnComment}" />
        </el-form-item>
#end
#end
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">纭?瀹?/el-button>
        <el-button @click="cancel">鍙?娑?/el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ${className}Api from "@/api/${moduleName}/${businessName}"

export default {
  name: "${ClassName}",
  data() {
    return {
      loading: false,
      rows: [],
      ids: [],
      total: 0,
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      form: {},
      businessActions: [
#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
        { code: "${action.code}", name: "${action.name}" }#if($foreach.hasNext),#end
#end
#end
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      ${className}Api.list${ClassName}(this.queryParams).then(response => {
        this.rows = response.rows || response.data || []
        this.total = response.total || this.rows.length
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.${pkColumn.javaField})
    },
    handleAdd() {
      this.form = {}
      this.open = true
      this.title = "鏂板${functionName}"
    },
    handleUpdate(row) {
      const id = row.${pkColumn.javaField}
      ${className}Api.get${ClassName}(id).then(response => {
        this.form = response.data || {}
        this.open = true
        this.title = "淇敼${functionName}"
      })
    },
    submitForm() {
      const request = this.form.${pkColumn.javaField} ? ${className}Api.update${ClassName}(this.form) : ${className}Api.add${ClassName}(this.form)
      request.then(() => {
        this.#[[$modal]]#.msgSuccess("淇濆瓨鎴愬姛")
        this.open = false
        this.getList()
      })
    },
    handleDelete(row) {
      const id = row.${pkColumn.javaField}
      ${className}Api.del${ClassName}(id).then(() => {
        this.#[[$modal]]#.msgSuccess("鍒犻櫎鎴愬姛")
        this.getList()
      })
    },
    handleBusinessAction(row, actionCode) {
      const action = this.businessActions.find(item => item.code === actionCode)
      ${className}Api[actionCode]({ ...row }).then(() => {
        this.#[[$modal]]#.msgSuccess((action ? action.name : "涓氬姟鍔ㄤ綔") + "鎴愬姛")
        this.getList()
      })
    },
    cancel() {
      this.open = false
    }
  }
}
</script>
', 'admin', sysdate());

INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910204, 9102, 'adminMenus.js.vm', NULL, 'adminMenus.js.vm',
'export const appRoles = [
#foreach($role in $appRoles)
  { code: "${role.code}", name: "${role.name}", description: "${role.description}" }#if($foreach.hasNext),#end
#end
]

export const adminMenus = [
#foreach($menu in $adminMenus)
  {
    code: "${menu.code}",
    name: "${menu.name}",
    path: "${menu.path}",
    requiresLogin: ${menu.requiresLogin},
    visibleRoles: [
#foreach($role in $menu.visibleRoles)
      "${role}"#if($foreach.hasNext),#end
#end
    ],
    dataScope: "${menu.dataScope}"
  }#if($foreach.hasNext),#end
#end
]

export function requiresLogin(menu) {
  return Boolean(menu && menu.requiresLogin)
}

export function canShowMenu(menu, currentUser = {}) {
  if (!menu) {
    return false
  }
  if (menu.requiresLogin && !currentUser.id && !currentUser.userId) {
    return false
  }
  const userRoles = Array.isArray(currentUser.roles) ? currentUser.roles : []
  if (!Array.isArray(menu.visibleRoles) || menu.visibleRoles.length === 0) {
    return true
  }
  return menu.visibleRoles.some(role => userRoles.includes(role))
}
', 'admin', sysdate());

INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910205, 9102, 'adminPermission.js.vm', NULL, 'adminPermission.js.vm',
'import { adminMenus, canShowMenu, requiresLogin } from "./config/adminMenus"

function defaultCurrentUser() {
  try {
    return JSON.parse(localStorage.getItem("currentUser") || "{}")
  } catch (error) {
    return {}
  }
}

function isLoggedIn(user) {
  return Boolean(user && (user.id || user.userId))
}

export function installAdminGuard(router, getCurrentUser = defaultCurrentUser) {
  router.beforeEach((to, from, next) => {
    const menu = adminMenus.find(item => item.path === to.path)
    const user = getCurrentUser() || {}
    if (menu && !canShowMenu(menu, user)) {
      next(false)
      return
    }
    if (menu && requiresLogin(menu) && !isLoggedIn(user)) {
      next("/login")
      return
    }
    next()
  })
}
', 'admin', sysdate());

INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910206, 9102, 'index.html.vm', NULL, 'index.html.vm',
'<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>${projectName} Admin</title>
</head>
<body>
  <noscript>Please enable JavaScript.</noscript>
  <div id="app"></div>
</body>
</html>
', 'admin', sysdate()),
(910207, 9102, 'main.js.vm', NULL, 'main.js.vm',
'import Vue from "vue"
import ElementUI from "element-ui"
import "element-ui/lib/theme-chalk/index.css"
import App from "./App.vue"
import router from "./router"
import Pagination from "./components/Pagination.vue"

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.component("Pagination", Pagination)

Vue.prototype.#[[$modal]]# = {
  msgSuccess(message) {
    Vue.prototype.#[[$message]]#.success(message || "Success")
  },
  msgError(message) {
    Vue.prototype.#[[$message]]#.error(message || "Error")
  }
}

new Vue({
  router,
  render: h => h(App)
}).#[[$mount]]#("#app")
', 'admin', sysdate()),
(910208, 9102, 'App.vue.vm', NULL, 'App.vue.vm',
'<template>
  <el-container class="admin-shell">
    <el-aside width="220px" class="admin-aside">
      <div class="admin-brand">${projectName}</div>
      <el-menu router :default-active="#[[$route]]#.path" background-color="rgb(34, 45, 50)" text-color="rgb(191, 203, 217)" active-text-color="rgb(64, 158, 255)">
        <el-menu-item v-for="menu in visibleMenus" :key="menu.code" :index="menu.path">
          <i class="el-icon-menu"></i>
          <span slot="title">{{ menu.name }}</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header class="admin-header">
        <strong>{{ currentTitle }}</strong>
      </el-header>
      <el-main class="admin-main">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { adminMenus, canShowMenu } from "./config/adminMenus"

function previewRoles() {
  const roles = []
  adminMenus.forEach(menu => {
    if (Array.isArray(menu.visibleRoles)) {
      menu.visibleRoles.forEach(role => {
        if (roles.indexOf(role) === -1) {
          roles.push(role)
        }
      })
    }
  })
  return roles
}

function loadCurrentUser() {
  try {
    const user = JSON.parse(localStorage.getItem("currentUser") || "{}")
    if (user && (user.id || user.userId)) {
      return user
    }
  } catch (error) {
    return { id: "preview-admin", userId: "preview-admin", roles: previewRoles() }
  }
  return { id: "preview-admin", userId: "preview-admin", roles: previewRoles() }
}

export default {
  name: "App",
  data() {
    return {
      currentUser: loadCurrentUser()
    }
  },
  computed: {
    visibleMenus() {
      return adminMenus.filter(menu => canShowMenu(menu, this.currentUser))
    },
    currentTitle() {
      return this.#[[$route]]#.meta && this.#[[$route]]#.meta.title ? this.#[[$route]]#.meta.title : "Admin"
    }
  }
}
</script>

<style scoped>
.admin-shell {
  min-height: 100vh;
}

.admin-aside {
  background: rgb(34, 45, 50);
}

.admin-brand {
  height: 56px;
  line-height: 56px;
  padding: 0 16px;
  color: white;
  font-weight: 700;
  background: rgb(24, 144, 255);
}

.admin-header {
  display: flex;
  align-items: center;
  background: white;
  border-bottom: 1px solid rgb(232, 234, 237);
}

.admin-main {
  background: rgb(245, 247, 251);
}
</style>
', 'admin', sysdate()),
(910209, 9102, 'router.js.vm', NULL, 'router.js.vm',
'import Vue from "vue"
import Router from "vue-router"
import { adminMenus } from "../config/adminMenus"
import { installAdminGuard } from "../permission"
#foreach($table in $tables)
import ${table.className}View from "../views/${table.moduleName}/${table.businessName}/index.vue"
#end

Vue.use(Router)

#if($hasTables)
#set($firstTable = $tables.get(0))
const firstPath = "/${firstTable.moduleName}/${firstTable.businessName}"
#else
const firstPath = "/empty"
const Empty = {
  render(h) {
    return h("div", { class: "app-container" }, "No generated tables")
  }
}
#end

const routes = [
  {
    path: "/",
    redirect: firstPath
  }#if(!$hasTables),
  {
    path: "/empty",
    name: "Empty",
    component: Empty,
    meta: { title: "Admin" }
  }#end
#foreach($table in $tables),
  {
    path: "/${table.moduleName}/${table.businessName}",
    name: "${table.className}",
    component: ${table.className}View,
    meta: { title: "${table.functionName}" }
  }
#end
]

function previewRoles() {
  const roles = []
  adminMenus.forEach(menu => {
    if (Array.isArray(menu.visibleRoles)) {
      menu.visibleRoles.forEach(role => {
        if (roles.indexOf(role) === -1) {
          roles.push(role)
        }
      })
    }
  })
  return roles
}

function currentUser() {
  try {
    const user = JSON.parse(localStorage.getItem("currentUser") || "{}")
    if (user && (user.id || user.userId)) {
      return user
    }
  } catch (error) {
    return { id: "preview-admin", userId: "preview-admin", roles: previewRoles() }
  }
  return { id: "preview-admin", userId: "preview-admin", roles: previewRoles() }
}

const router = new Router({
  mode: "history",
  routes
})

installAdminGuard(router, currentUser)

export default router
', 'admin', sysdate()),
(910210, 9102, 'request.js.vm', NULL, 'request.js.vm',
'import axios from "axios"
import { Message } from "element-ui"

const service = axios.create({
  baseURL: "/api",
  timeout: 30000
})

service.interceptors.response.use(
  response => response.data,
  error => {
    Message.error(error && error.message ? error.message : "Request failed")
    return Promise.reject(error)
  }
)

export default service
', 'admin', sysdate()),
(910211, 9102, 'babel.config.js.vm', NULL, 'babel.config.js.vm',
'module.exports = {
  presets: [
    "@vue/cli-plugin-babel/preset"
  ]
}
', 'admin', sysdate()),
(910212, 9102, 'vue.config.js.vm', NULL, 'vue.config.js.vm',
'const port = process.env.PORT || 8081
const apiBaseUrl = process.env.VUE_APP_API_BASE_URL || "http://localhost:8080"

module.exports = {
  devServer: {
    host: "0.0.0.0",
    port: port,
    proxy: {
      "/api": {
        target: apiBaseUrl,
        changeOrigin: true,
        pathRewrite: {
          "^/api": ""
        }
      }
    }
  }
}
', 'admin', sysdate()),
(910213, 9102, 'Pagination.vue.vm', NULL, 'Pagination.vue.vm',
'<template>
  <div class="pagination-container">
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      @current-change="emitPagination"
      @size-change="emitPagination"
    />
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    total: {
      type: Number,
      default: 0
    },
    page: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 10
    }
  },
  computed: {
    currentPage: {
      get() {
        return this.page
      },
      set(value) {
        this.#[[$emit]]#("update:page", value)
      }
    },
    pageSize: {
      get() {
        return this.limit
      },
      set(value) {
        this.#[[$emit]]#("update:limit", value)
      }
    }
  },
  methods: {
    emitPagination() {
      this.#[[$emit]]#("pagination")
    }
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 16px;
  text-align: right;
}
</style>
', 'admin', sysdate());

-- Portal frontend template files
INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910301, 9103, 'package.json.vm', NULL, 'package.json.vm',
'{
  "name": "${projectFileName}-portal",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 0.0.0.0",
    "build": "vite build"
  },
  "dependencies": {
    "@vitejs/plugin-vue": "5.0.5",
    "axios": "1.7.2",
    "element-plus": "2.7.6",
    "vite": "5.3.1",
    "vue": "3.4.29",
    "vue-router": "4.4.0"
  },
  "devDependencies": {}
}
', 'admin', sysdate()),
(910302, 9103, 'index.html.vm', NULL, 'index.html.vm',
'<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>${projectName}</title>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="/src/main.js"></script>
</body>
</html>
', 'admin', sysdate()),
(910303, 9103, 'main.js.vm', NULL, 'main.js.vm',
'import { createApp } from "vue"
import ElementPlus from "element-plus"
import "element-plus/dist/index.css"
import App from "./App.vue"
import router from "./router"

createApp(App).use(router).use(ElementPlus).mount("#app")
', 'admin', sysdate()),
(910304, 9103, 'App.vue.vm', NULL, 'App.vue.vm',
'<template>
  <el-container class="shell">
    <el-header class="topbar">
      <strong>${projectName}</strong>
      <el-menu mode="horizontal" router :default-active="$route.path">
        <el-menu-item index="/">宸ヤ綔鍙?/el-menu-item>
        <el-menu-item v-for="menu in visibleMenus" :key="menu.code" :index="menu.path">
          {{ menu.name }}
        </el-menu-item>
      </el-menu>
    </el-header>
    <el-main>
      <router-view />
    </el-main>
  </el-container>
</template>

<script setup>
import { computed, ref } from "vue"
import { canShowMenu, frontendMenus } from "./config/frontendMenus"

function loadCurrentUser() {
  try {
    return JSON.parse(localStorage.getItem("currentUser") || "{}")
  } catch (error) {
    return {}
  }
}

const currentUser = ref(loadCurrentUser())
const visibleMenus = computed(() => frontendMenus.filter(menu => canShowMenu(menu, currentUser.value)))
</script>

<style scoped>
.shell {
  min-height: 100vh;
  background: #f6f8fb;
}
.topbar {
  display: flex;
  align-items: center;
  gap: 24px;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
}
</style>
', 'admin', sysdate()),
(910305, 9103, 'router.js.vm', NULL, 'router.js.vm',
'import { createRouter, createWebHistory } from "vue-router"
import { canShowMenu, frontendMenus, requiresLogin } from "../config/frontendMenus"
#foreach($table in $tables)
import ${table.className}Index from "../views/${table.businessName}/index.vue"
import ${table.className}Detail from "../views/${table.businessName}/detail.vue"
#end

const routes = [
#if($hasTables)
#set($firstTable = $tables.get(0))
  {
    path: "/",
    redirect: "/${firstTable.businessName}"
  },
#else
  {
    path: "/",
    component: { template: "<main />" }
  }
#end
#foreach($table in $tables)
  {
    path: "/${table.businessName}",
    component: ${table.className}Index
  },
  {
    path: "/${table.businessName}/:id",
    component: ${table.className}Detail
  }#if($foreach.hasNext),#end
#end
]

function currentUser() {
  try {
    return JSON.parse(localStorage.getItem("currentUser") || "{}")
  } catch (error) {
    return {}
  }
}

function isLoggedIn(user) {
  return Boolean(user && (user.id || user.userId))
}

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const menu = frontendMenus.find(item => item.path === to.path)
  const user = currentUser()
  if (menu && !canShowMenu(menu, user)) {
    next(false)
    return
  }
  if (menu && requiresLogin(menu) && !isLoggedIn(user)) {
    next("/login")
    return
  }
  next()
})

export default router
', 'admin', sysdate()),
(910306, 9103, 'request.js.vm', NULL, 'request.js.vm',
'import axios from "axios"
import { ElMessage } from "element-plus"

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || "",
  timeout: 15000
})

request.interceptors.response.use(
  response => response.data,
  error => {
    ElMessage.error(error.response?.data?.msg || error.message || "璇锋眰澶辫触")
    return Promise.reject(error)
  }
)

export default request
', 'admin', sysdate()),
(910307, 9103, 'api.js.vm', NULL, 'api.js.vm',
'import request from "./request"

const baseUrl = "/${moduleName}/${businessName}"

export function list${ClassName}(query) {
  return request({
    url: baseUrl + "/list",
    method: "get",
    params: query
  })
}

export function get${ClassName}(${pkColumn.javaField}) {
  return request({
    url: baseUrl + "/" + ${pkColumn.javaField},
    method: "get"
  })
}

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
export function ${action.code}(data) {
  return request({
    url: baseUrl + "${action.path}",
    method: "${action.method.toLowerCase()}",
#if($action.method == "GET")
    params: data
#else
    data
#end
  })
}

#end
#end
', 'admin', sysdate()),
(910308, 9103, 'index.vue.vm', NULL, 'index.vue.vm',
'<template>
  <section class="page">
    <div class="toolbar">
      <el-input v-model="keyword" placeholder="鎼滅储${functionName}" clearable @keyup.enter="loadData" />
      <el-button type="primary" @click="loadData">鎼滅储</el-button>
    </div>

    <el-table v-loading="loading" :data="rows" @row-click="openDetail">
#foreach($column in $columns)
#if($column.isList == "1")
      <el-table-column prop="${column.javaField}" label="${column.columnComment}" />
#end
#end
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click.stop="openDetail(row)">查看详情</el-button>
#if($hasListRowBusinessActions)
#foreach($action in $listRowBusinessActions)
          <el-button size="small" @click.stop="runAction(row, ${foreach.index})">${action.name}</el-button>
#end
#elseif($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
          <el-button size="small" @click.stop="runAction(row, ${foreach.index})">${action.name}</el-button>
#end
#end
        </template>
      </el-table-column>
    </el-table>
  </section>
</template>

<script setup>
import { onMounted, ref } from "vue"
import { useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import * as api from "../../api/${businessName}"

const router = useRouter()
const loading = ref(false)
const rows = ref([])
const keyword = ref("")
const actions = [
#if($hasListRowBusinessActions)
#foreach($action in $listRowBusinessActions)
  { code: "${action.code}", name: "${action.name}" }#if($foreach.hasNext),#end
#end
#elseif($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
  { code: "${action.code}", name: "${action.name}" }#if($foreach.hasNext),#end
#end
#end
]

function resolveSlotActions(slotActions, fallbackActions) {
  return slotActions.length ? slotActions : fallbackActions
}

function loadData() {
  loading.value = true
  api.list${ClassName}({ keyword: keyword.value }).then(res => {
    rows.value = res.rows || res.data || []
  }).finally(() => {
    loading.value = false
  })
}

function openDetail(row) {
  router.push("/${businessName}/" + row.${pkColumn.javaField})
}

function runAction(row, index) {
  const action = actions[index]
  if (!action || !api[action.code]) {
    return
  }
  api[action.code]({ ...row }).then(() => {
    ElMessage.success(action.name + "鎴愬姛")
    loadData()
  })
}

onMounted(loadData)
</script>

<style scoped>
.page {
  max-width: 1180px;
  margin: 0 auto;
}
.toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}
.muted {
  color: #909399;
}
</style>
', 'admin', sysdate()),
(910309, 9103, 'detail.vue.vm', NULL, 'detail.vue.vm',
'<template>
  <section class="detail">
    <el-page-header @back="router.back()" content="${functionName}璇︽儏" />
    <el-descriptions :column="2" border>
#foreach($column in $columns)
      <el-descriptions-item label="${column.columnComment}">{{ detail.${column.javaField} }}</el-descriptions-item>
#end
    </el-descriptions>
    <div class="actions">
#if($hasDetailPrimaryBusinessActions)
#foreach($action in $detailPrimaryBusinessActions)
      <el-button type="primary" @click="runAction(${foreach.index})">${action.name}</el-button>
#end
#elseif($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
      <el-button type="primary" @click="runAction(${foreach.index})">${action.name}</el-button>
#end
#end
    </div>
  </section>
</template>

<script setup>
import { onMounted, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import * as api from "../../api/${businessName}"

const route = useRoute()
const router = useRouter()
const detail = ref({})
const actions = [
#if($hasDetailPrimaryBusinessActions)
#foreach($action in $detailPrimaryBusinessActions)
  { code: "${action.code}", name: "${action.name}" }#if($foreach.hasNext),#end
#end
#elseif($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
  { code: "${action.code}", name: "${action.name}" }#if($foreach.hasNext),#end
#end
#end
]

function resolveSlotActions(slotActions, fallbackActions) {
  return slotActions.length ? slotActions : fallbackActions
}

function loadDetail() {
  api.get${ClassName}(route.params.id).then(res => {
    detail.value = res.data || res
  })
}

function runAction(index) {
  const action = actions[index]
  if (!action || !api[action.code]) {
    return
  }
  api[action.code]({ ...detail.value }).then(() => {
    ElMessage.success(action.name + "鎴愬姛")
    loadDetail()
  })
}

onMounted(loadDetail)
</script>

<style scoped>
.detail {
  max-width: 960px;
  margin: 0 auto;
}
.actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
}
</style>
', 'admin', sysdate());

INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(910310, 9103, 'frontendMenus.js.vm', NULL, 'frontendMenus.js.vm',
'export const appRoles = [
#foreach($role in $appRoles)
  { code: "${role.code}", name: "${role.name}", description: "${role.description}" }#if($foreach.hasNext),#end
#end
]

export const frontendMenus = [
#foreach($menu in $frontendMenus)
  {
    code: "${menu.code}",
    name: "${menu.name}",
    path: "${menu.path}",
    requiresLogin: ${menu.requiresLogin},
    visibleRoles: [
#foreach($role in $menu.visibleRoles)
      "${role}"#if($foreach.hasNext),#end
#end
    ],
    dataScope: "${menu.dataScope}"
  }#if($foreach.hasNext),#end
#end
]

export function requiresLogin(menu) {
  return Boolean(menu && menu.requiresLogin)
}

export function canShowMenu(menu, currentUser = {}) {
  if (!menu) {
    return false
  }
  if (menu.requiresLogin && !currentUser.id && !currentUser.userId) {
    return false
  }
  const userRoles = Array.isArray(currentUser.roles) ? currentUser.roles : []
  if (!Array.isArray(menu.visibleRoles) || menu.visibleRoles.length === 0) {
    return true
  }
  return menu.visibleRoles.some(role => userRoles.includes(role))
}
', 'admin', sysdate());

-- Backend project structure
INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910100, 0, '{projectName}-backend', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910101, 910100, 'pom.xml', 'file', NULL, 9101, -1, 'pom.xml.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910102, 910100, 'README.md', 'file', NULL, 9101, -1, 'README.md.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910103, 910100, 'src', 'folder', NULL, 9101, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(910104, 910103, 'main', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910105, 910104, 'java', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910106, 910105, '{packageName}', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910122, 910106, '{projectClassName}Application.java', 'file', NULL, 9101, -1, 'Application.java.vm', 0, '0', 'admin', sysdate(), '', NULL),
(910107, 910106, 'domain', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910108, 910106, 'mapper', 'folder', NULL, 9101, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(910109, 910106, 'service', 'folder', NULL, 9101, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(910110, 910109, 'impl', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910111, 910106, 'controller', 'folder', NULL, 9101, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(910112, 910104, 'resources', 'folder', NULL, 9101, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(910113, 910112, 'mapper', 'folder', NULL, 9101, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910114, 910113, '{moduleName}', 'folder', NULL, 9101, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910115, 910112, 'application.yml', 'file', NULL, 9101, -1, 'application.yml.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910116, 910107, '{ClassName}.java', 'file', NULL, 9101, 0, 'domain.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910117, 910108, '{ClassName}Mapper.java', 'file', NULL, 9101, 0, 'mapper.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910118, 910109, 'I{ClassName}Service.java', 'file', NULL, 9101, 0, 'service.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910119, 910110, '{ClassName}ServiceImpl.java', 'file', NULL, 9101, 0, 'serviceImpl.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910120, 910111, '{ClassName}Controller.java', 'file', NULL, 9101, 0, 'controller.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910121, 910114, '{ClassName}Mapper.xml', 'file', NULL, 9101, 0, 'mapper.xml.vm', 1, '0', 'admin', sysdate(), '', NULL);

-- Admin frontend project structure
INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910200, 0, '{projectName}-admin', 'folder', NULL, 9102, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910201, 910200, 'package.json', 'file', NULL, 9102, -1, 'package.json.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910202, 910200, 'src', 'folder', NULL, 9102, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(910203, 910202, 'api', 'folder', NULL, 9102, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910204, 910203, '{moduleName}', 'folder', NULL, 9102, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910205, 910204, '{businessName}.js', 'file', NULL, 9102, 0, 'api.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910206, 910202, 'views', 'folder', NULL, 9102, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(910207, 910206, '{moduleName}', 'folder', NULL, 9102, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910208, 910207, '{businessName}', 'folder', NULL, 9102, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910209, 910208, 'index.vue', 'file', NULL, 9102, 0, 'index.vue.vm', 1, '0', 'admin', sysdate(), '', NULL);

INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910210, 910202, 'config', 'folder', NULL, 9102, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(910211, 910210, 'adminMenus.js', 'file', NULL, 9102, -1, 'adminMenus.js.vm', 1, '0', 'admin', sysdate(), '', NULL);

INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910212, 910202, 'permission.js', 'file', NULL, 9102, -1, 'adminPermission.js.vm', 4, '0', 'admin', sysdate(), '', NULL);

INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910213, 910200, 'babel.config.js', 'file', NULL, 9102, -1, 'babel.config.js.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910214, 910200, 'vue.config.js', 'file', NULL, 9102, -1, 'vue.config.js.vm', 3, '0', 'admin', sysdate(), '', NULL),
(910215, 910200, 'public', 'folder', NULL, 9102, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(910216, 910215, 'index.html', 'file', NULL, 9102, -1, 'index.html.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910217, 910202, 'main.js', 'file', NULL, 9102, -1, 'main.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910218, 910202, 'App.vue', 'file', NULL, 9102, -1, 'App.vue.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910219, 910202, 'router', 'folder', NULL, 9102, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(910220, 910219, 'index.js', 'file', NULL, 9102, -1, 'router.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910221, 910202, 'utils', 'folder', NULL, 9102, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(910222, 910221, 'request.js', 'file', NULL, 9102, -1, 'request.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910223, 910202, 'components', 'folder', NULL, 9102, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(910224, 910223, 'Pagination.vue', 'file', NULL, 9102, -1, 'Pagination.vue.vm', 1, '0', 'admin', sysdate(), '', NULL);

-- Portal frontend project structure
INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910300, 0, '{projectName}-portal', 'folder', NULL, 9103, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910301, 910300, 'package.json', 'file', NULL, 9103, -1, 'package.json.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910302, 910300, 'index.html', 'file', NULL, 9103, -1, 'index.html.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910303, 910300, 'src', 'folder', NULL, 9103, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(910304, 910303, 'main.js', 'file', NULL, 9103, -1, 'main.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910305, 910303, 'App.vue', 'file', NULL, 9103, -1, 'App.vue.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910306, 910303, 'router', 'folder', NULL, 9103, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(910307, 910306, 'index.js', 'file', NULL, 9103, -1, 'router.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910308, 910303, 'api', 'folder', NULL, 9103, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(910309, 910308, 'request.js', 'file', NULL, 9103, -1, 'request.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910310, 910308, '{businessName}.js', 'file', NULL, 9103, 0, 'api.js.vm', 2, '0', 'admin', sysdate(), '', NULL),
(910311, 910303, 'views', 'folder', NULL, 9103, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(910312, 910311, '{businessName}', 'folder', NULL, 9103, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(910313, 910312, 'index.vue', 'file', NULL, 9103, 0, 'index.vue.vm', 1, '0', 'admin', sysdate(), '', NULL),
(910314, 910312, 'detail.vue', 'file', NULL, 9103, 0, 'detail.vue.vm', 2, '0', 'admin', sysdate(), '', NULL);

INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(910315, 910303, 'config', 'folder', NULL, 9103, NULL, NULL, 6, '0', 'admin', sysdate(), '', NULL),
(910316, 910315, 'frontendMenus.js', 'file', NULL, 9103, -1, 'frontendMenus.js.vm', 1, '0', 'admin', sysdate(), '', NULL);

SET FOREIGN_KEY_CHECKS = 1;

-- Runnable three-tier code generation templates
-- Import this script after sql/db.sql.
-- Template ids: 9201 backend, 9202 admin_frontend, 9203 frontend

SET FOREIGN_KEY_CHECKS = 0;

DELETE FROM sys_project_template WHERE template_id IN (9201, 9202, 9203);
DELETE FROM sys_project_structure WHERE template_id IN (9201, 9202, 9203) OR node_id BETWEEN 920100 AND 920399;
DELETE FROM sys_template_file WHERE template_id IN (9201, 9202, 9203) OR template_file_id BETWEEN 920100 AND 920399;
DELETE FROM sys_template WHERE template_id IN (9201, 9202, 9203);

INSERT INTO sys_template (template_id, template_name, template_path, template_desc, template_type, template_status, create_by, create_time, remark) VALUES
(9201, 'Runnable Backend Template', '/runnable/backend', 'Spring Boot + MyBatis Plus runnable backend', 'backend', 0, 'admin', sysdate(), 'three-tier runnable template'),
(9202, 'Runnable Admin Frontend Template', '/runnable/admin_frontend', 'Vue2 + Element UI runnable admin frontend', 'admin_frontend', 0, 'admin', sysdate(), 'three-tier runnable template'),
(9203, 'Runnable Portal Frontend Template', '/runnable/frontend', 'Vue2 + Element UI runnable portal frontend', 'frontend', 0, 'admin', sysdate(), 'three-tier runnable template');

-- Backend template files
INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(920101, 9201, 'pom.xml.vm', NULL, 'pom.xml.vm', '<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.9</version>
        <relativePath/>
    </parent>

    <groupId>${packageName}</groupId>
    <artifactId>${businessName}-service</artifactId>
    <version>1.0.0</version>
    <name>${functionName}</name>
    <description>${functionName} generated by qing template</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.20</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
', 'admin', sysdate()),
(920102, 9201, 'README.md.vm', NULL, 'README.md.vm', '# ${functionName}

这是由 qing 模板生成的单表 Spring Boot + Vue2 项目。

## 后端启动

1. 创建 MySQL 数据库，默认库名为 `vip`。
2. 执行 `sql/${businessName}.sql` 中的建表语句。
3. 按需修改 `src/main/resources/application.yml` 里的数据库账号密码。
4. 在项目根目录运行：

```bash
mvn spring-boot:run
```

The service starts at `http://localhost:8080`.

## 前端启动

```bash
cd vue
npm install
npm run dev
```

前端开发服务默认把 `/api` 代理到 `http://localhost:8080`。
', 'admin', sysdate()),
(920103, 9201, 'Application.java.vm', NULL, 'Application.java.vm', 'package ${packageName};

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("${packageName}.mapper")
@SpringBootApplication
public class ${ClassName}Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(${ClassName}Application.class, args);
    }
}
', 'admin', sysdate()),
(920104, 9201, 'Result.java.vm', NULL, 'Result.java.vm', 'package ${packageName}.common;

import java.io.Serializable;

public class Result<T> implements Serializable
{
    private static final long serialVersionUID = 1L;

    private String code;
    private String msg;
    private T data;

    public Result()
    {
    }

    public Result(String code, String msg, T data)
    {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> success()
    {
        return new Result<T>("200", "操作成功", null);
    }

    public static <T> Result<T> success(T data)
    {
        return new Result<T>("200", "操作成功", data);
    }

    public static <T> Result<T> error(String msg)
    {
        return new Result<T>("500", msg, null);
    }

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getMsg()
    {
        return msg;
    }

    public void setMsg(String msg)
    {
        this.msg = msg;
    }

    public T getData()
    {
        return data;
    }

    public void setData(T data)
    {
        this.data = data;
    }
}
', 'admin', sysdate()),
(920105, 9201, 'MybatisPlusConfig.java.vm', NULL, 'MybatisPlusConfig.java.vm', 'package ${packageName}.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig
{
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor()
    {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
', 'admin', sysdate()),
(920106, 9201, 'CorsConfig.java.vm', NULL, 'CorsConfig.java.vm', 'package ${packageName}.config;

import ${packageName}.security.PortalAuthInterceptor;
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer
{
    @Resource
    private PortalAuthInterceptor portalAuthInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry)
    {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(portalAuthInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/auth/login", "/auth/admin/login", "/business-blocks/**", "/files/**", "/error");
    }
}
', 'admin', sysdate()),
(920107, 9201, 'FileController.java.vm', NULL, 'FileController.java.vm', 'package ${packageName}.controller;

import ${packageName}.common.Result;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/files")
public class FileController
{
    private final Path uploadRoot = Paths.get("uploads");

    @PostMapping("/upload")
    public Result<Map<String, String>> upload(@RequestParam("file") MultipartFile file) throws IOException
    {
        Files.createDirectories(uploadRoot);
        String originalName = StringUtils.cleanPath(file.getOriginalFilename() == null ? "file" : file.getOriginalFilename());
        String suffix = "";
        int dotIndex = originalName.lastIndexOf(''.'');
        if (dotIndex >= 0)
        {
            suffix = originalName.substring(dotIndex);
        }
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        Files.copy(file.getInputStream(), uploadRoot.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);

        Map<String, String> data = new HashMap<String, String>();
        data.put("name", originalName);
        data.put("url", "/files/" + fileName);
        return Result.success(data);
    }

    @GetMapping("/{fileName:.+}")
    public ResponseEntity<Resource> getFile(@PathVariable String fileName) throws MalformedURLException
    {
        Path filePath = uploadRoot.resolve(fileName).normalize();
        Resource resource = new UrlResource(filePath.toUri());
        if (!resource.exists())
        {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\\"" + resource.getFilename() + "\\"")
                .body(resource);
    }
}
', 'admin', sysdate()),
(920108, 9201, 'application.yml.vm', NULL, 'application.yml.vm', '#set($d = ''$'')
server:
  port: ${d}{SERVER_PORT:8080}

spring:
  application:
    name: ${businessName}-service
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: ${d}{DB_URL:jdbc:mysql://localhost:3306/vip?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8}
    username: ${d}{DB_USERNAME:root}
    password: ${d}{DB_PASSWORD:[REDACTED]
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

mybatis-plus:
  mapper-locations: classpath*:mapper/**/*.xml
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
', 'admin', sysdate()),
(920109, 9201, 'entity.java.vm', NULL, 'entity.java.vm', 'package ${packageName}.entity;

#foreach ($import in $importList)
import ${import};
#end
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import cn.hutool.core.annotation.Alias;

/**
 * ${functionName}对象 ${tableName}
 *
 * @author ${author}
 * @date ${datetime}
 */
#if($table.crud || $table.sub)
#set($Entity="BaseEntity")
#elseif($table.tree)
#set($Entity="TreeEntity")
#end
@Getter
@Setter
@Accessors(chain = true)
@ApiModel(value = "${ClassName}对象", description = "${functionName}")
@TableName("${tableName}")
public class ${ClassName}
{
    private static final long serialVersionUID = 1L;

#foreach ($column in $columns)
    /** $column.columnComment */
#if($column.list)
#set($parentheseIndex=$column.columnComment.indexOf("（"))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.javaType == ''Date'')
    @JsonFormat(pattern = "yyyy-MM-dd")
#else
#end
#end
    @ApiModelProperty("${column.columnComment}")
    @Alias("${column.columnComment}")
#if ($column.isPk == "1")
    @TableId(value = "${column.columnName}", type = IdType.AUTO)
#else
    @TableField("${column.columnName}")
#end
    private $column.javaType $column.javaField;

#end
#if($table.sub)
    /** $table.subTable.functionName信息 */
    @ApiModelProperty("${table.subTable.functionName}信息")
    private List<${subClassName}> ${subclassName}List;

#end
    @Override
    public String toString() {
        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
#foreach ($column in $columns)
#if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]"))
#set($AttrName=$column.javaField)
#else
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#end
            .append("${column.javaField}", get${AttrName}())
#end
#if($table.sub)
            .append("${subclassName}List", get${subClassName}List())
#end
            .toString();
    }
}
', 'admin', sysdate()),
(920110, 9201, 'mapper.java.vm', NULL, 'mapper.java.vm', 'package ${packageName}.mapper;

import ${packageName}.entity.${ClassName};
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * ${functionName}Mapper接口
 *
 * @author ${author}
 * @date ${datetime}
 */
public interface ${ClassName}Mapper extends BaseMapper<${ClassName}> {

}
', 'admin', sysdate()),
(920111, 9201, 'service.java.vm', NULL, 'service.java.vm', 'package ${packageName}.service;

import ${packageName}.entity.${ClassName};
import com.baomidou.mybatisplus.extension.service.IService;
#if($hasTableBusinessActions)
import java.util.Map;
#end

/**
 * ${functionName}Service接口
 *
 * @author ${author}
 * @date ${datetime}
 */
public interface I${ClassName}Service extends IService<${ClassName}> {

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
    int ${action.code}(Map<String, Object> params);

#end
#end
}
', 'admin', sysdate()),
(920112, 9201, 'serviceImpl.java.vm', NULL, 'serviceImpl.java.vm', 'package ${packageName}.service.impl;

import ${packageName}.entity.${ClassName};
import ${packageName}.mapper.${ClassName}Mapper;
import ${packageName}.service.I${ClassName}Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
#if($hasTableBusinessActions)
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
#end
import org.springframework.stereotype.Service;

/**
 * ${functionName}Service业务层处理
 *
 * @author ${author}
 * @date ${datetime}
 */
@Service
public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper, ${ClassName}> implements I${ClassName}Service {

#if($hasTableBusinessActions)
    // STRICT_TARGET_TABLE_CONDITIONS
    @Resource
    private JdbcTemplate jdbcTemplate;

#foreach($action in $tableBusinessActions)
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int ${action.code}(Map<String, Object> params)
    {
        if (params == null)
        {
            throw new IllegalArgumentException("业务动作参数不能为空");
        }
#if($action.requestFields)
#foreach($field in $action.requestFields)
        requireBusinessParam(params, "${field}");
#end
#end
#if($action.ruleChecks)
#foreach($rule in $action.ruleChecks)
#set($conditionFields = $rule.conditionFields)
#if($rule.type == "EXISTS")
        assertExists(params, "${rule.targetTable}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "NOT_EXISTS")
        assertNotExists(params, "${rule.targetTable}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "FIELD_EQUALS")
        assertFieldEquals(params, "${rule.targetTable}", "${rule.targetField}", "${rule.expectedValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "FIELD_NOT_EQUALS")
        assertFieldNotEquals(params, "${rule.targetTable}", "${rule.targetField}", "${rule.expectedValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "FIELD_IN")
        assertFieldIn(params, "${rule.targetTable}", "${rule.targetField}", new String[] {#foreach($value in $rule.expectedValues)"${value}"#if($foreach.hasNext), #end#end}, new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#elseif($rule.type == "NUMBER_GTE")
        assertNumberGte(params, "${rule.targetTable}", "${rule.targetField}", "${rule.compareValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${rule.message}");
#end
#end
#end
        int rows = 0;
#if($action.effects)
#foreach($effect in $action.effects)
#if($effect.type == "UPDATE_FIELD")
#set($conditionFields = $effect.conditionFields)
        rows += executeUpdateFieldEffect(params, "${effect.targetTable}", "${effect.targetField}", "${effect.value}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "INSERT_ROW")
#set($effectIndex = $foreach.index)
        Map<String, Object> insertValues${effectIndex} = new java.util.LinkedHashMap<String, Object>();
#foreach($entry in $effect.values.entrySet())
        insertValues${effectIndex}.put("${entry.key}", resolveBusinessValue(params, "${entry.value}"));
#end
        rows += insertRow("${effect.targetTable}", insertValues${effectIndex});
#elseif($effect.type == "UPDATE_FIELDS")
#set($conditionFields = $effect.conditionFields)
#set($effectIndex = $foreach.index)
        Map<String, Object> updateValues${effectIndex} = new java.util.LinkedHashMap<String, Object>();
#foreach($entry in $effect.values.entrySet())
        updateValues${effectIndex}.put("${entry.key}", resolveBusinessValue(params, "${entry.value}"));
#end
        rows += updateFields(params, "${effect.targetTable}", updateValues${effectIndex}, new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "SET_STATUS")
#set($conditionFields = $effect.conditionFields)
        rows += setStatus(params, "${effect.targetTable}", "${effect.targetField}", resolveBusinessValue(params, "${effect.value}"), new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "INCREASE_NUMBER")
#set($conditionFields = $effect.conditionFields)
        rows += increaseNumberField(params, "${effect.targetTable}", "${effect.targetField}", "${effect.amount}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end});
#elseif($effect.type == "DECREASE_NUMBER")
#set($conditionFields = $effect.conditionFields)
        rows += decreaseNumberField(params, "${effect.targetTable}", "${effect.targetField}", "${effect.amount}", "${effect.minValue}", new String[] {#foreach($field in $conditionFields)"${field}"#if($foreach.hasNext), #end#end}, "${effect.message}");
#end
#end
#end
        return rows;
    }

#end
    private void requireBusinessParam(Map<String, Object> params, String field)
    {
        if (!params.containsKey(field) || params.get(field) == null || String.valueOf(params.get(field)).trim().isEmpty())
        {
            throw new IllegalArgumentException("缺少业务动作参数：" + field);
        }
    }

    private void assertExists(Map<String, Object> params, String tableName, String[] conditionFields, String message)
    {
        if (countRows(params, tableName, conditionFields) <= 0)
        {
            throw new IllegalArgumentException(defaultMessage(message, "业务记录不存在"));
        }
    }

    private void assertNotExists(Map<String, Object> params, String tableName, String[] conditionFields, String message)
    {
        if (countRows(params, tableName, conditionFields) > 0)
        {
            throw new IllegalArgumentException(defaultMessage(message, "业务记录已存在"));
        }
    }

    private void assertFieldEquals(Map<String, Object> params, String tableName, String targetField,
                                   String expectedValue, String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        if (value == null || !String.valueOf(resolveBusinessValue(params, expectedValue)).equals(String.valueOf(value)))
        {
            throw new IllegalArgumentException(defaultMessage(message, "业务规则校验失败"));
        }
    }

    private void assertFieldNotEquals(Map<String, Object> params, String tableName, String targetField,
                                      String expectedValue, String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        if (value != null && String.valueOf(resolveBusinessValue(params, expectedValue)).equals(String.valueOf(value)))
        {
            throw new IllegalArgumentException(defaultMessage(message, "业务规则校验失败"));
        }
    }

    private void assertFieldIn(Map<String, Object> params, String tableName, String targetField,
                               String[] expectedValues, String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        String current = value == null ? "" : String.valueOf(value);
        for (String expectedValue : expectedValues)
        {
            if (String.valueOf(resolveBusinessValue(params, expectedValue)).equals(current))
            {
                return;
            }
        }
        throw new IllegalArgumentException(defaultMessage(message, "业务规则校验失败"));
    }

    private void assertNumberGte(Map<String, Object> params, String tableName, String targetField,
                                 String compareValue, String[] conditionFields, String message)
    {
        Object value = querySingleField(params, tableName, targetField, conditionFields);
        BigDecimal current = toBigDecimal(value, "业务数值无效");
        BigDecimal expected = resolveBusinessNumber(params, compareValue);
        if (current.compareTo(expected) < 0)
        {
            throw new IllegalArgumentException(defaultMessage(message, "业务数值校验失败"));
        }
    }

    private int insertRow(String tableName, Map<String, Object> values)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务动作目标表无效");
        if (values == null || values.isEmpty())
        {
            throw new IllegalArgumentException("业务新增字段不能为空");
        }
        StringBuilder fields = new StringBuilder();
        StringBuilder placeholders = new StringBuilder();
        List<Object> args = new ArrayList<Object>();
        for (Map.Entry<String, Object> entry : values.entrySet())
        {
            if (fields.length() > 0)
            {
                fields.append(", ");
                placeholders.append(", ");
            }
            fields.append(requireSafeIdentifier(entry.getKey(), "业务新增字段无效"));
            placeholders.append("?");
            args.add(entry.getValue());
        }
        return jdbcTemplate.update("insert into " + safeTableName + " (" + fields + ") values (" + placeholders + ")",
                args.toArray());
    }

    private int updateFields(Map<String, Object> params, String tableName, Map<String, Object> values,
                             String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务动作目标表无效");
        if (values == null || values.isEmpty())
        {
            throw new IllegalArgumentException("业务更新字段不能为空");
        }
        StringBuilder sets = new StringBuilder();
        List<Object> args = new ArrayList<Object>();
        for (Map.Entry<String, Object> entry : values.entrySet())
        {
            if (sets.length() > 0)
            {
                sets.append(", ");
            }
            sets.append(requireSafeIdentifier(entry.getKey(), "业务更新字段无效")).append(" = ?");
            args.add(entry.getValue());
        }
        String whereClause = buildWhereClause(params, conditionFields);
        appendConditionValues(args, params, conditionFields);
        return jdbcTemplate.update("update " + safeTableName + " set " + sets + " where " + whereClause,
                args.toArray());
    }

    private int setStatus(Map<String, Object> params, String tableName, String targetField, Object value,
                          String[] conditionFields)
    {
        Map<String, Object> values = new java.util.LinkedHashMap<String, Object>();
        values.put(targetField, value);
        return updateFields(params, tableName, values, conditionFields);
    }

    private int increaseNumberField(Map<String, Object> params, String tableName, String targetField,
                                    String amountExpression, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务动作目标表无效");
        String safeTargetField = requireSafeIdentifier(targetField, "业务动作目标字段无效");
        BigDecimal amount = resolveBusinessNumber(params, amountExpression);
        String whereClause = buildWhereClause(params, conditionFields);
        List<Object> args = new ArrayList<Object>();
        args.add(amount);
        appendConditionValues(args, params, conditionFields);
        return jdbcTemplate.update("update " + safeTableName + " set " + safeTargetField + " = "
                + safeTargetField + " + ? where " + whereClause, args.toArray());
    }

    private int decreaseNumberField(Map<String, Object> params, String tableName, String targetField,
                                    String amountExpression, String minValueExpression,
                                    String[] conditionFields, String message)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务动作目标表无效");
        String safeTargetField = requireSafeIdentifier(targetField, "业务动作目标字段无效");
        BigDecimal amount = resolveBusinessNumber(params, amountExpression);
        BigDecimal minValue = resolveBusinessNumber(params,
                minValueExpression == null || minValueExpression.length() == 0 ? "0" : minValueExpression);
        String whereClause = buildWhereClause(params, conditionFields);
        List<Object> args = new ArrayList<Object>();
        args.add(amount);
        appendConditionValues(args, params, conditionFields);
        args.add(amount);
        args.add(minValue);
        int rows = jdbcTemplate.update("update " + safeTableName + " set " + safeTargetField + " = "
                + safeTargetField + " - ? where " + whereClause + " and " + safeTargetField + " - ? >= ?",
                args.toArray());
        if (rows == 0)
        {
            throw new IllegalArgumentException(defaultMessage(message, "业务数值扣减失败"));
        }
        return rows;
    }

    private int executeUpdateFieldEffect(Map<String, Object> params, String tableName, String targetField,
                                         String valueExpression, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务动作目标表无效");
        String safeTargetField = requireSafeIdentifier(targetField, "业务动作目标字段无效");
        String safeValueExpression = requireSafeExpression(valueExpression);
        String whereClause = buildWhereClause(params, conditionFields);
        return jdbcTemplate.update("update " + safeTableName + " set " + safeTargetField + " = "
                + safeValueExpression + " where " + whereClause, conditionValues(params, conditionFields));
    }

    private String buildWhereClause(Map<String, Object> params, String[] conditionFields)
    {
        if (conditionFields == null || conditionFields.length == 0)
        {
            throw new IllegalArgumentException("业务动作条件字段不能为空");
        }
        StringBuilder where = new StringBuilder();
        for (String field : conditionFields)
        {
            String safeField = requireSafeIdentifier(field, "业务动作条件字段无效");
            requireBusinessParam(params, safeField);
            if (where.length() > 0)
            {
                where.append(" and ");
            }
            where.append(safeField).append(" = ?");
        }
        return where.toString();
    }

    private Object[] conditionValues(Map<String, Object> params, String[] conditionFields)
    {
        Object[] values = new Object[conditionFields.length];
        for (int i = 0; i < conditionFields.length; i++)
        {
            values[i] = params.get(conditionFields[i]);
        }
        return values;
    }

    private int countRows(Map<String, Object> params, String tableName, String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务规则目标表无效");
        String whereClause = buildWhereClause(params, conditionFields);
        Integer count = jdbcTemplate.queryForObject("select count(1) from " + safeTableName + " where "
                + whereClause, conditionValues(params, conditionFields), Integer.class);
        return count == null ? 0 : count.intValue();
    }

    private Object querySingleField(Map<String, Object> params, String tableName, String targetField,
                                    String[] conditionFields)
    {
        String safeTableName = requireSafeIdentifier(tableName, "业务规则目标表无效");
        String safeTargetField = requireSafeIdentifier(targetField, "业务规则目标字段无效");
        String whereClause = buildWhereClause(params, conditionFields);
        List<Map<String, Object>> rows = jdbcTemplate.queryForList("select " + safeTargetField + " from "
                + safeTableName + " where " + whereClause + " limit 1", conditionValues(params, conditionFields));
        return rows.isEmpty() ? null : rows.get(0).get(safeTargetField);
    }

    private void appendConditionValues(List<Object> args, Map<String, Object> params, String[] conditionFields)
    {
        for (Object value : conditionValues(params, conditionFields))
        {
            args.add(value);
        }
    }

    private Object resolveBusinessValue(Map<String, Object> params, String valueExpression)
    {
        if (valueExpression == null)
        {
            return null;
        }
        if ("#[[${now}]]#".equals(valueExpression))
        {
            return new Date();
        }
        if ("#[[${current_user.id}]]#".equals(valueExpression)
                || "#[[${current_user_id}]]#".equals(valueExpression))
        {
            requireBusinessParam(params, "__currentUserId");
            return params.get("__currentUserId");
        }
        if (valueExpression.startsWith("#[[${param.]]#") && valueExpression.endsWith("}"))
        {
            String field = valueExpression.substring(8, valueExpression.length() - 1);
            requireBusinessParam(params, field);
            return params.get(field);
        }
        return valueExpression;
    }

    private BigDecimal resolveBusinessNumber(Map<String, Object> params, String valueExpression)
    {
        return toBigDecimal(resolveBusinessValue(params, valueExpression), "业务数值表达式无效");
    }

    private BigDecimal toBigDecimal(Object value, String message)
    {
        try
        {
            return new BigDecimal(String.valueOf(value));
        }
        catch (RuntimeException e)
        {
            throw new IllegalArgumentException(message);
        }
    }

    private String defaultMessage(String message, String fallback)
    {
        return message == null || message.length() == 0 ? fallback : message;
    }

    private String requireSafeIdentifier(String value, String message)
    {
        if (value == null || !value.matches("[A-Za-z][A-Za-z0-9_]*"))
        {
            throw new IllegalArgumentException(message);
        }
        return value;
    }

    private String requireSafeExpression(String valueExpression)
    {
        if (valueExpression == null || !valueExpression.matches("[A-Za-z0-9_ +*/().-]{1,200}")
                || valueExpression.contains(";") || valueExpression.contains("--"))
        {
            throw new IllegalArgumentException("业务动作表达式无效");
        }
        return valueExpression;
    }
#end
}
', 'admin', sysdate()),
(920113, 9201, 'controller.java.vm', NULL, 'controller.java.vm', 'package ${packageName}.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${packageName}.common.Result;
import ${packageName}.entity.${ClassName};
#if($hasQingCurrentUserColumn || $hasTableBusinessActions)
import ${packageName}.entity.PortalUser;
import ${packageName}.security.PortalAuthTokenStore;
#end
import ${packageName}.service.I${ClassName}Service;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
#if($hasQingCurrentUserColumn || $hasTableBusinessActions)
import javax.servlet.http.HttpServletRequest;
#end
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * ${functionName}Controller
 *
 * @author ${author}
 * @date ${datetime}
 */
@RestController
public class ${ClassName}Controller
{
    @Resource
    private I${ClassName}Service ${className}Service;

#if($hasQingCurrentUserColumn || $hasTableBusinessActions)
    @Resource
    private PortalAuthTokenStore tokenStore;

#end

    #if($allowAdd == ''1'' || $allowEdit == ''1'')
    @PostMapping("/${moduleName}/${businessName}")
    public Result<Void> save(@RequestBody ${ClassName} ${className})
    {
        #if($allowAdd == ''1'' && $allowEdit == ''1'')
        ${className}Service.saveOrUpdate(${className});
        #elseif($allowAdd == ''1'')
        ${className}Service.save(${className});
        #else
        ${className}Service.updateById(${className});
        #end
        return Result.success();
    }
    #end

    #if($allowRemove == ''1'')
    @DeleteMapping("/${moduleName}/${businessName}/{${pkColumn.javaField}}")
    public Result<Void> delete(@PathVariable ${pkColumn.javaType} ${pkColumn.javaField})
    {
        ${className}Service.removeById(${pkColumn.javaField});
        return Result.success();
    }

    @PostMapping("/${moduleName}/${businessName}/del/batch")
    public Result<Void> deleteBatch(@RequestBody List<${pkColumn.javaType}> ${pkColumn.javaField}s)
    {
        ${className}Service.removeByIds(${pkColumn.javaField}s);
        return Result.success();
    }
    #end

    @GetMapping("/${moduleName}/${businessName}")
    public Result<List<${ClassName}>> findAll()
    {
        return Result.success(${className}Service.list());
    }

    @GetMapping("/${moduleName}/${businessName}/{${pkColumn.javaField}}")
    public Result<${ClassName}> findOne(@PathVariable ${pkColumn.javaType} ${pkColumn.javaField})
    {
        return Result.success(${className}Service.getById(${pkColumn.javaField}));
    }

    @GetMapping("/${moduleName}/${businessName}/page")
    public Result<Page<${ClassName}>> findPage(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                               @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                               @RequestParam(required = false) Map<String, Object> params#if($hasQingCurrentUserColumn),
                                               HttpServletRequest request#end)
    {
        QueryWrapper<${ClassName}> queryWrapper = new QueryWrapper<${ClassName}>();
#if($hasQingCurrentUserColumn)
        if (isCurrentUserOnly(params))
        {
            PortalUser currentUser = tokenStore.getPortalUser(resolveToken(request));
            if (currentUser == null)
            {
                return Result.success(new Page<${ClassName}>(pageNum, pageSize));
            }
            queryWrapper.eq("${qingCurrentUserColumn.columnName}", currentUser.getUserId());
        }
#end
#foreach ($column in $columns)
#if($column.isQuery == "1")
#set($queryType=$column.queryType)
#set($javaField=$column.javaField)
#set($columnName=$column.columnName)
#if($queryType == "EQ")
        queryWrapper.eq(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "NE")
        queryWrapper.ne(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "GT")
        queryWrapper.gt(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "GTE")
        queryWrapper.ge(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "LT")
        queryWrapper.lt(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "LTE")
        queryWrapper.le(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "LIKE")
        queryWrapper.like(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#else
        queryWrapper.eq(hasValue(params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#end
#end
#end
        queryWrapper.orderByDesc("${pkColumn.columnName}");
        return Result.success(${className}Service.page(new Page<${ClassName}>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/${moduleName}/${businessName}/export")
    public void export(HttpServletResponse response) throws Exception
    {
        List<${ClassName}> list = ${className}Service.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("${functionName}信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    #if($allowAdd == ''1'')
    @PostMapping("/${moduleName}/${businessName}/import")
    public Result<Void> imp(MultipartFile file) throws Exception
    {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<${ClassName}> list = reader.readAll(${ClassName}.class);
        ${className}Service.saveBatch(list);
        return Result.success();
    }
    #end

#if($hasTableBusinessActions)
#foreach($action in $tableBusinessActions)
#if($action.method == "GET")
    @GetMapping("${action.path}")
    public Result<Integer> ${action.code}(@RequestParam(required = false) Map<String, Object> params,
                                          HttpServletRequest request)
#elseif($action.method == "PUT")
    @org.springframework.web.bind.annotation.PutMapping("${action.path}")
    public Result<Integer> ${action.code}(@RequestBody(required = false) Map<String, Object> params,
                                          HttpServletRequest request)
#elseif($action.method == "DELETE")
    @DeleteMapping("${action.path}")
    public Result<Integer> ${action.code}(@RequestBody(required = false) Map<String, Object> params,
                                          HttpServletRequest request)
#else
    @PostMapping("${action.path}")
    public Result<Integer> ${action.code}(@RequestBody(required = false) Map<String, Object> params,
                                          HttpServletRequest request)
#end
    {
        try
        {
            Map<String, Object> actionParams = prepareBusinessActionParams(params, request, new String[] {#foreach($field in $action.currentUserFields)"${field}"#if($foreach.hasNext), #end#end});
            return Result.success(${className}Service.${action.code}(actionParams));
        }
        catch (RuntimeException e)
        {
            return Result.error(e.getMessage());
        }
    }

#end
    private Map<String, Object> prepareBusinessActionParams(Map<String, Object> params, HttpServletRequest request,
                                                             String[] currentUserFields)
    {
        Map<String, Object> actionParams = params == null
                ? new LinkedHashMap<String, Object>()
                : new LinkedHashMap<String, Object>(params);
        PortalUser currentUser = tokenStore.getPortalUser(resolveToken(request));
        if (currentUser == null)
        {
            throw new IllegalArgumentException("请先登录");
        }
        actionParams.put("__currentUserId", currentUser.getUserId());
        if (currentUserFields != null)
        {
            for (String field : currentUserFields)
            {
                if (StringUtils.isNotBlank(field))
                {
                    if ("username".equals(field) || "user_name".equals(field))
                    {
                        actionParams.put(field, currentUser.getUsername());
                    }
                    else
                    {
                        actionParams.put(field, currentUser.getUserId());
                    }
                }
            }
        }
        return actionParams;
    }

#end
    private boolean hasValue(Object value)
    {
        return value != null && StringUtils.isNotBlank(String.valueOf(value));
    }

#if($hasQingCurrentUserColumn)
    private boolean isCurrentUserOnly(Map<String, Object> params)
    {
        return params != null && "true".equalsIgnoreCase(String.valueOf(params.get("__currentUserOnly")));
    }

#end
#if($hasQingCurrentUserColumn || $hasTableBusinessActions)
    private String resolveToken(HttpServletRequest request)
    {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer "))
        {
            return authorization.substring("Bearer ".length());
        }
        return request.getHeader("X-Portal-Token");
    }
#end
}
', 'admin', sysdate()),
(920114, 9201, 'mapper.xml.vm', NULL, 'mapper.xml.vm', '<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${packageName}.mapper.${ClassName}Mapper">

    <!-- 通用查询映射结果 -->
    <resultMap type="${packageName}.entity.${ClassName}" id="BaseResultMap">
#foreach ($column in $columns)
#if ($column.isPk == "1")
        <id column="${column.columnName}" property="${column.javaField}"/>
#else
        <result column="${column.columnName}" property="${column.javaField}"/>
#end
#end
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
#foreach ($column in $columns)
        ${column.columnName}#if($foreach.count != $columns.size()),#end

#end
    </sql>

</mapper>
', 'admin', sysdate()),
(920115, 9201, 'sql.vm', NULL, 'sql.vm', '-- ${functionName} table
-- Generated by qing template at ${datetime}

${table.createTableSql}

create table if not exists t_admin (
  admin_id bigint not null auto_increment comment ''Admin ID'',
  username varchar(64) not null comment ''Username'',
  password_hash varchar(64) not null comment ''SHA-256 password hash'',
  nickname varchar(64) default null comment ''Nickname'',
  status char(1) default ''0'' comment ''Status, 0 normal 1 disabled'',
  create_time datetime default current_timestamp comment ''Create time'',
  primary key (admin_id),
  unique key uk_t_admin_username (username)
) engine=innodb default charset=utf8mb4 comment=''Admin user table'';

insert into t_admin (username, password_hash, nickname, status)
select ''admin'',
       ''8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92'',
       ''Administrator'',
       ''0''
where not exists (select 1 from t_admin where username = ''admin'');

create table if not exists t_user (
  user_id bigint not null auto_increment comment ''User ID'',
  username varchar(64) not null comment ''Username'',
  password_hash varchar(64) not null comment ''SHA-256 password hash'',
  nickname varchar(64) default null comment ''Nickname'',
  status char(1) default ''0'' comment ''Status, 0 normal 1 disabled'',
  create_time datetime default current_timestamp comment ''Create time'',
  primary key (user_id),
  unique key uk_t_user_username (username)
) engine=innodb default charset=utf8mb4 comment=''Portal user table'';

insert into t_user (username, password_hash, nickname, status)
select ''user'',
       ''8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92'',
       ''User'',
       ''0''
where not exists (select 1 from t_user where username = ''user'');
', 'admin', sysdate()),
(920116, 9201, 'PortalUser.java.vm', NULL, 'PortalUser.java.vm', 'package ${packageName}.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Getter
@Setter
@Accessors(chain = true)
@TableName("t_user")
public class PortalUser
{
    @TableId(value = "user_id", type = IdType.AUTO)
    private Long userId;

    private String username;

    private String passwordHash;

    private String nickname;

    private String status;
}
', 'admin', sysdate()),
(920117, 9201, 'PortalUserMapper.java.vm', NULL, 'PortalUserMapper.java.vm', 'package ${packageName}.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ${packageName}.entity.PortalUser;

public interface PortalUserMapper extends BaseMapper<PortalUser>
{
}
', 'admin', sysdate()),
(920118, 9201, 'PortalAuthTokenStore.java.vm', NULL, 'PortalAuthTokenStore.java.vm', 'package ${packageName}.security;

import ${packageName}.entity.AdminUser;
import ${packageName}.entity.PortalUser;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Component;

@Component
public class PortalAuthTokenStore
{
    private final Map<String, Object> sessions = new ConcurrentHashMap<String, Object>();

    public String issue(Object user)
    {
        String token = UUID.randomUUID().toString().replace("-", "");
        sessions.put(token, user);
        return token;
    }

    public Object getUser(String token)
    {
        if (token == null || token.trim().isEmpty())
        {
            return null;
        }
        return sessions.get(token);
    }

    public PortalUser getPortalUser(String token)
    {
        Object user = getUser(token);
        return user instanceof PortalUser ? (PortalUser) user : null;
    }

    public AdminUser getAdminUser(String token)
    {
        Object user = getUser(token);
        return user instanceof AdminUser ? (AdminUser) user : null;
    }

    public boolean validate(String token)
    {
        return getUser(token) != null;
    }

    public void revoke(String token)
    {
        if (token != null)
        {
            sessions.remove(token);
        }
    }
}
', 'admin', sysdate()),
(920119, 9201, 'PortalAuthInterceptor.java.vm', NULL, 'PortalAuthInterceptor.java.vm', 'package ${packageName}.security;

import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class PortalAuthInterceptor implements HandlerInterceptor
{
    @Resource
    private PortalAuthTokenStore tokenStore;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException
    {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
        {
            return true;
        }

        String token = resolveToken(request);
        if (tokenStore.validate(token))
        {
            return true;
        }

        response.setStatus(401);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\\"code\\":\\"401\\",\\"msg\\":\\"请先登录\\",\\"data\\":null}");
        return false;
    }

    private String resolveToken(HttpServletRequest request)
    {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer "))
        {
            return authorization.substring("Bearer ".length());
        }
        return request.getHeader("X-Portal-Token");
    }
}
', 'admin', sysdate()),
(920120, 9201, 'PortalAuthController.java.vm', NULL, 'PortalAuthController.java.vm', 'package ${packageName}.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ${packageName}.common.Result;
import ${packageName}.entity.PortalUser;
import ${packageName}.mapper.PortalUserMapper;
import ${packageName}.security.PortalAuthTokenStore;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
public class PortalAuthController
{
    @Resource
    private PortalUserMapper portalUserMapper;

    @Resource
    private PortalAuthTokenStore tokenStore;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginBody body)
    {
        if (body == null || isBlank(body.getUsername()) || isBlank(body.getPassword()))
        {
            return Result.error("请输入用户名和密码");
        }

        PortalUser user = portalUserMapper.selectOne(new QueryWrapper<PortalUser>()
                .eq("username", body.getUsername())
                .eq("status", "0")
                .last("limit 1"));

        if (user == null || !passwordHash(body.getPassword()).equalsIgnoreCase(user.getPasswordHash()))
        {
            return Result.error("账号或密码错误");
        }

        String token = tokenStore.issue(user);
        user.setPasswordHash(null);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("token", token);
        data.put("user", user);
        return Result.success(data);
    }

    @GetMapping("/me")
    public Result<PortalUser> me(HttpServletRequest request)
    {
        PortalUser user = tokenStore.getPortalUser(resolveToken(request));
        if (user == null)
        {
            return Result.error("请先登录");
        }
        user.setPasswordHash(null);
        return Result.success(user);
    }

    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request)
    {
        tokenStore.revoke(resolveToken(request));
        return Result.success();
    }

    private String resolveToken(HttpServletRequest request)
    {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer "))
        {
            return authorization.substring("Bearer ".length());
        }
        return request.getHeader("X-Portal-Token");
    }

    private String passwordHash(String password)
    {
        try
        {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder builder = new StringBuilder();
            for (byte item : hash)
            {
                builder.append(String.format("%02x", item));
            }
            return builder.toString();
        }
        catch (Exception e)
        {
            throw new IllegalStateException("Password hash failed", e);
        }
    }

    private boolean isBlank(String value)
    {
        return value == null || value.trim().isEmpty();
    }

    public static class LoginBody
    {
        private String username;
        private String password;

        public String getUsername()
        {
            return username;
        }

        public void setUsername(String username)
        {
            this.username = username;
        }

        public String getPassword()
        {
            return password;
        }

        public void setPassword(String password)
        {
            this.password = [REDACTED]
        }
    }
}
', 'admin', sysdate()),
(920121, 9201, 'AdminUser.java.vm', NULL, 'AdminUser.java.vm', 'package ${packageName}.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Getter
@Setter
@Accessors(chain = true)
@TableName("t_admin")
public class AdminUser
{
    @TableId(value = "admin_id", type = IdType.AUTO)
    private Long adminId;

    private String username;

    private String passwordHash;

    private String nickname;

    private String status;
}
', 'admin', sysdate()),
(920122, 9201, 'AdminUserMapper.java.vm', NULL, 'AdminUserMapper.java.vm', 'package ${packageName}.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ${packageName}.entity.AdminUser;

public interface AdminUserMapper extends BaseMapper<AdminUser>
{
}
', 'admin', sysdate()),
(920123, 9201, 'AdminAuthController.java.vm', NULL, 'AdminAuthController.java.vm', 'package ${packageName}.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ${packageName}.common.Result;
import ${packageName}.entity.AdminUser;
import ${packageName}.mapper.AdminUserMapper;
import ${packageName}.security.PortalAuthTokenStore;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth/admin")
public class AdminAuthController
{
    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private PortalAuthTokenStore tokenStore;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginBody body)
    {
        if (body == null || isBlank(body.getUsername()) || isBlank(body.getPassword()))
        {
            return Result.error("请输入用户名和密码");
        }

        AdminUser user = adminUserMapper.selectOne(new QueryWrapper<AdminUser>()
                .eq("username", body.getUsername())
                .eq("status", "0")
                .last("limit 1"));

        if (user == null || !passwordHash(body.getPassword()).equalsIgnoreCase(user.getPasswordHash()))
        {
            return Result.error("账号或密码错误");
        }

        String token = tokenStore.issue(user);
        user.setPasswordHash(null);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("token", token);
        data.put("user", user);
        return Result.success(data);
    }

    @GetMapping("/me")
    public Result<AdminUser> me(HttpServletRequest request)
    {
        AdminUser user = tokenStore.getAdminUser(resolveToken(request));
        if (user == null)
        {
            return Result.error("请先登录");
        }
        user.setPasswordHash(null);
        return Result.success(user);
    }

    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request)
    {
        tokenStore.revoke(resolveToken(request));
        return Result.success();
    }

    private String resolveToken(HttpServletRequest request)
    {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer "))
        {
            return authorization.substring("Bearer ".length());
        }
        return request.getHeader("X-Admin-Token");
    }

    private String passwordHash(String password)
    {
        try
        {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder builder = new StringBuilder();
            for (byte item : hash)
            {
                builder.append(String.format("%02x", item));
            }
            return builder.toString();
        }
        catch (Exception e)
        {
            throw new IllegalStateException("Password hash failed", e);
        }
    }

    private boolean isBlank(String value)
    {
        return value == null || value.trim().isEmpty();
    }

    public static class LoginBody
    {
        private String username;
        private String password;

        public String getUsername()
        {
            return username;
        }

        public void setUsername(String username)
        {
            this.username = username;
        }

        public String getPassword()
        {
            return password;
        }

        public void setPassword(String password)
        {
            this.password = [REDACTED]
        }
    }
}
', 'admin', sysdate());

-- Admin frontend template files
INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(920201, 9202, 'package.json.vm', NULL, 'package.json.vm', '{
  "name": "${projectFileName}-admin",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "vue-cli-service serve --host 0.0.0.0",
    "serve": "vue-cli-service serve --host 0.0.0.0",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "axios": "^0.27.2",
    "core-js": "^3.8.3",
    "echarts": "5.4.0",
    "element-ui": "^2.15.14",
    "vue": "^2.6.14",
    "vue-router": "^3.6.5"
  },
  "devDependencies": {
    "@vue/cli-service": "^4.5.19",
    "vue-template-compiler": "^2.6.14"
  }
}', 'admin', sysdate()),
(920202, 9202, 'babel.config.js.vm', NULL, 'babel.config.js.vm', 'module.exports = {
  presets: [
    "@vue/cli-plugin-babel/preset"
  ]
}
', 'admin', sysdate()),
(920203, 9202, 'vue.config.js.vm', NULL, 'vue.config.js.vm', 'const port = process.env.PORT || 8081
const apiBaseUrl = process.env.VUE_APP_API_BASE_URL || "http://localhost:8080"

module.exports = {
  transpileDependencies: [],
  devServer: {
    port,
    proxy: {
      "/api": {
        target: apiBaseUrl,
        changeOrigin: true,
        pathRewrite: {
          "^/api": ""
        }
      }
    }
  }
}
', 'admin', sysdate()),
(920204, 9202, 'index.html.vm', NULL, 'index.html.vm', '<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>${projectName} Admin</title>
</head>
<body>
  <noscript>请启用 JavaScript 后访问。</noscript>
  <div id="app"></div>
</body>
</html>', 'admin', sysdate()),
(920205, 9202, 'admin-main.js.vm', NULL, 'admin-main.js.vm', 'import Vue from "vue"
import ElementUI from "element-ui"
import "element-ui/lib/theme-chalk/index.css"
import App from "./App.vue"
import router from "./router"
import request from "./utils/request"
import dict from "./utils/dict"

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.prototype.request = request
Vue.prototype._dict = dict

new Vue({
  router,
  render: h => h(App)
}).#[[$mount]]#("#app")', 'admin', sysdate()),
(920206, 9202, 'admin-App.vue.vm', NULL, 'admin-App.vue.vm', '<template>
  <div id="app">
    <router-view v-if="isLoginPage" />
    <div v-else class="admin-shell">
      <aside class="admin-sidebar">
        <router-link class="brand" to="/">
          <span class="brand-mark">ADM</span>
          <span class="brand-text">${projectName}后台</span>
        </router-link>

        <nav class="sidebar-menu">
#if($hasAdminNavGroups)
#foreach($group in $adminNavGroups)
#if($group.hasChildren)
          <div class="menu-group">
#if($group.clickable)
            <router-link class="menu-title menu-title-link" :class=''{ active: isSidebarGroupActive(${group.activePathsLiteral}) }'' to="${group.path}" exact>
              <span><i class="el-icon-menu"></i>${group.name}</span>
              <i class="el-icon-arrow-up"></i>
            </router-link>
#else
            <div class="menu-title" :class=''{ active: isSidebarGroupActive(${group.activePathsLiteral}) }''>
              <span><i class="el-icon-folder-opened"></i>${group.name}</span>
              <i class="el-icon-arrow-up"></i>
            </div>
#end
#foreach($child in $group.children)
            <router-link class="sidebar-link is-child" to="${child.path}" exact>
              <span>${child.name}</span>
            </router-link>
#end
          </div>
#else
          <router-link class="sidebar-link" to="${group.path}" exact>
            <i class="el-icon-menu"></i>
            <span>${group.name}</span>
          </router-link>
#end
#end
#else
          <router-link class="sidebar-link" to="/empty" exact>
            <i class="el-icon-warning-outline"></i>
            <span>暂无菜单</span>
          </router-link>
#end
        </nav>
      </aside>

      <section class="admin-main">
        <header class="topbar">
          <div class="breadcrumb">
            <router-link to="/">首页</router-link>
            <span>/</span>
            <strong>{{ currentTitle }}</strong>
          </div>
          <el-dropdown trigger="click" @command="handleUserCommand">
            <span class="user-entry">
              <span class="avatar">管</span>
              <span>{{ userName }}</span>
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </header>
        <main class="content-area">
          <router-view />
        </main>
      </section>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    isLoginPage() {
      return this.#[[$route]]#.path === "/login"
    },
    currentTitle() {
      return this.#[[$route]]#.meta && this.#[[$route]]#.meta.title ? this.#[[$route]]#.meta.title : "系统首页"
    },
    userName() {
      const storedUser = window.localStorage.getItem("admin-user")
      if (storedUser) {
        try {
          const user = JSON.parse(storedUser)
          return user.nickname || user.username || "管理员"
        } catch (e) {
          return "管理员"
        }
      }
      return window.localStorage.getItem("adminUserName") || "管理员"
    }
  },
  methods: {
    isSidebarGroupActive(paths) {
      return Array.isArray(paths) && paths.indexOf(this.#[[$route]]#.path) !== -1
    },
    handleUserCommand(command) {
      if (command === "logout") {
        this.request.post("/auth/admin/logout").finally(() => {
          this.clearAdminSession()
          this.#[[$router]]#.replace("/login")
        })
      }
    },
    clearAdminSession() {
      window.localStorage.removeItem("admin-token")
      window.localStorage.removeItem("admin-user")
    }
  }
}
</script>

<style>
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  background: #f3f5fa;
  color: #303133;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
}

a {
  text-decoration: none;
}

.admin-shell {
  min-height: 100vh;
  display: flex;
  background: #f3f5fa;
}

.admin-sidebar {
  width: 208px;
  min-height: 100vh;
  flex: 0 0 208px;
  overflow-y: auto;
  background: #0f172a;
  color: #d8e6f0;
}

.brand {
  height: 62px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #fff;
  background: #111827;
}

.brand-mark {
  display: inline-grid;
  width: 36px;
  height: 36px;
  place-items: center;
  border-radius: 8px;
  color: #ffffff;
  background: #17633b;
  font-size: 12px;
  font-weight: 800;
  letter-spacing: 0;
}

.brand-text {
  min-width: 0;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 17px;
  font-weight: 700;
}

.sidebar-menu {
  padding: 10px 0 24px;
}

.sidebar-link,
.menu-title {
  min-height: 44px;
  padding: 0 18px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #d8e6f0;
  font-size: 14px;
}

.menu-title {
  justify-content: space-between;
  background: #111f35;
  border-left: 3px solid transparent;
}

.menu-title-link {
  color: #d8e6f0;
}

.menu-title span {
  display: flex;
  align-items: center;
  gap: 10px;
}

.menu-title.active,
.menu-title:hover,
.sidebar-link:hover {
  color: #ffffff;
  background: #1e2f4d;
}

.sidebar-link.is-child {
  padding-left: 48px;
  background: #0b1220;
}

.sidebar-link.router-link-exact-active,
.sidebar-link.router-link-active {
  background: #2563eb;
  color: #fff;
}

.admin-main {
  min-width: 0;
  flex: 1;
}

.topbar {
  height: 56px;
  padding: 0 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  color: #111827;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.breadcrumb a,
.breadcrumb strong {
  color: #111827;
}

.user-entry {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: #334155;
  cursor: pointer;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: inline-grid;
  place-items: center;
  color: #1d4ed8;
  background: #eff6ff;
  font-weight: 700;
}

.content-area {
  min-height: calc(100vh - 56px);
  padding: 8px 10px 28px;
}
</style>', 'admin', sysdate()),
(920207, 9202, 'admin-router.js.vm', NULL, 'admin-router.js.vm', 'import Vue from "vue"
import Router from "vue-router"
import Login from "@/views/login/index.vue"
#if($hasAdminRouteItems)
#foreach($component in $adminRouteComponents)
import ${component.componentName} from "${component.componentPath}"
#end
#end

Vue.use(Router)

#if($hasAdminRouteItems)
const firstPath = "${defaultAdminPath}"
#else
const firstPath = "/empty"
const Empty = { template: "<div class=\"empty-page\">暂无可管理数据</div>" }
#end

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: { title: "登录" }
  },
  {
    path: "/",
    redirect: firstPath
  }#if($hasAdminRouteItems)#else,
  {
    path: "/empty",
    name: "Empty",
    component: Empty,
    meta: { title: "系统首页" }
  }#end
#foreach($item in $adminRouteItems),
  {
    path: "${item.path}",
    name: "${item.code}",
    component: ${item.componentName},
    meta: { title: "${item.title}" }
  }
#end
]

const router = new Router({
  mode: "hash",
  routes
})

router.beforeEach((to, from, next) => {
  const hasToken = Boolean(window.localStorage.getItem("admin-token"))
  if (to.path !== "/login" && !hasToken) {
    next({ path: "/login", query: { redirect: to.fullPath } })
    return
  }
  if (to.path === "/login" && hasToken) {
    next(to.query.redirect || firstPath)
    return
  }
  next()
})

export default router', 'admin', sysdate()),
(920211, 9202, 'admin-login.vue.vm', NULL, 'admin-login.vue.vm', '<template>
  <div class="login-page">
    <section class="login-visual">
      <div class="login-brand">
        <span class="brand-mark">
          <i></i><i></i><i></i><i></i>
        </span>
        <span>${projectName}后台</span>
      </div>
      <h1>${projectName}</h1>
      <p>统一管理分类、内容、订单与用户数据</p>
    </section>
    <el-form ref="loginForm" :model="form" :rules="rules" class="login-card" @keyup.enter.native="handleLogin">
      <h2>欢迎登录${projectName}后台</h2>
      <p>请输入管理员账号进入后台</p>
      <el-form-item prop="username">
        <el-input v-model="form.username" prefix-icon="el-icon-user" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="form.password" prefix-icon="el-icon-lock" placeholder="请输入密码" show-password />
      </el-form-item>
      <div class="login-options">
        <el-checkbox v-model="form.remember">记住账号</el-checkbox>
      </div>
      <el-button type="primary" :loading="loading" @click="handleLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>
#if($hasTables)
#set($firstTable = $tables.get(0))
const defaultRedirect = "/${firstTable.moduleName}/${firstTable.businessName}"
#else
const defaultRedirect = "/empty"
#end

export default {
  name: "AdminLogin",
  data() {
    return {
      loading: false,
      form: {
        username: window.localStorage.getItem("adminUserName") || "admin",
        password: "[REDACTED]
        remember: true
      },
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    }
  },
  methods: {
    handleLogin() {
      this.#[[$refs]]#.loginForm.validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        this.request.post("/auth/admin/login", {
          username: this.form.username,
          password: [REDACTED]
        }).then(res => {
          if (!res || res.code !== "200" || !res.data || !res.data.token) {
            throw new Error((res && res.msg) || "登录失败")
          }
          window.localStorage.setItem("admin-token", res.data.token)
          window.localStorage.setItem("admin-user", JSON.stringify(res.data.user || {
            username: this.form.username,
            nickname: this.form.username
          }))
          if (this.form.remember) {
            window.localStorage.setItem("adminUserName", this.form.username)
          } else {
            window.localStorage.removeItem("adminUserName")
          }
          this.#[[$message]]#.success("登录成功")
          this.#[[$router]]#.replace(this.#[[$route]]#.query.redirect || defaultRedirect)
        }).catch(error => {
          this.#[[$message]]#.error(error.message || "登录失败")
        }).finally(() => {
          this.loading = false
        })
      })
    }
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: grid;
  grid-template-columns: minmax(0, 1fr) 420px;
  background: #f3f5fa;
}

.login-visual {
  padding: 54px 64px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: linear-gradient(135deg, #20a9b5 0%, #147a8f 48%, #001120 100%);
  color: #fff;
}

.login-brand {
  position: absolute;
  top: 32px;
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 20px;
  font-weight: 700;
}

.brand-mark {
  width: 30px;
  height: 30px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 3px;
  transform: rotate(45deg);
}

.brand-mark i {
  display: block;
  border-radius: 2px;
}

.brand-mark i:nth-child(1) {
  background: #f4c542;
}

.brand-mark i:nth-child(2) {
  background: #22b8cf;
}

.brand-mark i:nth-child(3) {
  background: #2f80ed;
}

.brand-mark i:nth-child(4) {
  background: #42c77b;
}

.login-visual h1 {
  margin: 0;
  font-size: 46px;
  font-weight: 700;
  letter-spacing: 0;
}

.login-visual p {
  max-width: 520px;
  margin: 16px 0 0;
  color: rgba(255, 255, 255, .82);
  font-size: 18px;
}

.login-card {
  align-self: center;
  margin: 0 48px 0 0;
  padding: 36px 34px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 18px 42px rgba(0, 17, 32, .16);
}

.login-card h2 {
  margin: 0;
  color: #17233d;
  font-size: 25px;
  font-weight: 700;
  letter-spacing: 0;
}

.login-card p {
  margin: 8px 0 24px;
  color: #8a95a6;
}

.login-options {
  margin: -4px 0 18px;
}

.login-card .el-button {
  width: 100%;
  height: 42px;
  border-color: #0f7dbd;
  background: #0f7dbd;
}

@media (max-width: 900px) {
  .login-page {
    grid-template-columns: 1fr;
  }

  .login-visual {
    min-height: 220px;
    padding: 36px 28px;
  }

  .login-brand {
    position: static;
    margin-bottom: 48px;
  }

  .login-visual h1 {
    font-size: 34px;
  }

  .login-card {
    margin: 24px;
  }
}
</style>
', 'admin', sysdate()),
(920208, 9202, 'request.js.vm', NULL, 'request.js.vm', 'import axios from "axios"
import { Message } from "element-ui"

const request = axios.create({
  baseURL: "/api",
  timeout: 30000
})

request.interceptors.request.use(config => {
  const token = window.localStorage.getItem("admin-token")
  if (token) {
    config.headers.Authorization = "Bearer " + token
  }
  return config
})

request.interceptors.response.use(
  response => {
    const data = response.data
    if (data && data.code === "401") {
      clearAdminSession()
      Message.error(data.msg || "请先登录")
      return Promise.reject(new Error(data.msg || "Unauthorized"))
    }
    return data
  },
  error => {
    if (error && error.response && error.response.status === 401) {
      clearAdminSession()
      Message.error("请先登录")
    } else {
      Message.error(error && error.message ? error.message : "请求失败")
    }
    return Promise.reject(error)
  }
)

function clearAdminSession() {
  window.localStorage.removeItem("admin-token")
  window.localStorage.removeItem("admin-user")
  if (window.location.hash.indexOf("#/login") !== 0) {
    window.location.hash = "#/login"
  }
}

export default request
', 'admin', sysdate()),
(920209, 9202, 'dict.js.vm', NULL, 'dict.js.vm', 'const emptyDict = []

export default {
  getDictDataByType() {
    return emptyDict
  },
  getDictLabel(type, value) {
    return value === undefined || value === null || value === "" ? "-" : value
  }
}
', 'admin', sysdate()),
(920210, 9202, 'admin-index.vue.vm', NULL, 'admin-index.vue.vm', '<template>
  <div class="page-container">
    <section class="query-panel">
      <div class="toolbar query-toolbar">
#foreach ($column in $columns)
#if($column.isQuery == "1")
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#if($column.htmlType == "input")
      <el-input class="filter-item" placeholder="请输入${columnComment}" clearable v-model="queryParams.${javaField}" @keyup.enter.native="load" />
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
      <el-select class="filter-item" v-model="queryParams.${javaField}" placeholder="请选择${columnComment}" clearable>
        <el-option
          v-for="item in _dict.getDictDataByType(''${column.dictType}'')"
          :key="item.value"
          :label="item.name"
          :value="item.value" />
      </el-select>
#elseif($column.htmlType == "datetime")
      <el-date-picker class="filter-item" v-model="queryParams.${javaField}" type="date" value-format="yyyy-MM-dd" placeholder="选择${columnComment}" />
#end
#end
#end
      <el-button type="primary" @click="load">搜索</el-button>
      <el-button @click="reset">重置</el-button>
      </div>
    </section>

    <section class="action-panel">
      <div class="toolbar action-toolbar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-popconfirm
        confirm-button-text="确定"
        cancel-button-text="取消"
        icon="el-icon-info"
        icon-color="red"
        title="确定批量删除选中的数据吗？"
        @confirm="delBatch">
        <el-button slot="reference" type="danger" icon="el-icon-delete">批量删除</el-button>
      </el-popconfirm>
      </div>
    </section>

    <section class="table-panel">
    <el-table class="data-table" :data="${businessName}List" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="${pkColumn.javaField}" label="ID" width="90" />
#foreach ($column in $columns)
#if($column.isList == "1")
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#if($column.htmlType == "datetime")
      <el-table-column prop="${javaField}" label="${columnComment}" align="center" width="180" />
#elseif($column.htmlType == "imageUpload")
      <el-table-column prop="${javaField}" label="${columnComment}" align="center" width="110">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.${javaField}"
            class="table-image"
            :src="resolveResourceUrl(scope.row.${javaField})"
            :preview-src-list="[resolveResourceUrl(scope.row.${javaField})]" />
          <span v-else>-</span>
        </template>
      </el-table-column>
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
      <el-table-column prop="${javaField}" label="${columnComment}" align="center">
        <template slot-scope="scope">
          {{ _dict.getDictLabel(''${column.dictType}'', scope.row.${javaField}) }}
        </template>
      </el-table-column>
#else
      <el-table-column prop="${javaField}" label="${columnComment}" align="center" />
#end
#end
#end
      <el-table-column label="操作" width="190" align="center">
        <template slot-scope="scope">
          <el-button class="row-action edit-action" type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除这条数据吗？"
            @confirm="del(scope.row.${pkColumn.javaField})">
            <el-button slot="reference" class="row-action delete-action" type="danger" icon="el-icon-delete" circle></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    </section>

    <section class="pagination-panel">
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total" />
    </section>

    <el-dialog :title="form.${pkColumn.javaField} ? ''编辑${functionName}'' : ''新增${functionName}''" :visible.sync="dialogFormVisible" width="520px">
      <el-form ref="form" :model="form" label-width="110px" size="small">
#foreach ($column in $columns)
#if($column.isEdit == "1")
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
        <el-form-item label="${columnComment}" prop="${javaField}"#if($column.isRequired == "1") :rules="[{ required: true, message: ''${columnComment}不能为空'', trigger: #if($column.htmlType == "select")''change''#else''blur''#end }]"#end>
#if($column.htmlType == "input")
          <el-input v-model="form.${javaField}" placeholder="请输入${columnComment}" />
#elseif($column.htmlType == "textarea")
          <el-input v-model="form.${javaField}" type="textarea" placeholder="请输入${columnComment}" />
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
          <el-select v-model="form.${javaField}" placeholder="请选择${columnComment}" clearable>
            <el-option
              v-for="item in _dict.getDictDataByType(''${column.dictType}'')"
              :key="item.value"
              :label="item.name"
              :value="item.value" />
          </el-select>
#elseif($column.htmlType == "datetime")
          <el-date-picker v-model="form.${javaField}" type="date" value-format="yyyy-MM-dd" placeholder="选择${columnComment}" />
#elseif($column.htmlType == "imageUpload")
          <el-upload
            class="avatar-uploader"
            action="/api/files/upload"
            :show-file-list="false"
            :on-success="(res) => uploadSuccess(''${javaField}'', res)">
            <img v-if="form.${javaField}" :src="resolveResourceUrl(form.${javaField})" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
#elseif($column.htmlType == "fileUpload")
          <el-upload
            action="/api/files/upload"
            :on-success="(res) => uploadSuccess(''${javaField}'', res)">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div v-if="form.${javaField}" class="file-link">{{ form.${javaField} }}</div>
#end
        </el-form-item>
#end
#end
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "${BusinessName}",
  data() {
    return {
      ${businessName}List: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
#foreach ($column in $columns)
#if($column.isQuery == "1")
        ${column.javaField}: undefined,
#end
#end
      },
      form: {},
      dialogFormVisible: false,
      multipleSelection: []
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.request.get("/${moduleName}/${businessName}/page", {
        params: this.queryParams
      }).then(res => {
        const page = res.data || {}
        this.${businessName}List = page.records || []
        this.total = page.total || 0
      })
    },
    save() {
      this.#[[$refs]]#.form.validate(valid => {
        if (!valid) {
          return
        }
        this.request.post("/${moduleName}/${businessName}", this.form).then(res => {
          if (res.code === "200") {
            this.#[[$message]]#.success("保存成功")
            this.dialogFormVisible = false
            this.load()
          } else {
            this.#[[$message]]#.error(res.msg || "保存失败")
          }
        })
      })
    },
    handleAdd() {
      this.form = {}
      this.dialogFormVisible = true
      this.#[[$nextTick]]#(() => this.#[[$refs]]#.form && this.#[[$refs]]#.form.clearValidate())
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
      this.#[[$nextTick]]#(() => this.#[[$refs]]#.form && this.#[[$refs]]#.form.clearValidate())
    },
    del(${pkColumn.javaField}) {
      this.request.delete("/${moduleName}/${businessName}/" + ${pkColumn.javaField}).then(res => {
        if (res.code === "200") {
          this.#[[$message]]#.success("删除成功")
          this.load()
        } else {
          this.#[[$message]]#.error(res.msg || "删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    delBatch() {
      const ids = this.multipleSelection.map(item => item.${pkColumn.javaField})
      if (!ids.length) {
        this.#[[$message]]#.warning("请先选择要删除的数据")
        return
      }
      this.request.post("/${moduleName}/${businessName}/del/batch", ids).then(res => {
        if (res.code === "200") {
          this.#[[$message]]#.success("批量删除成功")
          this.load()
        } else {
          this.#[[$message]]#.error(res.msg || "批量删除失败")
        }
      })
    },
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.load()
    },
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.load()
    },
    resolveResourceUrl(url) {
      if (!url) {
        return ""
      }
      if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0 || url.indexOf("//") === 0 || url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) {
        return url
      }
      if (url.indexOf("/api/") === 0) {
        return url
      }
      if (url.indexOf("/files/") === 0) {
        return "/api" + url
      }
      return url
    },
    uploadSuccess(field, res) {
      if (res && res.code === "200" && res.data && res.data.url) {
        this.#[[$set]]#(this.form, field, res.data.url)
      } else {
        this.#[[$message]]#.error("上传失败，请重试")
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: calc(100vh - 72px);
}

.query-panel,
.action-panel,
.table-panel,
.pagination-panel {
  margin-bottom: 8px;
  border: 1px solid #edf0f5;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 8px rgba(26, 39, 56, .08);
}

.query-panel,
.action-panel {
  padding: 12px 14px;
}

.table-panel {
  padding: 12px 12px 0;
}

.pagination-panel {
  padding: 10px 12px;
}

.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.query-toolbar .el-button--primary {
  border-color: #cde8f0;
  background: #eaf8fb;
  color: #158a9a;
}

.query-toolbar .el-button--default {
  border-color: #f6e6ba;
  background: #fff8e6;
  color: #c58600;
}

.action-toolbar .el-button--primary {
  border-color: #9cd4ed;
  background: #eefaff;
  color: #0d80bd;
}

.action-toolbar .el-button--danger {
  border-color: #f2c2c7;
  background: #fff3f4;
  color: #d64252;
}

.filter-item {
  width: 220px;
}

.data-table {
  width: 100%;
  color: #606266;
  font-size: 13px;
}

.data-table >>> th {
  height: 48px;
  background: #fff;
  color: #7d8794;
  font-weight: 600;
}

.data-table >>> td {
  height: 58px;
  border-color: #f0f2f5;
}

.data-table >>> .el-table__row--striped td {
  background: #fafafa;
}

.pagination {
  display: flex;
  justify-content: flex-start;
}

.row-action {
  width: 30px;
  height: 30px;
  padding: 0;
  border: 0;
  font-size: 14px;
}

.edit-action {
  background: #0b7ec2;
}

.delete-action {
  margin-left: 10px;
  background: #e82f3d;
}

.table-image {
  width: 52px;
  height: 52px;
  border-radius: 4px;
}

.avatar-uploader .avatar {
  width: 96px;
  height: 96px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  width: 96px;
  height: 96px;
  line-height: 96px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  text-align: center;
  color: #8c939d;
}

.file-link {
  margin-top: 6px;
  color: #606266;
  word-break: break-all;
}
</style>
', 'admin', sysdate());

-- Portal frontend template files
INSERT INTO sys_template_file (template_file_id, template_id, file_name, module_id, file_path, file_content, create_by, create_time) VALUES
(920301, 9203, 'package.json.vm', NULL, 'package.json.vm', '{
  "name": "${projectFileName}-web",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "vue-cli-service serve --host 0.0.0.0",
    "serve": "vue-cli-service serve --host 0.0.0.0",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "axios": "^0.27.2",
    "core-js": "^3.8.3",
    "echarts": "5.4.0",
    "element-ui": "^2.15.14",
    "vue": "^2.6.14",
    "vue-router": "^3.6.5"
  },
  "devDependencies": {
    "@vue/cli-service": "^4.5.19",
    "vue-template-compiler": "^2.6.14"
  }
}
', 'admin', sysdate()),
(920302, 9203, 'babel.config.js.vm', NULL, 'babel.config.js.vm', 'module.exports = {
  presets: [
    "@vue/cli-plugin-babel/preset"
  ]
}
', 'admin', sysdate()),
(920303, 9203, 'vue.config.js.vm', NULL, 'vue.config.js.vm', 'const port = process.env.PORT || 8082
const apiBaseUrl = process.env.VUE_APP_API_BASE_URL || "http://localhost:8080"

module.exports = {
  transpileDependencies: [],
  devServer: {
    port,
    proxy: {
      "/api": {
        target: apiBaseUrl,
        changeOrigin: true,
        pathRewrite: {
          "^/api": ""
        }
      }
    }
  }
}
', 'admin', sysdate()),
(920304, 9203, 'index.html.vm', NULL, 'index.html.vm', '<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>${functionName}</title>
</head>
<body>
  <noscript>请启用 JavaScript 后访问。</noscript>
  <div id="app"></div>
</body>
</html>
', 'admin', sysdate()),
(920305, 9203, 'frontend-main.js.vm', NULL, 'frontend-main.js.vm', 'import Vue from "vue"
import ElementUI from "element-ui"
import "element-ui/lib/theme-chalk/index.css"
import App from "./App.vue"
import router from "./router"
import request from "./api/request"
import dict from "./utils/dict"
import "./style.css"

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.prototype.request = request
Vue.prototype._dict = dict

new Vue({
  router,
  render: h => h(App)
}).#[[$mount]]#("#app")', 'admin', sysdate()),
(920306, 9203, 'frontend-App.vue.vm', NULL, 'frontend-App.vue.vm', '#set($portalProjectName = $projectName)
#if(!$portalProjectName || $portalProjectName == "")
#set($portalProjectName = $functionName)
#end
#if(!$portalProjectName || $portalProjectName == "")
#set($portalProjectName = "Portal")
#end
#set($portalHomePath = $defaultFrontendPath)
#if(!$portalHomePath || $portalHomePath == "")
#set($portalHomePath = "/${moduleName}/${businessName}")
#end
<template>
  <div class="portal-shell">
    <template v-if="!isLoginRoute">
      <header class="top-nav">
        <router-link class="brand" to="${portalHomePath}">
          <span class="brand-logo" aria-hidden="true">APP</span>
          <span>${portalProjectName}</span>
        </router-link>

        <nav class="portal-nav" aria-label="主导航">
#if($hasFrontendNavGroups)
#foreach($group in $frontendNavGroups)
          <div class="portal-nav-group#if($group.hasChildren) has-children#end" :class=''{ active: isNavGroupActive(${group.activePathsLiteral}) }''>
#if($group.clickable)
            <router-link class="portal-nav-parent" to="${group.path}" exact>${group.name}</router-link>
#else
            <span class="portal-nav-parent portal-nav-directory">${group.name}</span>
#end
#if($group.hasChildren)
            <button class="portal-nav-toggle" type="button" aria-label="展开子菜单">⌄</button>
            <div class="portal-nav-dropdown">
#foreach($child in $group.children)
              <router-link class="portal-nav-child" to="${child.path}" exact>${child.name}</router-link>
#end
            </div>
#end
          </div>
#end
#else
          <div class="portal-nav-group">
            <router-link class="portal-nav-parent" to="${portalHomePath}" exact>首页</router-link>
          </div>
#end
        </nav>

        <div class="user-area">
          <template v-if="currentUser">
            <button class="user-chip" type="button">
              <span class="avatar">{{ userInitial }}</span>
              <span>{{ currentUserName }}</span>
            </button>
            <button class="logout-link" type="button" @click="logout">退出</button>
          </template>
          <button v-else class="login-link" type="button" @click="goLogin">登录</button>
        </div>
      </header>

      <section class="hero-banner" aria-label="项目横幅">
        <div class="hero-pattern" aria-hidden="true"></div>
        <h1>${portalProjectName}</h1>
      </section>
    </template>

    <main :class="[''portal-main'', { ''portal-main-login'': isLoginRoute }]">
      <router-view />
    </main>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      currentUser: null
    }
  },
  computed: {
    isLoginRoute() {
      return this.#[[$route]]#.path === "/login"
    },
    currentUserName() {
      return this.currentUser && (this.currentUser.nickname || this.currentUser.username || "User")
    },
    userInitial() {
      const name = this.currentUserName || "U"
      return name.slice(0, 1).toUpperCase()
    }
  },
  mounted() {
    this.loadUser()
    window.addEventListener("portal-user-change", this.loadUser)
  },
  beforeDestroy() {
    window.removeEventListener("portal-user-change", this.loadUser)
  },
  methods: {
    isNavGroupActive(paths) {
      return Array.isArray(paths) && paths.indexOf(this.#[[$route]]#.path) !== -1
    },
    loadUser() {
      const raw = localStorage.getItem("portal-user")
      if (!raw) {
        this.currentUser = null
        return
      }
      try {
        this.currentUser = JSON.parse(raw)
      } catch (error) {
        localStorage.removeItem("portal-user")
        this.currentUser = null
      }
    },
    goLogin() {
      this.#[[$router]]#.push({
        path: "/login",
        query: { redirect: this.#[[$route]]#.fullPath }
      })
    },
    logout() {
      this.request.post("/auth/logout").catch(() => {})
      localStorage.removeItem("portal-token")
      localStorage.removeItem("portal-user")
      window.dispatchEvent(new Event("portal-user-change"))
      this.#[[$router]]#.push("/login")
    }
  }
}
</script>

<style>
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  background: #f6f7fb;
  color: #1f2937;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
}

a {
  color: inherit;
  text-decoration: none;
}

button {
  font: inherit;
}

.portal-shell {
  min-height: 100vh;
  background: #f6f7fb;
}

.top-nav {
  position: sticky;
  top: 0;
  z-index: 20;
  display: grid;
  grid-template-columns: minmax(180px, auto) minmax(0, 1fr) auto;
  align-items: center;
  gap: 24px;
  min-height: 68px;
  padding: 0 32px;
  color: #111827;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 1px 0 rgba(15, 23, 42, 0.04);
}

.brand,
.portal-nav,
.user-area,
.user-chip {
  display: inline-flex;
  align-items: center;
}

.brand {
  gap: 10px;
  min-width: 0;
  font-size: 18px;
  font-weight: 700;
}

.brand span:last-child {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.brand-logo {
  display: inline-grid;
  width: 36px;
  height: 36px;
  flex: 0 0 36px;
  place-items: center;
  border-radius: 8px;
  color: #ffffff;
  background: #17633b;
  font-size: 12px;
  font-weight: 800;
  letter-spacing: 0;
}

.portal-nav {
  justify-content: center;
  gap: 8px;
  min-width: 0;
  height: 100%;
  overflow: visible;
}

.portal-nav-group {
  position: relative;
  display: inline-flex;
  align-items: center;
  flex: 0 0 auto;
  min-height: 68px;
}

.portal-nav-parent,
.portal-nav-toggle,
.portal-nav-child {
  display: inline-flex;
  align-items: center;
  border: 0;
  background: transparent;
  font: inherit;
  cursor: pointer;
}

.portal-nav-parent {
  min-height: 36px;
  padding: 0 14px;
  border-radius: 8px;
  color: #1f2937;
  font-size: 15px;
  font-weight: 600;
  white-space: nowrap;
}

.portal-nav-parent:hover,
.portal-nav-parent.router-link-active,
.portal-nav-group.active .portal-nav-parent {
  color: #2563eb;
  background: #eef5ff;
}

.portal-nav-directory {
  cursor: default;
}

.portal-nav-toggle {
  justify-content: center;
  width: 28px;
  height: 28px;
  margin-left: -8px;
  border-radius: 6px;
  color: #64748b;
}

.portal-nav-group:hover .portal-nav-toggle,
.portal-nav-group:focus-within .portal-nav-toggle,
.portal-nav-group.active .portal-nav-toggle {
  color: #2563eb;
  background: #eef5ff;
}

.portal-nav-dropdown {
  position: absolute;
  top: calc(100% - 8px);
  left: 0;
  z-index: 30;
  display: none;
  min-width: 168px;
  padding: 8px;
  border: 1px solid #dbe4f0;
  border-radius: 8px;
  background: #ffffff;
  box-shadow: 0 16px 34px rgba(15, 23, 42, 0.14);
}

.portal-nav-group:hover .portal-nav-dropdown,
.portal-nav-group:focus-within .portal-nav-dropdown {
  display: grid;
  gap: 4px;
}

.portal-nav-child {
  min-height: 34px;
  padding: 0 10px;
  border-radius: 6px;
  color: #334155;
  font-size: 14px;
  white-space: nowrap;
}

.portal-nav-child:hover,
.portal-nav-child.router-link-active {
  color: #2563eb;
  background: #eef5ff;
}

.user-area {
  justify-content: flex-end;
  gap: 10px;
  min-width: 130px;
}

.user-chip,
.login-link,
.logout-link {
  border: 1px solid #dbe4f0;
  color: #475569;
  background: #ffffff;
  cursor: pointer;
}

.user-chip {
  gap: 8px;
  padding: 0;
}

.avatar {
  display: inline-grid;
  width: 36px;
  height: 36px;
  place-items: center;
  border: 1px solid #bfdbfe;
  border-radius: 50%;
  color: #1d4ed8;
  background: #eff6ff;
  font-weight: 700;
}

.logout-link,
.login-link {
  min-height: 32px;
  padding: 0 10px;
  border-radius: 4px;
}

.logout-link:hover,
.login-link:hover {
  color: #2563eb;
  background: #f8fbff;
}

.hero-banner {
  position: relative;
  display: grid;
  min-height: 260px;
  place-items: center;
  overflow: hidden;
  background:
    linear-gradient(132deg, rgba(24, 141, 149, 0.95), rgba(44, 120, 215, 0.88)),
    #168d95;
}

.hero-pattern {
  position: absolute;
  inset: 0;
  opacity: 0.58;
  background:
    linear-gradient(42deg, transparent 0 18%, rgba(255, 255, 255, 0.18) 18% 27%, transparent 27% 100%),
    linear-gradient(132deg, transparent 0 48%, rgba(246, 186, 51, 0.32) 48% 55%, transparent 55% 100%);
}

.hero-banner h1 {
  position: relative;
  z-index: 1;
  max-width: min(900px, calc(100% - 40px));
  margin: 0;
  color: #ffffff;
  font-size: 46px;
  font-weight: 600;
  letter-spacing: 0;
  line-height: 1.2;
  text-align: center;
  text-shadow: 0 12px 28px rgba(15, 23, 42, 0.22);
}

.portal-main {
  width: min(1120px, calc(100% - 48px));
  margin: 0 auto;
  padding: 26px 0 44px;
}

.portal-main-login {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 0;
}

@media (max-width: 900px) {
  .top-nav {
    grid-template-columns: 1fr auto;
    gap: 10px;
    height: auto;
    min-height: 56px;
    padding: 10px 16px;
  }

  .portal-nav {
    grid-column: 1 / -1;
    justify-content: flex-start;
    order: 3;
    gap: 6px;
    overflow-x: auto;
    overflow-y: visible;
  }

  .portal-nav-group {
    min-height: 38px;
  }

  .portal-nav-parent {
    min-height: 34px;
    padding: 0 12px;
  }

  .portal-nav-dropdown {
    position: fixed;
    top: 104px;
    left: 16px;
    right: 16px;
  }

  .hero-banner {
    min-height: 210px;
  }

  .hero-banner h1 {
    font-size: 34px;
  }

  .portal-main {
    width: min(100% - 28px, 1120px);
  }
}
</style>
', 'admin', sysdate()),
(920307, 9203, 'style.css.vm', NULL, 'style.css.vm', 'body {
  margin: 0;
  background: #f6f7fb;
  color: #1f2937;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
}

.el-button {
  border-radius: 4px;
}', 'admin', sysdate()),
(920308, 9203, 'frontend-router.js.vm', NULL, 'frontend-router.js.vm', 'import Vue from "vue"
import Router from "vue-router"
import Login from "@/views/login/index.vue"
#set($portalDefaultPath = $defaultFrontendPath)
#if(!$portalDefaultPath || $portalDefaultPath == "")
#set($portalDefaultPath = "/${moduleName}/${businessName}")
#end
#if($hasFrontendRouteItems)
#foreach($component in $frontendRouteComponents)
import ${component.componentName} from "${component.componentPath}"
#end
#else
import ${BusinessName} from "@/views/${moduleName}/${businessName}/index.vue"
#end

Vue.use(Router)

const router = new Router({
  mode: "hash",
  routes: [
    {
      path: "/",
      redirect: "${portalDefaultPath}"
    },
    {
      path: "/login",
      name: "Login",
      component: Login
    },
#if($hasFrontendRouteItems)
#foreach($item in $frontendRouteItems)
    {
      path: "${item.path}",
      name: "${item.code}",
      component: ${item.componentName},
      meta: { requiresAuth: ${item.requiresLogin} }
    }#if($foreach.hasNext),#end
#end
#else
    {
      path: "/${moduleName}/${businessName}",
      name: "${BusinessName}",
      component: ${BusinessName},
      meta: { requiresAuth: true }
    }
#end
  ]
})

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta && record.meta.requiresAuth)
  const hasToken = Boolean(localStorage.getItem("portal-token"))

  if (requiresAuth && !hasToken) {
    next({
      path: "/login",
      query: { redirect: to.fullPath }
    })
    return
  }

  next()
})

export default router
', 'admin', sysdate()),
(920309, 9203, 'frontend-request.js.vm', NULL, 'frontend-request.js.vm', 'import axios from "axios"
import { Message } from "element-ui"

const request = axios.create({
  baseURL: "/api",
  timeout: 30000
})

request.interceptors.request.use(config => {
  const token = localStorage.getItem("portal-token")
  if (token) {
    config.headers.Authorization = "Bearer " + token
  }
  return config
})

request.interceptors.response.use(
  response => {
    const data = response.data
    if (data && data.code === "401") {
      clearSession()
      Message.error(data.msg || "请先登录")
      return Promise.reject(new Error(data.msg || "Unauthorized"))
    }
    return data
  },
  error => {
    if (error && error.response && error.response.status === 401) {
      clearSession()
      Message.error("请先登录")
    } else {
      Message.error(error && error.message ? error.message : "请求失败")
    }
    return Promise.reject(error)
  }
)

function clearSession() {
  localStorage.removeItem("portal-token")
  localStorage.removeItem("portal-user")
  if (window.location.hash.indexOf("#/login") !== 0) {
    window.location.hash = "#/login"
  }
}

export default request
', 'admin', sysdate()),
(920310, 9203, 'frontend-api.js.vm', NULL, 'frontend-api.js.vm', 'import request from "./request"

export function list${ClassName}(query) {
  return request({
    url: "/${moduleName}/${businessName}/page",
    method: "get",
    params: query
  })
}

export function get${ClassName}(${pkColumn.javaField}) {
  return request({
    url: "/${moduleName}/${businessName}/" + ${pkColumn.javaField},
    method: "get"
  })
}', 'admin', sysdate()),
(920311, 9203, 'frontend-index.vue.vm', NULL, 'frontend-index.vue.vm', '<template>
#set($designed = $hasCurrentFrontendPageDesign)
#set($queryColumns = $columns)
#set($tableColumns = $columns)
#set($formColumns = $columns)
#set($cardColumns = $columns)
#set($cardTitleColumn = false)
#set($cardImageColumn = false)
#set($showAdd = false)
#set($showBatchDelete = false)
#set($showView = false)
#set($showEdit = false)
#set($showDelete = false)
#set($isCardListLayout = false)
#set($isSplitListLayout = false)
#set($showQuery = true)
#set($showToolbar = true)
#set($showForm = true)
#set($renderForm = true)
#set($currentUserOnly = false)
#set($isDetailPage = $pageDesignIsDetail)
#set($detailColumns = $columns)
#set($toolbarBusinessActions = $pageDesignToolbarBusinessActions)
#set($rowBusinessActions = $pageDesignRowBusinessActions)
#set($allPageBusinessActions = $pageDesignBusinessActions)
#set($hasToolbarBusinessActions = $hasPageDesignToolbarBusinessActions)
#set($hasRowBusinessActions = $hasPageDesignRowBusinessActions)
#set($topBusinessBlocks = $pageDesignTopBusinessBlocks)
#set($bottomBusinessBlocks = $pageDesignBottomBusinessBlocks)
#set($embeddedBusinessBlocks = $pageDesignEmbeddedBusinessBlocks)
#if($allowAdd == ''1'')
#set($showAdd = true)
#end
#if($allowRemove == ''1'')
#set($showBatchDelete = true)
#set($showDelete = true)
#end
#if($allowEdit == ''1'')
#set($showEdit = true)
#end
#if($designed)
#set($queryColumns = $pageDesignQueryColumns)
#set($tableColumns = $pageDesignTableColumns)
#set($formColumns = $pageDesignFormColumns)
#set($cardColumns = $pageDesignCardColumns)
#set($cardTitleColumn = $pageDesignCardTitleColumn)
#set($cardImageColumn = $pageDesignCardImageColumn)
#set($showAdd = $pageDesignAllowAdd)
#set($showBatchDelete = $pageDesignAllowBatchDelete)
#set($showView = $pageDesignAllowView)
#set($showEdit = $pageDesignAllowEdit)
#set($showDelete = $pageDesignAllowDelete)
#set($isCardListLayout = $pageDesignIsCardList)
#set($isSplitListLayout = $pageDesignIsSplitList)
#set($showQuery = $pageDesignShowQuery)
#set($showToolbar = $pageDesignShowToolbar)
#set($showForm = $pageDesignShowForm)
#set($currentUserOnly = $pageDesignIsCurrentUserList)
#set($detailColumns = $pageDesignFormColumns)
#end
#if(!$showToolbar)
#set($showAdd = false)
#set($showBatchDelete = false)
#end
#if($isDetailPage)
#set($showQuery = false)
#set($showToolbar = false)
#set($showAdd = false)
#set($showBatchDelete = false)
#set($showView = false)
#set($showEdit = false)
#set($showDelete = false)
#set($showForm = false)
#set($renderForm = false)
#if($detailColumns.size() == 0)
#set($detailColumns = $columns)
#end
#end
#set($renderForm = $showForm)
#if($showAdd || $showEdit)
#set($renderForm = true)
#end
  <section class="portal-page">
#if($hasPageDesignTopBusinessBlocks)
    <section class="embedded-business-blocks top-business-blocks">
#foreach($block in $topBusinessBlocks)
      <div class="embedded-business-block__item embedded-business-block__item--span-${block.span}">
        <${block.componentName} />
      </div>
#end
    </section>
#end

    <section class="content-board">
      <div class="feature-card">
        <div class="feature-illustration" aria-hidden="true">
          <div class="device-face">
            <span></span>
            <span></span>
          </div>
        </div>
        <div class="feature-copy">
          <span>精选推荐</span>
          <h2>${functionName}</h2>
          <p>围绕资源管理、活动公告和玩家社区内容，快速维护当前模块的数据。</p>
        </div>
      </div>

      <aside class="notice-panel">
        <div class="notice-tabs">
          <button
            v-for="tab in noticeTabs"
            :key="tab"
            type="button"
            :class="{ active: activeTab === tab }"
            @click="activeTab = tab">
            {{ tab }}
          </button>
        </div>
        <ul class="notice-list">
          <li v-for="notice in notices" :key="notice.title">
            <strong>{{ notice.title }}</strong>
            <span><i class="el-icon-time"></i>{{ notice.time }}</span>
          </li>
        </ul>
      </aside>
    </section>

    <section class="data-panel#if($isSplitListLayout) split-data-panel#end">
      <div class="panel-heading">
        <div>
          <span class="section-kicker">资源数据</span>
          <h2>${functionName}管理</h2>
        </div>
        <div class="panel-actions">
          #if($showToolbar)
          #if($showAdd)
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          #end
          #if($showBatchDelete)
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定批量删除选中的数据吗？"
            @confirm="delBatch">
            <el-button slot="reference" type="danger" icon="el-icon-delete">批量删除</el-button>
          </el-popconfirm>
          #end
          #foreach($action in $toolbarBusinessActions)
          #set($buttonLabel = $action.buttonLabel)
          #if(!$buttonLabel)#set($buttonLabel = $action.name)#end
          #set($buttonType = $action.buttonType)
          #if(!$buttonType)#set($buttonType = "primary")#end
          #set($buttonIcon = $action.buttonIcon)
          #if(!$buttonIcon)#set($buttonIcon = "el-icon-position")#end
          <el-button type="${buttonType}" plain icon="${buttonIcon}" @click="handleBusinessAction(''${action.code}'')">${buttonLabel}</el-button>
          #end
          #end
        </div>
      </div>

#if($isDetailPage)
      <div class="detail-view" v-loading="detailLoading">
        <div v-if="detailLoaded && !detailRecord.${pkColumn.javaField}" class="empty-detail">
          <i class="el-icon-document"></i>
          <span>暂无详情数据</span>
        </div>
        <template v-else>
          <dl class="detail-grid">
#foreach ($column in $detailColumns)
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#set($remoteSelect=$qingRemoteSelectFields.contains($javaField))
            <div class="detail-field#if($column.htmlType == "textarea") wide#end">
              <dt>${columnComment}</dt>
              <dd>
#if($column.htmlType == "imageUpload")
                <el-image
                  v-if="detailRecord.${javaField}"
                  class="detail-image"
                  :src="resolveResourceUrl(detailRecord.${javaField})"
                  :preview-src-list="[resolveResourceUrl(detailRecord.${javaField})]" />
                <span v-else>-</span>
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
#if($remoteSelect)
                {{ getOptionLabel(''${javaField}'', detailRecord.${javaField}) }}
#else
                {{ _dict.getDictLabel(''${column.dictType}'', detailRecord.${javaField}) || ''-'' }}
#end
#else
                {{ formatDetailValue(detailRecord.${javaField}) }}
#end
              </dd>
            </div>
#end
          </dl>
#if($hasRowBusinessActions)
          <div class="detail-actions">
#foreach($action in $rowBusinessActions)
#set($buttonLabel = $action.buttonLabel)
#if(!$buttonLabel)#set($buttonLabel = $action.name)#end
#set($buttonType = $action.buttonType)
#if(!$buttonType)#set($buttonType = "primary")#end
#set($buttonIcon = $action.buttonIcon)
#if(!$buttonIcon)#set($buttonIcon = "el-icon-position")#end
            <el-button type="${buttonType}" icon="${buttonIcon}" @click="handleBusinessAction(''${action.code}'', detailRecord)">${buttonLabel}</el-button>
#end
          </div>
#end
        </template>
      </div>
#else

      #if($showQuery)
      <div class="filter-bar">
#foreach ($column in $queryColumns)
#set($renderQueryField = false)
#if($designed)
#set($renderQueryField = true)
#elseif($column.isQuery == "1")
#set($renderQueryField = true)
#end
#if($renderQueryField)
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#set($remoteSelect=$qingRemoteSelectFields.contains($javaField))
#if($column.htmlType == "input")
        <el-input class="filter-item" placeholder="请输入${columnComment}" clearable v-model="queryParams.${javaField}" @keyup.enter.native="load" />
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
        <el-select class="filter-item" v-model="queryParams.${javaField}" placeholder="请选择${columnComment}" clearable>
#if($remoteSelect)
          <el-option
            v-for="item in getSelectOptions(''${javaField}'')"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
#else
          <el-option
            v-for="item in _dict.getDictDataByType(''${column.dictType}'')"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
#end
        </el-select>
#elseif($column.htmlType == "datetime")
        <el-date-picker class="filter-item" v-model="queryParams.${javaField}" type="date" value-format="yyyy-MM-dd" placeholder="选择${columnComment}" />
#end
#end
#end
        <el-button type="primary" icon="el-icon-search" @click="load">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </div>
      #end

#if($isCardListLayout)
      <div class="resource-card-grid">
        <article v-for="item in ${businessName}List" :key="item.${pkColumn.javaField}" class="resource-card-item">
          #if($showBatchDelete)
          <el-checkbox class="resource-card-check" v-model="item.__checked" @change="handleCardSelectionChange" />
          #end
          <div class="resource-card-body">
#if($cardImageColumn)
            <el-image
              v-if="item.${cardImageColumn.javaField}"
              class="resource-card-image"
              :src="resolveResourceUrl(item.${cardImageColumn.javaField})"
              :preview-src-list="[resolveResourceUrl(item.${cardImageColumn.javaField})]" />
#end
#if($cardTitleColumn)
            <h3 class="resource-card-title">{{ item.${cardTitleColumn.javaField} || ''-'' }}</h3>
#end
#foreach ($column in $cardColumns)
#set($renderCardField = false)
#if($designed)
#set($renderCardField = true)
#elseif($column.isList == "1")
#set($renderCardField = true)
#end
#if($renderCardField)
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#set($remoteSelect=$qingRemoteSelectFields.contains($javaField))
#if($column.htmlType == "imageUpload")
            <el-image
              v-if="item.${javaField}"
              class="resource-card-image"
              :src="resolveResourceUrl(item.${javaField})"
              :preview-src-list="[resolveResourceUrl(item.${javaField})]" />
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
            <div class="resource-card-field">
              <span>${columnComment}</span>
#if($remoteSelect)
              <strong>{{ getOptionLabel(''${javaField}'', item.${javaField}) }}</strong>
#else
              <strong>{{ _dict.getDictLabel(''${column.dictType}'', item.${javaField}) || ''-'' }}</strong>
#end
            </div>
#else
            <div class="resource-card-field">
              <span>${columnComment}</span>
              <strong>{{ item.${javaField} || ''-'' }}</strong>
            </div>
#end
#end
#end
          </div>
          #if($showView || $showEdit || $showDelete || $hasRowBusinessActions)
          <div class="resource-card-actions">
            #if($showView)
            <el-button type="text" icon="el-icon-view" @click="handleView(item)">查看</el-button>
            #end
            #if($showEdit)
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(item)">编辑</el-button>
            #end
            #if($showDelete)
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除这条数据吗？"
              @confirm="del(item.${pkColumn.javaField})">
              <el-button slot="reference" type="text" icon="el-icon-delete" class="danger-text">删除</el-button>
            </el-popconfirm>
            #end
            #foreach($action in $rowBusinessActions)
            #set($buttonLabel = $action.buttonLabel)
            #if(!$buttonLabel)#set($buttonLabel = $action.name)#end
            #set($buttonType = $action.buttonType)
            #if(!$buttonType)#set($buttonType = "text")#end
            #set($buttonIcon = $action.buttonIcon)
            #if(!$buttonIcon)#set($buttonIcon = "el-icon-position")#end
            <el-button type="${buttonType}" icon="${buttonIcon}" @click="handleBusinessAction(''${action.code}'', item)">${buttonLabel}</el-button>
            #end
          </div>
          #end
        </article>
      </div>
#else
      <el-table :data="${businessName}List" border stripe class="resource-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
#if(!$designed)
        <el-table-column prop="${pkColumn.javaField}" label="ID" width="90" />
#end
#foreach ($column in $tableColumns)
#set($renderTableField = false)
#if($designed)
#set($renderTableField = true)
#elseif($column.isList == "1")
#set($renderTableField = true)
#end
#if($renderTableField)
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#set($remoteSelect=$qingRemoteSelectFields.contains($javaField))
#if($column.htmlType == "datetime")
        <el-table-column prop="${javaField}" label="${columnComment}" align="center" width="180" />
#elseif($column.htmlType == "imageUpload")
        <el-table-column prop="${javaField}" label="${columnComment}" align="center" width="110">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.${javaField}"
              class="table-image"
              :src="resolveResourceUrl(scope.row.${javaField})"
              :preview-src-list="[resolveResourceUrl(scope.row.${javaField})]" />
            <span v-else>-</span>
          </template>
        </el-table-column>
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
        <el-table-column prop="${javaField}" label="${columnComment}" align="center">
          <template slot-scope="scope">
#if($remoteSelect)
            {{ getOptionLabel(''${javaField}'', scope.row.${javaField}) }}
#else
            {{ _dict.getDictLabel(''${column.dictType}'', scope.row.${javaField}) }}
#end
          </template>
        </el-table-column>
#else
        <el-table-column prop="${javaField}" label="${columnComment}" align="center" />
#end
#end
#end
        #if($showView || $showEdit || $showDelete || $hasRowBusinessActions)
        <el-table-column label="操作" width="230" align="center">
          <template slot-scope="scope">
            #if($showView)
            <el-button type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            #end
            #if($showEdit)
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            #end
            #if($showDelete)
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除这条数据吗？"
              @confirm="del(scope.row.${pkColumn.javaField})">
              <el-button slot="reference" type="text" icon="el-icon-delete" class="danger-text">删除</el-button>
            </el-popconfirm>
            #end
            #foreach($action in $rowBusinessActions)
            #set($buttonLabel = $action.buttonLabel)
            #if(!$buttonLabel)#set($buttonLabel = $action.name)#end
            #set($buttonType = $action.buttonType)
            #if(!$buttonType)#set($buttonType = "text")#end
            #set($buttonIcon = $action.buttonIcon)
            #if(!$buttonIcon)#set($buttonIcon = "el-icon-position")#end
            <el-button type="${buttonType}" icon="${buttonIcon}" @click="handleBusinessAction(''${action.code}'', scope.row)">${buttonLabel}</el-button>
            #end
          </template>
        </el-table-column>
        #end
      </el-table>
#end

      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" />
#end
    </section>

#if($hasPageDesignBottomBusinessBlocks)
    <section class="embedded-business-blocks bottom-business-blocks">
#foreach($block in $bottomBusinessBlocks)
      <div class="embedded-business-block__item embedded-business-block__item--span-${block.span}">
        <${block.componentName} />
      </div>
#end
    </section>
#end

    #if($renderForm)
    <el-dialog :title="viewing ? ''查看${functionName}'' : (form.${pkColumn.javaField} ? ''编辑${functionName}'' : ''新增${functionName}'')" :visible.sync="dialogFormVisible" width="520px">
      <el-form ref="form" :model="form" label-width="110px" size="small" :disabled="viewing">
#foreach ($column in $formColumns)
#set($renderFormField = false)
#if($designed)
#set($renderFormField = true)
#elseif($column.isEdit == "1")
#set($renderFormField = true)
#end
#if($renderFormField)
#set($javaField=$column.javaField)
#set($columnComment=$column.columnComment)
#set($remoteSelect=$qingRemoteSelectFields.contains($javaField))
#set($autoIncrementField=$column.isIncrement == "1")
        <el-form-item#if($autoIncrementField) v-if="form.${javaField}"#end label="${columnComment}" prop="${javaField}"#if($column.isRequired == "1" && !$autoIncrementField) :rules="[{ required: true, message: ''${columnComment}不能为空'', trigger: #if($column.htmlType == "select")''change''#else''blur''#end }]"#end>
#if($column.htmlType == "input")
          <el-input v-model="form.${javaField}"#if($autoIncrementField) disabled#end placeholder="请输入${columnComment}" />
#elseif($column.htmlType == "textarea")
          <el-input v-model="form.${javaField}" type="textarea" placeholder="请输入${columnComment}" />
#elseif($column.htmlType == "select" || $column.htmlType == "radio")
          <el-select v-model="form.${javaField}" placeholder="请选择${columnComment}" clearable>
#if($remoteSelect)
            <el-option
              v-for="item in getSelectOptions(''${javaField}'')"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
#else
            <el-option
              v-for="item in _dict.getDictDataByType(''${column.dictType}'')"
              :key="item.value"
              :label="item.name"
              :value="item.value" />
#end
          </el-select>
#elseif($column.htmlType == "datetime")
          <el-date-picker v-model="form.${javaField}" type="date" value-format="yyyy-MM-dd" placeholder="选择${columnComment}" />
#elseif($column.htmlType == "imageUpload")
          <el-upload
            class="avatar-uploader"
            action="/api/files/upload"
            :show-file-list="false"
            :on-success="(res) => uploadSuccess(''${javaField}'', res)">
            <img v-if="form.${javaField}" :src="resolveResourceUrl(form.${javaField})" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
#elseif($column.htmlType == "fileUpload")
          <el-upload
            action="/api/files/upload"
            :on-success="(res) => uploadSuccess(''${javaField}'', res)">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div v-if="form.${javaField}" class="file-link">{{ form.${javaField} }}</div>
#end
        </el-form-item>
#end
#end
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="!viewing" type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
    #end

    <el-dialog
      :title="businessActionDialogTitle"
      :visible.sync="businessActionDialogVisible"
      width="520px"
      append-to-body
      :show-close="!businessActionSubmitting"
      :close-on-click-modal="false"
      :close-on-press-escape="!businessActionSubmitting"
      @closed="resetBusinessActionDialog">
      <p v-if="activeBusinessAction && activeBusinessAction.confirmMessage" class="business-action-hint">
        {{ activeBusinessAction.confirmMessage }}
      </p>
      <el-form
        ref="businessActionForm"
        :model="businessActionForm"
        label-width="110px"
        size="small">
        <el-form-item
          v-for="field in businessActionInputFields"
          :key="field.field"
          :label="field.label"
          :prop="field.field"
          :rules="[{ required: true, message: field.label + ''不能为空'', trigger: field.htmlType === ''select'' ? ''change'' : ''blur'' }]">
          <el-date-picker
            v-if="field.htmlType === ''datetime''"
            v-model="businessActionForm[field.field]"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="''请选择'' + field.label" />
          <el-select
            v-else-if="field.htmlType === ''select'' && field.dictType"
            v-model="businessActionForm[field.field]"
            clearable
            :placeholder="''请选择'' + field.label">
            <el-option
              v-for="option in getBusinessActionFieldOptions(field)"
              :key="option.value"
              :label="option.label"
              :value="option.value" />
          </el-select>
          <el-input
            v-else-if="field.htmlType === ''textarea''"
            v-model="businessActionForm[field.field]"
            type="textarea"
            :rows="3"
            :placeholder="''请输入'' + field.label" />
          <el-input
            v-else
            v-model="businessActionForm[field.field]"
            :placeholder="''请输入'' + field.label" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="businessActionSubmitting"
          @click="businessActionDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="businessActionSubmitting"
          @click="submitBusinessAction">
          {{ activeBusinessAction && activeBusinessAction.buttonLabel ? activeBusinessAction.buttonLabel : ''确认执行'' }}
        </el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
#foreach($block in $embeddedBusinessBlocks)
import ${block.componentName} from "${block.relativeImportPath}"
#end

export default {
  name: "${BusinessName}",
#if($hasPageDesignEmbeddedBusinessBlocks)
  components: {
#foreach($block in $embeddedBusinessBlocks)
    ${block.componentName}#if($foreach.hasNext),#end
#end
  },
#end
  data() {
    return {
      ${businessName}List: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
#if($currentUserOnly)
        __currentUserOnly: true,
#end
#foreach ($column in $queryColumns)
#set($renderQueryParam = false)
#if(!$showQuery)
#set($renderQueryParam = false)
#elseif($designed)
#set($renderQueryParam = true)
#elseif($column.isQuery == "1")
#set($renderQueryParam = true)
#end
#if($renderQueryParam)
        ${column.javaField}: undefined,
#end
#end
      },
#if($isDetailPage)
      detailRecord: {},
      detailLoading: false,
      detailLoaded: false,
#end
      form: {},
      viewing: false,
      dialogFormVisible: false,
      businessActionDialogVisible: false,
      businessActionSubmitting: false,
      activeBusinessAction: null,
      businessActionBasePayload: {},
      businessActionForm: {},
      businessActionInputFields: [],
      multipleSelection: [],
      remoteOptionMap: {},
      remoteSelectConfig: {
#foreach($remote in $qingRemoteSelects)
        ${remote.field}: {
          path: "${remote.path}",
          valueField: "${remote.valueField}",
          labelField: "${remote.labelField}"
        }#if($foreach.hasNext),#end
#end
      },
      activeTab: "最新公告",
      noticeTabs: ["最新公告", "热门赛事", "热门攻略", "热门帖子"],
      notices: [
        { title: "《${functionName}》资源内容更新与支持", time: "2025-06-24 16:50:40" },
        { title: "社区活动与资源维护窗口预告", time: "2025-06-24 16:48:30" },
        { title: "新内容发布和玩家反馈整理", time: "2025-06-24 10:30:24" },
        { title: "版本资料、攻略和周边内容同步", time: "2025-06-23 19:20:12" }
      ],
      businessActionMap: {
#foreach($action in $allPageBusinessActions)
        "${action.code}": {
          name: "${action.name}",
          buttonLabel: "${action.buttonLabel}",
          method: "${action.method}",
          path: "${action.path}",
          successMessage: "${action.successMessage}",
          refreshTarget: "${action.refreshTarget}",
          confirmMessage: "${action.confirmMessage}",
          requestFields: [#foreach($field in $action.requestFields)"${field}"#if($foreach.hasNext), #end#end],
          currentUserFields: [#foreach($field in $action.currentUserFields)"${field}"#if($foreach.hasNext), #end#end],
          inputFields: [
#foreach($field in $action.inputFields)
            {
              field: "${field.field}",
              label: "${field.label}",
              htmlType: "${field.htmlType}",
              dictType: "${field.dictType}"
            }#if($foreach.hasNext),#end
#end
          ]
        }#if($foreach.count != $allPageBusinessActions.size()),#end
#end
      },
      routeActionMap: {
#foreach($routeAction in $pageDesignRouteActionEntries)
        "${routeAction.key}": {
          path: "${routeAction.path}",
          paramMap: {#set($paramMap = $routeAction.paramMap)#foreach($param in $paramMap.entrySet())"${param.key}":"${param.value}"#if($foreach.count != $paramMap.size()),#end#end}
        }#if($foreach.count != $pageDesignRouteActionEntries.size()),#end
#end
      }
    }
  },
  computed: {
    businessActionDialogTitle() {
      if (!this.activeBusinessAction) {
        return "业务操作"
      }
      return this.activeBusinessAction.buttonLabel || this.activeBusinessAction.name || "业务操作"
    }
  },
  created() {
    this.loadRemoteOptions()
#if($isDetailPage)
    this.loadDetail()
#else
    this.load()
#end
  },
  methods: {
    loadRemoteOptions() {
      Object.keys(this.remoteSelectConfig).forEach(field => {
        const config = this.remoteSelectConfig[field]
        this.request.get(config.path, {
          params: { pageNum: 1, pageSize: 999 }
        }).then(res => {
          const data = res.data || {}
          const records = Array.isArray(data) ? data : (data.records || [])
          const options = records.map(item => ({
            value: item[config.valueField],
            label: item[config.labelField]
          }))
          this.#[[$set]]#(this.remoteOptionMap, field, options)
        })
      })
    },
    getSelectOptions(field) {
      return this.remoteOptionMap[field] || []
    },
    getOptionLabel(field, value) {
      const option = this.getSelectOptions(field).find(item => String(item.value) === String(value))
      if (option) {
        return option.label
      }
      return value === undefined || value === null || value === "" ? "-" : value
    },
#if(!$isDetailPage)
    load() {
      this.request.get("/${moduleName}/${businessName}/page", {
        params: this.queryParams
      }).then(res => {
        const page = res.data || {}
        this.${businessName}List = page.records || []
        this.total = page.total || 0
      })
    },
#end
#if($isDetailPage)
    resolveDetailId() {
      const params = this.#[[$route]]# && this.#[[$route]]#.params ? this.#[[$route]]#.params : {}
      return params.id || params.${pkColumn.javaField} || ""
    },
    loadDetail() {
      const detailId = this.resolveDetailId()
      if (!detailId) {
        this.detailRecord = {}
        this.form = {}
        this.detailLoaded = true
        return
      }
      this.detailLoading = true
      this.request.get("/${moduleName}/${businessName}/" + detailId).then(res => {
        this.detailRecord = res.data || {}
        this.form = JSON.parse(JSON.stringify(this.detailRecord))
        this.detailLoaded = true
      }).finally(() => {
        this.detailLoading = false
      })
    },
    formatDetailValue(value) {
      return value === undefined || value === null || value === "" ? "-" : value
    },
#end
    save() {
      this.#[[$refs]]#.form.validate(valid => {
        if (!valid) {
          return
        }
        this.request.post("/${moduleName}/${businessName}", this.form).then(res => {
          if (res.code === "200") {
            this.#[[$message]]#.success("保存成功")
            this.dialogFormVisible = false
            this.load()
          } else {
            this.#[[$message]]#.error(res.msg || "保存失败")
          }
        })
      })
    },
    handleAdd() {
      if (this.handleConfiguredRoute("toolbar:create")) {
        return
      }
      this.form = {}
      this.viewing = false
      this.dialogFormVisible = true
      this.#[[$nextTick]]#(() => this.#[[$refs]]#.form && this.#[[$refs]]#.form.clearValidate())
    },
    handleView(row) {
      if (this.handleConfiguredRoute("table:view", row)) {
        return
      }
      if (this.handleConfiguredRoute("cardActions:view", row)) {
        return
      }
      this.form = JSON.parse(JSON.stringify(row))
      this.viewing = true
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      if (this.handleConfiguredRoute("table:edit", row)) {
        return
      }
      if (this.handleConfiguredRoute("cardActions:edit", row)) {
        return
      }
      this.form = JSON.parse(JSON.stringify(row))
      this.viewing = false
      this.dialogFormVisible = true
      this.#[[$nextTick]]#(() => this.#[[$refs]]#.form && this.#[[$refs]]#.form.clearValidate())
    },
    del(${pkColumn.javaField}) {
      this.request.delete("/${moduleName}/${businessName}/" + ${pkColumn.javaField}).then(res => {
        if (res.code === "200") {
          this.#[[$message]]#.success("删除成功")
          this.load()
        } else {
          this.#[[$message]]#.error(res.msg || "删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleCardSelectionChange() {
      this.multipleSelection = this.${businessName}List.filter(item => item.__checked)
    },
    handleConfiguredRoute(actionKey, row) {
      const action = this.routeActionMap[actionKey]
      if (!action || !action.path) {
        return false
      }
      const path = this.buildConfiguredRoutePath(action.path, action.paramMap || {}, row)
      if (!path) {
        return false
      }
      this.#[[$router]]#.push(path)
      return true
    },
    buildConfiguredRoutePath(routePath, paramMap, row) {
      let path = routePath
      Object.keys(paramMap || {}).forEach(param => {
        const field = paramMap[param]
        const value = row && row[field]
        if (value !== undefined && value !== null && value !== "") {
          path = path.replace(new RegExp(":" + param + "(?=/|$)", "g"), encodeURIComponent(value))
        }
      })
      return this.hasUnresolvedRouteParam(path) ? "" : path
    },
    hasUnresolvedRouteParam(path) {
      return String(path || "").split("/").some(segment => segment.indexOf(":") === 0)
    },
    delBatch() {
      const ids = this.multipleSelection.map(item => item.${pkColumn.javaField})
      if (!ids.length) {
        this.#[[$message]]#.warning("请先选择要删除的数据")
        return
      }
      this.request.post("/${moduleName}/${businessName}/del/batch", ids).then(res => {
        if (res.code === "200") {
          this.#[[$message]]#.success("批量删除成功")
          this.load()
        } else {
          this.#[[$message]]#.error(res.msg || "批量删除失败")
        }
      })
    },
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10#if($currentUserOnly),
        __currentUserOnly: true#end
      }
      this.load()
    },
    handleBusinessAction(code, row) {
      if (this.handleConfiguredRoute("business:" + code, row) || this.handleConfiguredRoute("toolbar:" + code, row) || this.handleConfiguredRoute("table:" + code, row)) {
        return
      }
      const action = this.businessActionMap[code]
      if (!action || !action.path) {
        this.#[[$message]]#.warning("动作未配置")
        return
      }
      const payload = this.buildBusinessActionPayload(action, row)
      const missingFields = (action.inputFields || []).filter(field => !this.hasBusinessActionValue(payload[field.field]))
      if (missingFields.length > 0) {
        this.openBusinessActionDialog(action, payload, missingFields)
        return
      }
      if (action.confirmMessage) {
        this.#[[$confirm]]#(action.confirmMessage, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => this.executeBusinessAction(action, payload)).catch(() => {})
        return
      }
      this.executeBusinessAction(action, payload).catch(() => {})
    },
    openBusinessActionDialog(action, payload, fields) {
      const form = {}
      fields.forEach(field => {
        form[field.field] = this.hasBusinessActionValue(payload[field.field]) ? payload[field.field] : undefined
      })
      this.activeBusinessAction = action
      this.businessActionBasePayload = Object.assign({}, payload)
      this.businessActionInputFields = fields.slice()
      this.businessActionForm = form
      this.businessActionDialogVisible = true
      this.#[[$nextTick]]#(() => {
        const formRef = this.#[[$refs]]#.businessActionForm
        if (formRef) {
          formRef.clearValidate()
        }
      })
    },
    submitBusinessAction() {
      const formRef = this.#[[$refs]]#.businessActionForm
      if (!formRef || !this.activeBusinessAction) {
        return
      }
      formRef.validate(valid => {
        if (!valid) {
          return
        }
        const action = this.activeBusinessAction
        const payload = Object.assign({}, this.businessActionBasePayload, this.businessActionForm)
        this.businessActionSubmitting = true
        this.executeBusinessAction(action, payload)
          .then(() => {
            this.businessActionDialogVisible = false
          })
          .catch(() => {})
          .finally(() => {
            this.businessActionSubmitting = false
          })
      })
    },
    resetBusinessActionDialog() {
      this.activeBusinessAction = null
      this.businessActionBasePayload = {}
      this.businessActionForm = {}
      this.businessActionInputFields = []
    },
    hasBusinessActionValue(value) {
      if (value === undefined || value === null) {
        return false
      }
      return typeof value !== "string" || value.trim() !== ""
    },
    getBusinessActionFieldOptions(field) {
      if (!field || !field.dictType) {
        return []
      }
      return this._dict.getDictDataByType(field.dictType).map(option => ({
        label: option.name,
        value: option.value
      }))
    },
    executeBusinessAction(action, payload) {
      const method = String(action.method || "POST").toLowerCase()
      const request = method === "get"
        ? this.request.get(action.path, { params: payload })
        : this.request[method] ? this.request[method](action.path, payload) : this.request.post(action.path, payload)
      return request.then(res => {
        if (res.code !== "200") {
          return Promise.reject(new Error(res.msg || "操作失败"))
        }
        this.#[[$message]]#.success(action.successMessage || "操作成功")
        this.refreshBusinessActionTarget(action.refreshTarget)
        return res
      }).catch(error => {
        const data = error && error.response ? error.response.data : null
        this.#[[$message]]#.error((data && data.msg) || (error && error.message) || "操作失败")
        return Promise.reject(error)
      })
    },
    refreshBusinessActionTarget(refreshTarget) {
      const target = refreshTarget || "list"
      if (target === "none") {
        return
      }
      if (target === "page") {
        window.location.reload()
        return
      }
#if($isDetailPage)
      this.loadDetail()
#else
      this.load()
#end
    },
    buildBusinessActionPayload(action, row) {
      const payload = {}
      const currentUserFields = new Set(action.currentUserFields || [])
      ;(action.requestFields || []).forEach(field => {
        if (currentUserFields.has(field)) {
          return
        }
        const value = this.resolvePayloadValue(field, row)
        if (value !== undefined) {
          payload[field] = value
        }
      })
      return payload
    },
    resolvePayloadValue(field, row) {
      const camelField = this.toCamelCase(field)
      const sources = [row, this.detailRecord, this.form, this.queryParams]
      for (const source of sources) {
        if (!source) {
          continue
        }
        if (source[field] !== undefined) {
          return source[field]
        }
        if (source[camelField] !== undefined) {
          return source[camelField]
        }
      }
      return undefined
    },
    toCamelCase(value) {
      return String(value || "").replace(/_([a-zA-Z0-9])/g, (_, char) => char.toUpperCase())
    },
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.load()
    },
    resolveResourceUrl(url) {
      if (!url) {
        return ""
      }
      if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0 || url.indexOf("//") === 0 || url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) {
        return url
      }
      if (url.indexOf("/api/") === 0) {
        return url
      }
      if (url.indexOf("/files/") === 0) {
        return "/api" + url
      }
      return url
    },
    uploadSuccess(field, res) {
      if (res && res.code === "200" && res.data && res.data.url) {
        this.#[[$set]]#(this.form, field, res.data.url)
      } else {
        this.#[[$message]]#.error("上传失败，请重试")
      }
    }
  }
}
</script>

<style scoped>
.portal-page {
  display: grid;
  gap: 22px;
}

.embedded-business-blocks {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 16px;
}

.embedded-business-block__item--span-12 { grid-column: span 12; }
.embedded-business-block__item--span-6 { grid-column: span 6; }
.embedded-business-block__item--span-4 { grid-column: span 4; }

.content-board {
  display: grid;
  grid-template-columns: minmax(0, 1.36fr) minmax(320px, 0.64fr);
  gap: 24px;
  align-items: stretch;
}

.feature-card {
  position: relative;
  min-height: 270px;
  overflow: hidden;
  background: #ffffff;
}

@media (max-width: 900px) {
  .embedded-business-block__item {
    grid-column: span 12;
  }
}

.feature-illustration {
  position: absolute;
  inset: 0;
  background:
    linear-gradient(135deg, rgba(10, 66, 99, 0.92), rgba(255, 126, 86, 0.9)),
    #184967;
}

.feature-illustration::before,
.feature-illustration::after {
  position: absolute;
  display: block;
  content: "";
}

.feature-illustration::before {
  left: 8%;
  top: 18%;
  width: 48%;
  height: 42%;
  border: 8px solid rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  transform: rotate(-8deg);
}

.feature-illustration::after {
  right: 9%;
  bottom: -12%;
  width: 290px;
  height: 290px;
  border-radius: 50%;
  background:
    radial-gradient(circle at 36% 38%, #ffffff 0 10px, transparent 11px),
    radial-gradient(circle at 64% 38%, #ffffff 0 10px, transparent 11px),
    radial-gradient(circle at 50% 58%, transparent 0 38px, #153d58 39px 45px, transparent 46px),
    #39a6d8;
  box-shadow: 0 20px 0 #133c58;
}

.device-face {
  position: absolute;
  left: 24%;
  bottom: 20%;
  display: grid;
  grid-template-columns: repeat(2, 36px);
  gap: 18px;
  padding: 18px;
  border-radius: 48px;
  background: rgba(21, 62, 88, 0.9);
  transform: rotate(7deg);
}

.device-face span {
  width: 36px;
  height: 36px;
  border: 5px solid #f7ebe0;
  border-radius: 50%;
}

.feature-copy {
  position: absolute;
  left: 28px;
  bottom: 24px;
  max-width: 420px;
  color: #ffffff;
}

.feature-copy span {
  display: inline-block;
  margin-bottom: 8px;
  color: #ffe1b6;
  font-size: 13px;
  font-weight: 700;
}

.feature-copy h2,
.feature-copy p,
.panel-heading h2 {
  margin: 0;
  letter-spacing: 0;
}

.feature-copy h2 {
  font-size: 28px;
  line-height: 1.25;
}

.feature-copy p {
  margin-top: 8px;
  color: rgba(255, 255, 255, 0.88);
  line-height: 1.7;
}

.notice-panel {
  min-width: 0;
  background: #ffffff;
}

.notice-tabs {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 10px;
  border-bottom: 1px solid #edf0f5;
}

.notice-tabs button {
  position: relative;
  min-height: 38px;
  border: 0;
  color: #475569;
  background: transparent;
  cursor: pointer;
}

.notice-tabs button.active {
  color: #19a6ad;
  font-weight: 700;
}

.notice-tabs button.active::after {
  position: absolute;
  right: 8px;
  bottom: -1px;
  left: 8px;
  height: 2px;
  background: #19a6ad;
  content: "";
}

.notice-list {
  display: grid;
  gap: 18px;
  margin: 16px 0 0;
  padding: 0;
  list-style: none;
}

.notice-list li {
  display: grid;
  gap: 7px;
}

.notice-list strong {
  color: #172033;
  font-size: 15px;
  font-weight: 500;
  line-height: 1.55;
}

.notice-list span {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: #7b8493;
  font-size: 13px;
}

.data-panel,
.notice-panel {
  padding: 20px;
  border: 1px solid #edf0f5;
  border-radius: 4px;
}

.data-panel {
  background: #ffffff;
}

.split-data-panel {
  display: grid;
  grid-template-columns: 260px minmax(0, 1fr);
  gap: 16px;
}

.split-data-panel .panel-heading {
  grid-column: 1 / -1;
  margin-bottom: 0;
}

.split-data-panel .filter-bar {
  align-content: flex-start;
  align-self: start;
  flex-direction: column;
  margin-bottom: 0;
  padding: 14px;
  border: 1px solid #edf0f5;
  border-radius: 4px;
  background: #f8fafc;
}

.split-data-panel .filter-item,
.split-data-panel .filter-bar .el-button {
  width: 100%;
}

.split-data-panel .resource-table,
.split-data-panel .resource-card-grid,
.split-data-panel .pagination {
  grid-column: 2;
}

.panel-heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 18px;
}

.section-kicker {
  color: #19a6ad;
  font-size: 13px;
  font-weight: 700;
}

.panel-heading h2 {
  margin-top: 6px;
  color: #172033;
  font-size: 22px;
}

.panel-actions,
.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-bar {
  margin-bottom: 14px;
}

.filter-item {
  width: 220px;
}

.resource-table {
  width: 100%;
}

.resource-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 14px;
}

.resource-card-item {
  position: relative;
  display: grid;
  gap: 12px;
  min-height: 180px;
  padding: 16px;
  border: 1px solid #edf0f5;
  border-radius: 4px;
  background: #ffffff;
}

.resource-card-check {
  position: absolute;
  top: 12px;
  right: 12px;
}

.resource-card-body {
  display: grid;
  gap: 10px;
}

.resource-card-field {
  display: grid;
  gap: 4px;
}

.resource-card-title {
  margin: 0;
  color: #172033;
  font-size: 17px;
  line-height: 1.35;
}

.resource-card-field span {
  color: #7b8493;
  font-size: 12px;
}

.resource-card-field strong {
  color: #172033;
  font-size: 14px;
  font-weight: 600;
  line-height: 1.45;
  word-break: break-word;
}

.resource-card-image {
  width: 100%;
  height: 132px;
  border-radius: 4px;
  object-fit: cover;
}

.resource-card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 4px;
  border-top: 1px solid #edf0f5;
}

.detail-view {
  min-height: 180px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 14px 18px;
  margin: 0;
}

.detail-field {
  display: grid;
  gap: 6px;
  padding: 14px 0;
  border-bottom: 1px solid #edf0f5;
}

.detail-field.wide {
  grid-column: 1 / -1;
}

.detail-field dt {
  color: #7b8493;
  font-size: 13px;
  font-weight: 600;
}

.detail-field dd {
  margin: 0;
  color: #172033;
  font-size: 15px;
  line-height: 1.65;
  word-break: break-word;
}

.detail-image {
  width: 180px;
  height: 128px;
  border-radius: 4px;
  object-fit: cover;
}

.detail-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 18px;
  padding-top: 16px;
  border-top: 1px solid #edf0f5;
}

.empty-detail {
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 120px;
  color: #7b8493;
}

.pagination {
  margin-top: 14px;
  text-align: right;
}

.danger-text {
  color: #f56c6c;
}

.table-image {
  width: 52px;
  height: 52px;
  border-radius: 4px;
}

.avatar-uploader .avatar {
  display: block;
  width: 96px;
  height: 96px;
  object-fit: cover;
}

.avatar-uploader-icon {
  width: 96px;
  height: 96px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  color: #8c939d;
  line-height: 96px;
  text-align: center;
}

.file-link {
  margin-top: 6px;
  color: #606266;
  word-break: break-all;
}

.business-action-hint {
  margin: 0 0 18px;
  padding: 10px 12px;
  border-radius: 4px;
  color: #606266;
  background: #f5f7fa;
  line-height: 1.6;
}

.business-action-hint + .el-form .el-date-editor,
.business-action-hint + .el-form .el-select,
.business-action-hint + .el-form .el-input,
.el-dialog .el-form .el-date-editor,
.el-dialog .el-form .el-select {
  width: 100%;
}

@media (max-width: 980px) {
  .content-board {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 720px) {
  .split-data-panel {
    grid-template-columns: 1fr;
  }

  .split-data-panel .panel-heading,
  .split-data-panel .resource-table,
  .split-data-panel .resource-card-grid,
  .split-data-panel .pagination {
    grid-column: 1;
  }

  .panel-heading {
    align-items: flex-start;
    flex-direction: column;
  }

  .filter-item {
    width: 100%;
  }

  .notice-tabs {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
', 'admin', sysdate()),
(920312, 9203, 'frontend-login.vue.vm', NULL, 'frontend-login.vue.vm', '#set($portalProjectName = $projectName)
#if(!$portalProjectName || $portalProjectName == "")
#set($portalProjectName = $functionName)
#end
#if(!$portalProjectName || $portalProjectName == "")
#set($portalProjectName = "Portal")
#end
#set($portalDefaultPath = $defaultFrontendPath)
#if(!$portalDefaultPath || $portalDefaultPath == "")
#set($portalDefaultPath = "/${moduleName}/${businessName}")
#end
<template>
  <section class="portal-login">
    <div class="login-visual" aria-hidden="true">
      <div class="login-brand">
        <span class="login-logo"></span>
        <strong>${portalProjectName}</strong>
      </div>
      <h1>${portalProjectName}</h1>
      <p>登录后继续访问你的项目功能和个人数据。</p>
    </div>

    <div class="login-panel">
      <div class="login-heading">
        <span>欢迎回来</span>
        <h2>账号登录</h2>
      </div>

      <el-form :model="form" label-position="top" class="login-form" @submit.native.prevent>
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名" prefix-icon="el-icon-user" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock" show-password />
        </el-form-item>
        <el-button type="primary" class="login-button" :loading="loading" @click="handleLogin">登录</el-button>
      </el-form>
    </div>
  </section>
</template>

<script>
export default {
  name: "PortalLogin",
  data() {
    return {
      loading: false,
      form: {
        username: "user",
        password: "[REDACTED]
      }
    }
  },
  methods: {
    handleLogin() {
      if (!this.form.username || !this.form.password) {
        this.#[[$message]]#.warning("请输入用户名和密码")
        return
      }

      this.loading = true
      this.request.post("/auth/login", this.form)
        .then(res => {
          if (!res || res.code !== "200" || !res.data || !res.data.token) {
            throw new Error((res && res.msg) || "登录失败")
          }
          localStorage.setItem("portal-token", res.data.token)
          localStorage.setItem("portal-user", JSON.stringify(res.data.user || {
            username: this.form.username,
            nickname: this.form.username
          }))
          window.dispatchEvent(new Event("portal-user-change"))
          this.#[[$message]]#.success("登录成功")
          const redirect = this.#[[$route]]#.query.redirect || "${portalDefaultPath}"
          this.#[[$router]]#.push(redirect)
        })
        .catch(error => {
          this.#[[$message]]#.error(error.message || "登录失败")
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped>
.portal-login {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 430px;
  min-height: 100vh;
  background:
    linear-gradient(132deg, rgba(24, 141, 149, 0.95), rgba(44, 120, 215, 0.88)),
    #168d95;
}

.login-visual {
  position: relative;
  display: flex;
  min-width: 0;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
  padding: 72px 9vw;
  color: #ffffff;
}

.login-visual::before {
  position: absolute;
  inset: 0;
  display: block;
  content: "";
  opacity: 0.58;
  background:
    linear-gradient(42deg, transparent 0 18%, rgba(255, 255, 255, 0.18) 18% 27%, transparent 27% 100%),
    linear-gradient(132deg, transparent 0 48%, rgba(246, 186, 51, 0.32) 48% 55%, transparent 55% 100%);
}

.login-brand,
.login-visual h1,
.login-visual p {
  position: relative;
  z-index: 1;
}

.login-brand {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 46px;
  font-size: 22px;
}

.login-logo {
  width: 28px;
  height: 28px;
  border-radius: 8px 18px 8px 18px;
  background: linear-gradient(135deg, #38d8f0 0 35%, #f3ba28 35% 66%, #5bc269 66%);
  transform: rotate(45deg);
}

.login-visual h1,
.login-visual p {
  margin: 0;
}

.login-visual h1 {
  max-width: 680px;
  font-size: 52px;
  font-weight: 600;
  letter-spacing: 0;
  line-height: 1.18;
}

.login-visual p {
  max-width: 520px;
  margin-top: 20px;
  color: rgba(255, 255, 255, 0.88);
  font-size: 17px;
  line-height: 1.8;
}

.login-panel {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 48px;
  background: #ffffff;
}

.login-heading span {
  color: #168d95;
  font-size: 14px;
  font-weight: 700;
}

.login-heading h2 {
  margin: 8px 0 28px;
  color: #111827;
  font-size: 30px;
  font-weight: 700;
  letter-spacing: 0;
}

.login-form {
  display: grid;
  gap: 2px;
}

.login-button {
  width: 100%;
  height: 42px;
  margin-top: 6px;
  border-color: #168d95;
  background: #168d95;
}

@media (max-width: 880px) {
  .portal-login {
    grid-template-columns: 1fr;
  }

  .login-visual {
    min-height: 280px;
    padding: 42px 26px;
  }

  .login-visual h1 {
    font-size: 36px;
  }

  .login-panel {
    padding: 34px 24px 44px;
  }
}
</style>
', 'admin', sysdate()),
(920313, 9203, 'frontend-dict.js.vm', NULL, 'frontend-dict.js.vm', 'const emptyDict = []

export default {
  getDictDataByType() {
    return emptyDict
  },
  getDictLabel(type, value) {
    return value === undefined || value === null || value === "" ? "-" : value
  }
}
', 'admin', sysdate());

-- Backend project structure
INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(920100, 0, '{projectName}-backend', 'folder', NULL, 9201, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920101, 920100, 'pom.xml', 'file', NULL, 9201, -1, 'pom.xml.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920102, 920100, 'README.md', 'file', NULL, 9201, -1, 'README.md.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920103, 920100, 'sql', 'folder', NULL, 9201, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(920104, 920103, '{businessName}.sql', 'file', NULL, 9201, 0, 'sql.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920110, 920100, 'src', 'folder', NULL, 9201, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(920111, 920110, 'main', 'folder', NULL, 9201, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920112, 920111, 'java', 'folder', NULL, 9201, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920113, 920111, 'resources', 'folder', NULL, 9201, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(920114, 920112, '{packagePath}', 'folder', NULL, 9201, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920115, 920114, '{projectClassName}Application.java', 'file', NULL, 9201, -1, 'Application.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920116, 920114, 'common', 'folder', NULL, 9201, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(920117, 920116, 'Result.java', 'file', NULL, 9201, -1, 'Result.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920118, 920114, 'config', 'folder', NULL, 9201, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(920119, 920118, 'MybatisPlusConfig.java', 'file', NULL, 9201, -1, 'MybatisPlusConfig.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920120, 920118, 'CorsConfig.java', 'file', NULL, 9201, -1, 'CorsConfig.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920121, 920114, 'controller', 'folder', NULL, 9201, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(920122, 920121, 'FileController.java', 'file', NULL, 9201, -1, 'FileController.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920123, 920121, '{ClassName}Controller.java', 'file', NULL, 9201, 0, 'controller.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920124, 920114, 'entity', 'folder', NULL, 9201, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(920125, 920124, '{ClassName}.java', 'file', NULL, 9201, 0, 'entity.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920126, 920114, 'mapper', 'folder', NULL, 9201, NULL, NULL, 6, '0', 'admin', sysdate(), '', NULL),
(920127, 920126, '{ClassName}Mapper.java', 'file', NULL, 9201, 0, 'mapper.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920128, 920114, 'service', 'folder', NULL, 9201, NULL, NULL, 7, '0', 'admin', sysdate(), '', NULL),
(920129, 920128, 'I{ClassName}Service.java', 'file', NULL, 9201, 0, 'service.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920130, 920128, 'impl', 'folder', NULL, 9201, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(920131, 920130, '{ClassName}ServiceImpl.java', 'file', NULL, 9201, 0, 'serviceImpl.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920132, 920113, 'application.yml', 'file', NULL, 9201, -1, 'application.yml.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920133, 920113, 'mapper', 'folder', NULL, 9201, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(920134, 920133, '{moduleName}', 'folder', NULL, 9201, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920135, 920134, '{ClassName}Mapper.xml', 'file', NULL, 9201, 0, 'mapper.xml.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920136, 920124, 'PortalUser.java', 'file', NULL, 9201, -1, 'PortalUser.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920137, 920126, 'PortalUserMapper.java', 'file', NULL, 9201, -1, 'PortalUserMapper.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920138, 920114, 'security', 'folder', NULL, 9201, NULL, NULL, 8, '0', 'admin', sysdate(), '', NULL),
(920139, 920138, 'PortalAuthTokenStore.java', 'file', NULL, 9201, -1, 'PortalAuthTokenStore.java.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920140, 920138, 'PortalAuthInterceptor.java', 'file', NULL, 9201, -1, 'PortalAuthInterceptor.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920141, 920121, 'PortalAuthController.java', 'file', NULL, 9201, -1, 'PortalAuthController.java.vm', 3, '0', 'admin', sysdate(), '', NULL),
(920142, 920124, 'AdminUser.java', 'file', NULL, 9201, -1, 'AdminUser.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920143, 920126, 'AdminUserMapper.java', 'file', NULL, 9201, -1, 'AdminUserMapper.java.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920144, 920121, 'AdminAuthController.java', 'file', NULL, 9201, -1, 'AdminAuthController.java.vm', 4, '0', 'admin', sysdate(), '', NULL);

-- Admin frontend project structure
INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(920200, 0, '{projectName}-admin', 'folder', NULL, 9202, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920201, 920200, 'package.json', 'file', NULL, 9202, -1, 'package.json.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920202, 920200, 'babel.config.js', 'file', NULL, 9202, -1, 'babel.config.js.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920203, 920200, 'vue.config.js', 'file', NULL, 9202, -1, 'vue.config.js.vm', 3, '0', 'admin', sysdate(), '', NULL),
(920204, 920200, 'public', 'folder', NULL, 9202, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(920205, 920204, 'index.html', 'file', NULL, 9202, -1, 'index.html.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920206, 920200, 'src', 'folder', NULL, 9202, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(920207, 920206, 'main.js', 'file', NULL, 9202, -1, 'admin-main.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920208, 920206, 'App.vue', 'file', NULL, 9202, -1, 'admin-App.vue.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920209, 920206, 'router', 'folder', NULL, 9202, NULL, NULL, 3, '0', 'admin', sysdate(), '', NULL),
(920210, 920209, 'index.js', 'file', NULL, 9202, -1, 'admin-router.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920211, 920206, 'utils', 'folder', NULL, 9202, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(920212, 920211, 'request.js', 'file', NULL, 9202, -1, 'request.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920213, 920211, 'dict.js', 'file', NULL, 9202, -1, 'dict.js.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920214, 920206, 'views', 'folder', NULL, 9202, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(920218, 920214, 'login', 'folder', NULL, 9202, -1, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920219, 920218, 'index.vue', 'file', NULL, 9202, -1, 'admin-login.vue.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920215, 920214, '{moduleName}', 'folder', NULL, 9202, 0, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(920216, 920215, '{businessName}', 'folder', NULL, 9202, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920217, 920216, 'index.vue', 'file', NULL, 9202, 0, 'admin-index.vue.vm', 1, '0', 'admin', sysdate(), '', NULL);

-- Portal frontend project structure
INSERT INTO sys_project_structure (node_id, parent_id, node_name, node_type, module, template_id, table_id, category, sort_order, status, create_by, create_time, update_by, update_time) VALUES
(920300, 0, '{projectName}-web', 'folder', NULL, 9203, NULL, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920301, 920300, 'package.json', 'file', NULL, 9203, -1, 'package.json.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920302, 920300, 'babel.config.js', 'file', NULL, 9203, -1, 'babel.config.js.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920303, 920300, 'vue.config.js', 'file', NULL, 9203, -1, 'vue.config.js.vm', 3, '0', 'admin', sysdate(), '', NULL),
(920304, 920300, 'public', 'folder', NULL, 9203, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(920305, 920304, 'index.html', 'file', NULL, 9203, -1, 'index.html.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920306, 920300, 'src', 'folder', NULL, 9203, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(920307, 920306, 'main.js', 'file', NULL, 9203, -1, 'frontend-main.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920308, 920306, 'App.vue', 'file', NULL, 9203, -1, 'frontend-App.vue.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920309, 920306, 'style.css', 'file', NULL, 9203, -1, 'style.css.vm', 3, '0', 'admin', sysdate(), '', NULL),
(920310, 920306, 'router', 'folder', NULL, 9203, NULL, NULL, 4, '0', 'admin', sysdate(), '', NULL),
(920311, 920310, 'index.js', 'file', NULL, 9203, -1, 'frontend-router.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920312, 920306, 'api', 'folder', NULL, 9203, NULL, NULL, 5, '0', 'admin', sysdate(), '', NULL),
(920313, 920312, 'request.js', 'file', NULL, 9203, -1, 'frontend-request.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920314, 920312, '{businessName}.js', 'file', NULL, 9203, 0, 'frontend-api.js.vm', 2, '0', 'admin', sysdate(), '', NULL),
(920321, 920306, 'utils', 'folder', NULL, 9203, NULL, NULL, 6, '0', 'admin', sysdate(), '', NULL),
(920322, 920321, 'dict.js', 'file', NULL, 9203, -1, 'frontend-dict.js.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920315, 920306, 'views', 'folder', NULL, 9203, NULL, NULL, 7, '0', 'admin', sysdate(), '', NULL),
(920316, 920315, '{moduleName}', 'folder', NULL, 9203, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920317, 920316, '{businessName}', 'folder', NULL, 9203, 0, NULL, 1, '0', 'admin', sysdate(), '', NULL),
(920318, 920317, 'index.vue', 'file', NULL, 9203, 0, 'frontend-index.vue.vm', 1, '0', 'admin', sysdate(), '', NULL),
(920319, 920315, 'login', 'folder', NULL, 9203, NULL, NULL, 2, '0', 'admin', sysdate(), '', NULL),
(920320, 920319, 'index.vue', 'file', NULL, 9203, -1, 'frontend-login.vue.vm', 1, '0', 'admin', sysdate(), '', NULL);
SET FOREIGN_KEY_CHECKS = 1;
