初始化-安装依赖

This commit is contained in:
2026-03-03 10:06:12 +08:00
parent 3f349a35a4
commit ec8cac4221
187 changed files with 26292 additions and 0 deletions

View File

@@ -0,0 +1,289 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\utils\code;
use Twig\TwigFilter;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use plugin\saiadmin\exception\ApiException;
// 定义目录分隔符常量
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
/**
* 代码生成引擎
*/
class CodeEngine
{
/**
* @var array 值栈
*/
private array $value = [];
/**
* 模板名称
* @var string
*/
private string $stub = 'saiadmin';
/**
* 获取配置文件
* @return string[]
*/
private static function _getConfig(): array
{
return [
'template_path' => base_path() . DS . 'plugin' . DS . 'saiadmin' . DS . 'utils' . DS . 'code' . DS . 'stub',
'generate_path' => runtime_path() . DS . 'code_engine' . DS . 'saiadmin',
];
}
/**
* 初始化
* @param array $data 数据
*/
public function __construct(array $data)
{
// 读取配置文件
$config = self::_getConfig();
// 判断模板是否存在
if (!is_dir($config['template_path'])) {
throw new ApiException('模板目录不存在!');
}
// 判断文件生成目录是否存在
if (!is_dir($config['generate_path'])) {
mkdir($config['generate_path'], 0770, true);
}
// 赋值
$this->value = $data;
}
/**
* 设置模板名称
* @param $stub
* @return void
*/
public function setStub($stub): void
{
$this->stub = $stub;
}
/**
* 渲染文件内容
*/
public function renderContent($path, $filename): string
{
$config = self::_getConfig();
$path = $config['template_path'] . DS . $this->stub . DS . $path;
$loader = new FilesystemLoader($path);
$twig = new Environment($loader);
$camelFilter = new TwigFilter('camel', function ($value) {
static $cache = [];
$key = $value;
if (isset($cache[$key])) {
return $cache[$key];
}
$value = ucwords(str_replace(['-', '_'], ' ', $value));
return $cache[$key] = str_replace(' ', '', $value);
});
$boolFilter = new TwigFilter('bool', function ($value) {
if ($value == 1) {
return 'true';
} else {
return 'false';
}
});
$formatFilter = new TwigFilter('formatNumber', function ($value) {
if (ctype_digit((string) $value)) {
return $value;
} else {
return '1';
}
});
$defaultFilter = new TwigFilter('parseNumber', function ($value) {
if ($value) {
return $value;
} else {
return 'null';
}
});
$containsFilter = new TwigFilter('str_contains', function ($haystack, $needle) {
return str_contains($haystack ?? '', $needle ?? '');
});
$twig->addFilter($camelFilter);
$twig->addFilter($boolFilter);
$twig->addFilter($containsFilter);
$twig->addFilter($formatFilter);
$twig->addFilter($defaultFilter);
return $twig->render($filename, $this->value);
}
/**
* 生成后端文件
*/
public function generateBackend($action, $content): void
{
$outPath = '';
if ($this->value['template'] == 'app') {
$rootPath = base_path() . DS . 'app' . DS . $this->value['namespace'];
$adminPath = '';
} else {
$rootPath = base_path() . DS . 'plugin' . DS . $this->value['namespace'] . DS . 'app';
$adminPath = DS . 'admin';
}
$subPath = DS . $this->value['package_name'];
switch ($action) {
case 'controller':
$outPath = $rootPath . $adminPath . DS . 'controller' . $subPath . DS . $this->value['class_name'] . 'Controller.php';
break;
case 'logic':
$outPath = $rootPath . $adminPath . DS . 'logic' . $subPath . DS . $this->value['class_name'] . 'Logic.php';
break;
case 'validate':
$outPath = $rootPath . $adminPath . DS . 'validate' . $subPath . DS . $this->value['class_name'] . 'Validate.php';
break;
case 'model':
$outPath = $rootPath . DS . 'model' . $subPath . DS . $this->value['class_name'] . '.php';
break;
default:
break;
}
if (empty($outPath)) {
throw new ApiException('文件类型异常,无法生成指定文件!');
}
if (!is_dir(dirname($outPath))) {
mkdir(dirname($outPath), 0777, true);
}
file_put_contents($outPath, $content);
}
/**
* 生成前端文件
*/
public function generateFrontend($action, $content): void
{
$rootPath = dirname(base_path()) . DS . $this->value['generate_path'];
if (!is_dir($rootPath)) {
throw new ApiException('前端目录查找失败,必须与后端目录为同级目录!');
}
$rootPath = $rootPath . DS . 'src' . DS . 'views' . DS . 'plugin' . DS . $this->value['namespace'];
$subPath = DS . $this->value['package_name'];
switch ($action) {
case 'index':
$outPath = $rootPath . $subPath . DS . $this->value['business_name'] . DS . 'index.vue';
break;
case 'edit-dialog':
$outPath = $rootPath . $subPath . DS . $this->value['business_name'] . DS . 'modules' . DS . 'edit-dialog.vue';
break;
case 'table-search':
$outPath = $rootPath . $subPath . DS . $this->value['business_name'] . DS . 'modules' . DS . 'table-search.vue';
break;
case 'api':
$outPath = $rootPath . DS . 'api' . $subPath . DS . $this->value['business_name'] . '.ts';
break;
default:
break;
}
if (empty($outPath)) {
throw new ApiException('文件类型异常,无法生成指定文件!');
}
if (!is_dir(dirname($outPath))) {
mkdir(dirname($outPath), 0777, true);
}
file_put_contents($outPath, $content);
}
/**
* 生成临时文件
*/
public function generateTemp(): void
{
$config = self::_getConfig();
$rootPath = $config['generate_path'];
$vuePath = $rootPath . DS . 'vue' . DS . 'src' . DS . 'views' . DS . 'plugin' . DS . $this->value['namespace'];
$phpPath = $rootPath . DS . 'php';
$sqlPath = $rootPath . DS . 'sql';
if ($this->value['template'] == 'app') {
$phpPath = $phpPath . DS . 'app' . DS . $this->value['namespace'];
$adminPath = '';
} else {
$phpPath = $phpPath . DS . 'plugin' . DS . $this->value['namespace'] . DS . 'app';
$adminPath = DS . 'admin';
}
$subPath = DS . $this->value['package_name'];
$indexOutPath = $vuePath . $subPath . DS . $this->value['business_name'] . DS . 'index.vue';
$this->checkPath($indexOutPath);
$indexContent = $this->renderContent('vue', 'index.stub');
file_put_contents($indexOutPath, $indexContent);
$editOutPath = $vuePath . $subPath . DS . $this->value['business_name'] . DS . 'modules' . DS . 'edit-dialog.vue';
$this->checkPath($editOutPath);
$editContent = $this->renderContent('vue', 'edit-dialog.stub');
file_put_contents($editOutPath, $editContent);
$searchOutPath = $vuePath . $subPath . DS . $this->value['business_name'] . DS . 'modules' . DS . 'table-search.vue';
$this->checkPath($searchOutPath);
$searchContent = $this->renderContent('vue', 'table-search.stub');
file_put_contents($searchOutPath, $searchContent);
$viewOutPath = $vuePath . DS . 'api' . $subPath . DS . $this->value['business_name'] . '.ts';
$this->checkPath($viewOutPath);
$viewContent = $this->renderContent('ts', 'api.stub');
file_put_contents($viewOutPath, $viewContent);
$controllerOutPath = $phpPath . $adminPath . DS . 'controller' . $subPath . DS . $this->value['class_name'] . 'Controller.php';
$this->checkPath($controllerOutPath);
$controllerContent = $this->renderContent('php', 'controller.stub');
file_put_contents($controllerOutPath, $controllerContent);
$logicOutPath = $phpPath . $adminPath . DS . 'logic' . $subPath . DS . $this->value['class_name'] . 'Logic.php';
$this->checkPath($logicOutPath);
$logicContent = $this->renderContent('php', 'logic.stub');
file_put_contents($logicOutPath, $logicContent);
$validateOutPath = $phpPath . $adminPath . DS . 'validate' . $subPath . DS . $this->value['class_name'] . 'Validate.php';
$this->checkPath($validateOutPath);
$validateContent = $this->renderContent('php', 'validate.stub');
file_put_contents($validateOutPath, $validateContent);
$modelOutPath = $phpPath . DS . 'model' . $subPath . DS . $this->value['class_name'] . '.php';
$this->checkPath($modelOutPath);
$modelContent = $this->renderContent('php', 'model.stub');
file_put_contents($modelOutPath, $modelContent);
$sqlOutPath = $sqlPath . DS . 'sql.sql';
$this->checkPath($sqlOutPath);
$sqlContent = $this->renderContent('sql', 'sql.stub');
file_put_contents($sqlOutPath, $sqlContent);
}
/**
* 检查并生成路径
* @param $path
* @return void
*/
protected function checkPath($path): void
{
if (!is_dir(dirname($path))) {
mkdir(dirname($path), 0777, true);
}
}
}

View File

@@ -0,0 +1,164 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\utils\code;
use plugin\saiadmin\exception\ApiException;
/**
* 代码构建 压缩类
*/
class CodeZip
{
/**
* 获取配置文件
* @return string[]
*/
private static function _getConfig(): array
{
return [
'template_path' => base_path().DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'saiadmin'.DIRECTORY_SEPARATOR.'utils'.DIRECTORY_SEPARATOR.'code'.DIRECTORY_SEPARATOR.'stub',
'generate_path' => runtime_path().DIRECTORY_SEPARATOR.'code_engine'.DIRECTORY_SEPARATOR.'saiadmin',
];
}
/**
* 构造器
*/
public function __construct()
{
// 读取配置文件
$config = self::_getConfig();
// 清理源目录
if (is_dir($config['generate_path'])) {
$this->recursiveDelete($config['generate_path']);
}
// 清理压缩文件
$zipName = $config['generate_path'].'.zip';
if (is_file($zipName)) {
unlink($zipName);
}
}
/**
* 文件压缩
*/
public function compress(bool $isDownload = false)
{
// 读取配置文件
$config = self::_getConfig();
$zipArc = new \ZipArchive;
$zipName = $config['generate_path'].'.zip';
$dirPath = $config['generate_path'];
if ($zipArc->open($zipName, \ZipArchive::OVERWRITE | \ZipArchive::CREATE) !== true) {
throw new ApiException('无法打开文件,或者文件创建失败');
}
$this->addFileToZip($dirPath, $zipArc);
$zipArc->close();
// 是否下载
if ($isDownload) {
$this->toBinary($zipName);
} else {
return $zipName;
}
}
/**
* 文件解压
*/
public function deCompress(string $file, string $dirName)
{
if (!file_exists($file)) {
return false;
}
// zip实例化对象
$zipArc = new \ZipArchive();
// 打开文件
if (!$zipArc->open($file)) {
return false;
}
// 解压文件
if (!$zipArc->extractTo($dirName)) {
// 关闭
$zipArc->close();
return false;
}
return $zipArc->close();
}
/**
* 将文件加入到压缩包
*/
public function addFileToZip($rootPath, $zip)
{
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
}
/**
* 递归删除目录下所有文件和文件夹
*/
public function recursiveDelete($dir)
{
// 打开指定目录
if ($handle = @opendir($dir)) {
while (($file = readdir($handle)) !== false) {
if (($file == ".") || ($file == "..")) {
continue;
}
if (is_dir($dir . '/' . $file)) {
// 递归
self::recursiveDelete($dir . '/' . $file);
} else {
unlink($dir . '/' . $file); // 删除文件
}
}
@closedir($handle);
}
rmdir($dir);
}
/**
* 下载二进制流文件
*/
public function toBinary(string $fileName)
{
try {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename=' . basename($fileName)); //文件名
header("Content-Type: application/zip"); //zip格式的
header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
header('Content-Length: ' . filesize($fileName)); //告诉浏览器,文件大小
if(ob_get_length() > 0) {
ob_clean();
}
flush();
@readfile($fileName);
@unlink($fileName);
} catch (\Throwable $th) {
throw new ApiException('系统生成文件错误');
}
}
}

View File

@@ -0,0 +1,137 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace {{namespace_start}}controller{{namespace_end}};
use plugin\saiadmin\basic\BaseController;
use {{namespace_start}}logic{{namespace_end}}\{{class_name}}Logic;
use {{namespace_start}}validate{{namespace_end}}\{{class_name}}Validate;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;
/**
* {{menu_name}}控制器
*/
class {{class_name}}Controller extends BaseController
{
/**
* 构造函数
*/
public function __construct()
{
$this->logic = new {{class_name}}Logic();
$this->validate = new {{class_name}}Validate;
parent::__construct();
}
/**
* 数据列表
* @param Request $request
* @return Response
*/
#[Permission('{{menu_name}}列表', '{{namespace}}:{{package_name}}:{{business_name}}:index')]
public function index(Request $request): Response
{
$where = $request->more([
{% for column in columns %}
{% if column.is_query == '2' %}
['{{column.column_name}}', ''],
{% endif %}
{% endfor %}
]);
{% if tpl_category == 'single' %}
$query = $this->logic->search($where);
{% if options.relations != null %}
$query->with([
{% for item in options.relations %}
'{{item.name}}',
{% endfor %}
]);
{% endif %}
$data = $this->logic->getList($query);
{% endif %}
{% if tpl_category == 'tree' %}
$data = $this->logic->tree($where);
{% endif %}
return $this->success($data);
}
/**
* 读取数据
* @param Request $request
* @return Response
*/
#[Permission('{{menu_name}}读取', '{{namespace}}:{{package_name}}:{{business_name}}:read')]
public function read(Request $request): Response
{
$id = $request->input('id', '');
$model = $this->logic->read($id);
if ($model) {
$data = is_array($model) ? $model : $model->toArray();
return $this->success($data);
} else {
return $this->fail('未查找到信息');
}
}
/**
* 保存数据
* @param Request $request
* @return Response
*/
#[Permission('{{menu_name}}添加', '{{namespace}}:{{package_name}}:{{business_name}}:save')]
public function save(Request $request): Response
{
$data = $request->post();
$this->validate('save', $data);
$result = $this->logic->add($data);
if ($result) {
return $this->success('添加成功');
} else {
return $this->fail('添加失败');
}
}
/**
* 更新数据
* @param Request $request
* @return Response
*/
#[Permission('{{menu_name}}修改', '{{namespace}}:{{package_name}}:{{business_name}}:update')]
public function update(Request $request): Response
{
$data = $request->post();
$this->validate('update', $data);
$result = $this->logic->edit($data['id'], $data);
if ($result) {
return $this->success('修改成功');
} else {
return $this->fail('修改失败');
}
}
/**
* 删除数据
* @param Request $request
* @return Response
*/
#[Permission('{{menu_name}}删除', '{{namespace}}:{{package_name}}:{{business_name}}:destroy')]
public function destroy(Request $request): Response
{
$ids = $request->post('ids', '');
if (empty($ids)) {
return $this->fail('请选择要删除的数据');
}
$result = $this->logic->destroy($ids);
if ($result) {
return $this->success('删除成功');
} else {
return $this->fail('删除失败');
}
}
}

View File

@@ -0,0 +1,89 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace {{namespace_start}}logic{{namespace_end}};
{% if stub == 'eloquent' %}
use plugin\saiadmin\basic\eloquent\BaseLogic;
{% else %}
use plugin\saiadmin\basic\think\BaseLogic;
{% endif %}
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\utils\Helper;
use {{namespace_start_model}}model{{namespace_end}}\{{class_name}};
/**
* {{menu_name}}逻辑层
*/
class {{class_name}}Logic extends BaseLogic
{
/**
* 构造函数
*/
public function __construct()
{
$this->model = new {{class_name}}();
}
{% if tpl_category == 'tree' %}
/**
* 修改数据
* @param $id
* @param $data
* @return mixed
*/
public function edit($id, $data): mixed
{
if (!isset($data['{{options.tree_parent_id}}'])) {
$data['{{options.tree_parent_id}}'] = 0;
}
if ($data['{{options.tree_parent_id}}'] == $data['{{options.tree_id}}']) {
throw new ApiException('不能设置父级为自身');
}
return parent::edit($id, $data);
}
/**
* 删除数据
* @param $ids
*/
public function destroy($ids): bool
{
$num = $this->model->whereIn('{{options.tree_parent_id}}', $ids)->count();
if ($num > 0) {
throw new ApiException('该分类下存在子分类,请先删除子分类');
} else {
return parent::destroy($ids);
}
}
/**
* 树形数据
*/
public function tree($where)
{
$query = $this->search($where);
$request = request();
if ($request && $request->input('tree', 'false') === 'true') {
{% if stub == 'eloquent' %}
$query->select('{{options.tree_id}}', '{{options.tree_id}} as value', '{{options.tree_name}} as label', '{{options.tree_parent_id}}');
{% else %}
$query->field('{{options.tree_id}}, {{options.tree_id}} as value, {{options.tree_name}} as label, {{options.tree_parent_id}}');
{% endif %}
}
{% if options.relations != null %}
$query->with([
{% for item in options.relations %}
'{{item.name}}',
{% endfor %}
]);
{% endif %}
$data = $this->getAll($query);
return Helper::makeTree($data);
}
{% endif %}
}

View File

@@ -0,0 +1,304 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace {{namespace_start_model}}model{{namespace_end}};
{% if stub == 'eloquent' %}
use plugin\saiadmin\basic\eloquent\BaseModel;
{% else %}
use plugin\saiadmin\basic\think\BaseModel;
{% endif %}
/**
* {{menu_name}}模型
*
* {{table_name}} {{table_comment}}
*
{% for column in columns %}
* @property {{column.php_type}} ${{column.column_name}} {{column.column_comment}}
{% endfor %}
*/
class {{class_name}} extends BaseModel
{
/**
* 数据表主键
* @var string
*/
{% if stub == 'eloquent' %}
protected $primaryKey = '{{pk}}';
{% else %}
protected $pk = '{{pk}}';
{% endif %}
/**
* 数据库表名称
* @var string
*/
protected $table = '{{table_name}}';
{% if source != db_source and source != '' %}
/**
* 数据库连接
* @var string
*/
protected $connection = '{{source}}';
{% endif %}
{% if stub == 'eloquent' %}
/**
* 属性转换
*/
protected function casts(): array
{
return array_merge(parent::casts(), [
{% for column in columns %}
{% if column.view_type == 'inputTag' or column.view_type == 'checkbox' %}
'{{column.column_name}}' => 'array',
{% endif %}
{% if column.view_type == 'uploadImage' and column.options.limit > 1 %}
'{{column.column_name}}' => 'array',
{% endif %}
{% if column.view_type == 'imagePicker' and column.options.limit > 1 %}
'{{column.column_name}}' => 'array',
{% endif %}
{% if column.view_type == 'uploadFile' and column.options.limit > 1 %}
'{{column.column_name}}' => 'array',
{% endif %}
{% if column.view_type == 'chunkUpload' and column.options.limit > 1 %}
'{{column.column_name}}' => 'array',
{% endif %}
{% endfor %}
]);
}
{% else %}
{% for column in columns %}
{% if column.view_type == 'inputTag' or column.view_type == 'checkbox' %}
/**
* {{column.column_comment}} 保存数组转换
*/
public function set{{column.column_name | camel}}Attr($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
/**
* {{column.column_comment}} 读取数组转换
*/
public function get{{column.column_name | camel}}Attr($value)
{
return json_decode($value ?? '', true);
}
{% endif %}
{% if column.view_type == 'uploadImage' and column.options.limit > 1 %}
/**
* {{column.column_comment}} 保存数组转换
*/
public function set{{column.column_name | camel}}Attr($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
/**
* {{column.column_comment}} 读取数组转换
*/
public function get{{column.column_name | camel}}Attr($value)
{
return json_decode($value ?? '', true);
}
{% endif %}
{% if column.view_type == 'imagePicker' and column.options.limit > 1 %}
/**
* {{column.column_comment}} 保存数组转换
*/
public function set{{column.column_name | camel}}Attr($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
/**
* {{column.column_comment}} 读取数组转换
*/
public function get{{column.column_name | camel}}Attr($value)
{
return json_decode($value ?? '', true);
}
{% endif %}
{% if column.view_type == 'uploadFile' and column.options.limit > 1 %}
/**
* {{column.column_comment}} 保存数组转换
*/
public function set{{column.column_name | camel}}Attr($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
/**
* {{column.column_comment}} 读取数组转换
*/
public function get{{column.column_name | camel}}Attr($value)
{
return json_decode($value ?? '', true);
}
{% endif %}
{% if column.view_type == 'chunkUpload' and column.options.limit > 1 %}
/**
* {{column.column_comment}} 保存数组转换
*/
public function set{{column.column_name | camel}}Attr($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
/**
* {{column.column_comment}} 读取数组转换
*/
public function get{{column.column_name | camel}}Attr($value)
{
return json_decode($value ?? '', true);
}
{% endif %}
{% endfor %}
{% endif %}
{% for column in columns %}
{% if column.is_query == 2 and column.query_type == 'neq' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->where('{{column.column_name}}', '<>', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'gt' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->where('{{column.column_name}}', '>', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'gte' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->where('{{column.column_name}}', '>=', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'lt' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->where('{{column.column_name}}', '<', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'lte' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->where('{{column.column_name}}', '<=', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'like' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->where('{{column.column_name}}', 'like', '%'.$value.'%');
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'in' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->whereIn('{{column.column_name}}', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'notin' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->whereNotIn('{{column.column_name}}', $value);
}
{% endif %}
{% if column.is_query == 2 and column.query_type == 'between' %}
/**
* {{column.column_comment}} 搜索
*/
public function search{{column.column_name | camel}}Attr($query, $value)
{
$query->whereBetween('{{column.column_name}}', $value);
}
{% endif %}
{% endfor %}
{% for item in options.relations %}
{% if item.type == 'belongsTo' %}
/**
* 关联模型 {{item.name}}
*/
public function {{item.name}}()
{
return $this->{{item.type}}({{item.model}}::class, '{{item.localKey}}', '{{item.foreignKey}}');
}
{% endif %}
{% if item.type == 'hasOne' or item.type == 'hasMany' %}
/**
* 关联模型 {{item.name}}
*/
public function {{item.name}}()
{
return $this->{{item.type}}({{item.model}}::class, '{{item.localKey}}', '{{item.foreignKey}}');
}
{% endif %}
{% if item.type == 'belongsToMany' and stub == 'think' %}
/**
* 关联模型 {{item.name}}
*/
public function {{item.name}}()
{
return $this->{{item.type}}({{item.model}}::class, {{item.table}}::class, '{{item.localKey}}', '{{item.foreignKey}}');
}
{% endif %}
{% if item.type == 'belongsToMany' and stub == 'eloquent' %}
/**
* 关联模型 {{item.name}}
*/
public function {{item.name}}()
{
return $this->{{item.type}}({{item.model}}::class, {{item.table}}::class, '{{item.foreignKey}}', '{{item.localKey}}');
}
{% endif %}
{% endfor %}
}

View File

@@ -0,0 +1,58 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace {{namespace_start}}validate{{namespace_end}};
use plugin\saiadmin\basic\BaseValidate;
/**
* {{menu_name}}验证器
*/
class {{class_name}}Validate extends BaseValidate
{
/**
* 定义验证规则
*/
protected $rule = [
{% for column in columns %}
{% if column.is_required == 2 and column.is_pk != 2 %}
'{{column.column_name}}' => 'require',
{% endif %}
{% endfor %}
];
/**
* 定义错误信息
*/
protected $message = [
{% for column in columns %}
{% if column.is_required == 2 and column.is_pk != 2 %}
'{{column.column_name}}' => '{{column.column_comment}}必须填写',
{% endif %}
{% endfor %}
];
/**
* 定义场景
*/
protected $scene = [
'save' => [
{% for column in columns %}
{% if column.is_required == 2 and column.is_pk != 2 %}
'{{column.column_name}}',
{% endif %}
{% endfor %}
],
'update' => [
{% for column in columns %}
{% if column.is_required == 2 and column.is_pk != 2 %}
'{{column.column_name}}',
{% endif %}
{% endfor %}
],
];
}

View File

@@ -0,0 +1,14 @@
-- 数据库语句--
{% for column in tables %}
-- 菜单[{{column.menu_name}}] SQL
INSERT INTO `sa_system_menu`(`parent_id`, `name`, `code`, `slug`, `type`, `path`, `component`, `icon`, `sort`, `is_iframe`, `is_keep_alive`, `is_hidden`, `is_fixed_tab`, `is_full_page`, `create_time`, `update_time`) VALUES ({{column.belong_menu_id}}, '{{column.menu_name}}', '{{column.namespace}}/{{column.package_name}}/{{column.business_name}}', '', 2, '{{column.package_name}}/{{column.business_name}}', '/plugin/{{column.namespace}}/{{column.package_name}}/{{column.business_name}}/index', 'ri:home-2-line', 100, 2, 2, 2, 2, 2, now(), now());
SET @id := LAST_INSERT_ID();
INSERT INTO `sa_system_menu`(`parent_id`, `name`, `slug`, `type`, `sort`, `is_iframe`, `is_keep_alive`, `is_hidden`, `is_fixed_tab`, `is_full_page`, `create_time`, `update_time`) VALUES (@id, '列表', '{{column.namespace}}:{{column.package_name}}:{{column.business_name}}:index', 3, 100, 2, 2, 2, 2, 2, now(), now());
INSERT INTO `sa_system_menu`(`parent_id`, `name`, `slug`, `type`, `sort`, `is_iframe`, `is_keep_alive`, `is_hidden`, `is_fixed_tab`, `is_full_page`, `create_time`, `update_time`) VALUES (@id, '保存', '{{column.namespace}}:{{column.package_name}}:{{column.business_name}}:save', 3, 100, 2, 2, 2, 2, 2, now(), now());
INSERT INTO `sa_system_menu`(`parent_id`, `name`, `slug`, `type`, `sort`, `is_iframe`, `is_keep_alive`, `is_hidden`, `is_fixed_tab`, `is_full_page`, `create_time`, `update_time`) VALUES (@id, '更新', '{{column.namespace}}:{{column.package_name}}:{{column.business_name}}:update', 3, 100, 2, 2, 2, 2, 2, now(), now());
INSERT INTO `sa_system_menu`(`parent_id`, `name`, `slug`, `type`, `sort`, `is_iframe`, `is_keep_alive`, `is_hidden`, `is_fixed_tab`, `is_full_page`, `create_time`, `update_time`) VALUES (@id, '读取', '{{column.namespace}}:{{column.package_name}}:{{column.business_name}}:read', 3, 100, 2, 2, 2, 2, 2, now(), now());
INSERT INTO `sa_system_menu`(`parent_id`, `name`, `slug`, `type`, `sort`, `is_iframe`, `is_keep_alive`, `is_hidden`, `is_fixed_tab`, `is_full_page`, `create_time`, `update_time`) VALUES (@id, '删除', '{{column.namespace}}:{{column.package_name}}:{{column.business_name}}:destroy', 3, 100, 2, 2, 2, 2, 2, now(), now());
{% endfor %}

View File

@@ -0,0 +1,69 @@
import request from '@/utils/http'
/**
* {{menu_name}} API接口
*/
export default {
/**
* 获取数据列表
* @param params 搜索参数
* @returns 数据列表
*/
list(params: Record<string, any>) {
{% if tpl_category == 'tree' %}
return request.get<Api.Common.ApiData[]>({
{% else %}
return request.get<Api.Common.ApiPage>({
{% endif %}
url: '/{{url_path}}/index',
params
})
},
/**
* 读取数据
* @param id 数据ID
* @returns 数据详情
*/
read(id: number | string) {
return request.get<Api.Common.ApiData>({
url: '/{{url_path}}/read?id=' + id
})
},
/**
* 创建数据
* @param params 数据参数
* @returns 执行结果
*/
save(params: Record<string, any>) {
return request.post<any>({
url: '/{{url_path}}/save',
data: params
})
},
/**
* 更新数据
* @param params 数据参数
* @returns 执行结果
*/
update(params: Record<string, any>) {
return request.put<any>({
url: '/{{url_path}}/update',
data: params
})
},
/**
* 删除数据
* @param id 数据ID
* @returns 执行结果
*/
delete(params: Record<string, any>) {
return request.del<any>({
url: '/{{url_path}}/destroy',
data: params
})
}
}

View File

@@ -0,0 +1,318 @@
<template>
{% if component_type == 1 %}
<el-dialog
{% else %}
<el-drawer
{% endif %}
v-model="visible"
:title="dialogType === 'add' ? '新增{{menu_name}}' : '编辑{{menu_name}}'"
{% if is_full == 2 %}
{% if component_type == 1 %}
:fullscreen="true"
{% else %}
size="100%"
{% endif %}
{% else %}
{% if component_type == 1 %}
width="{{form_width}}px"
{% else %}
:size="{{form_width}}"
{% endif %}
{% endif %}
align-center
:close-on-click-modal="false"
@close="handleClose"
>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
{% for column in columns %}
{% if column.is_insert == 2 %}
{% if column.view_type == 'input' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-input v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'password' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-input v-model="formData.{{column.column_name}}" type="password" placeholder="请输入{{column.column_comment}}" show-password />
</el-form-item>
{% endif %}
{% if column.view_type == 'textarea' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-input v-model="formData.{{column.column_name}}" type="textarea" :rows="2" placeholder="请输入{{column.column_comment}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'inputNumber' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-input-number v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'inputTag' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-input-tag v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" clearable />
</el-form-item>
{% endif %}
{% if column.view_type == 'switch' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-switch v-model="formData.{{column.column_name}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'slider' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-slider v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'select' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-select v-model="formData.{{column.column_name}}" :options="[]" placeholder="请选择{{column.column_comment}}" clearable />
</el-form-item>
{% endif %}
{% if column.view_type == 'saSelect' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-select v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" placeholder="请选择{{column.column_comment}}" clearable />
</el-form-item>
{% endif %}
{% if column.view_type == 'treeSelect' and column.column_name == options.tree_parent_id %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-tree-select
v-model="formData.{{column.column_name}}"
:data="optionData.treeData"
placeholder="请选择{{column.column_comment}}"
check-strictly
clearable
/>
</el-form-item>
{% endif %}
{% if column.view_type == 'treeSelect' and column.column_name != options.tree_parent_id %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-tree-select v-model="formData.{{column.column_name}}" :data="[]" placeholder="请选择{{column.column_comment}}" clearable />
</el-form-item>
{% endif %}
{% if column.view_type == 'radio' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-radio v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'checkbox' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-checkbox v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'date' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-date-picker v-model="formData.{{column.column_name}}" type="{{column.options.mode}}" placeholder="请选择{{column.column_comment}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'time' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-time-picker v-model="formData.{{column.column_name}}" placeholder="请选择{{column.column_comment}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'rate' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-rate v-model="formData.{{column.column_name}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'cascader' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-cascader v-model="formData.{{column.column_name}}" :options="[]" placeholder="请选择{{column.column_comment}}" allow-clear />
</el-form-item>
{% endif %}
{% if column.view_type == 'userSelect' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-user v-model="formData.{{column.column_name}}" :multiple="{{column.options.multiple|bool}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'uploadImage' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-image-upload v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'imagePicker' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-image-picker v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'uploadFile' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-file-upload v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'chunkUpload' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-chunk-upload v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
</el-form-item>
{% endif %}
{% if column.view_type == 'editor' %}
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-editor v-model="formData.{{column.column_name}}" height="{{column.options.height}}px" />
</el-form-item>
{% endif %}
{% endif %}
{% endfor %}
</el-form>
<template #footer>
<el-button @click="handleClose">取消</el-button>
<el-button type="primary" @click="handleSubmit">提交</el-button>
</template>
{% if component_type == 1 %}
</el-dialog>
{% else %}
</el-drawer>
{% endif %}
</template>
<script setup lang="ts">
import api from '../../../api/{{package_name}}/{{business_name}}'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
interface Props {
modelValue: boolean
dialogType: string
data?: Record<string, any>
}
interface Emits {
(e: 'update:modelValue', value: boolean): void
(e: 'success'): void
}
const props = withDefaults(defineProps<Props>(), {
modelValue: false,
dialogType: 'add',
data: undefined
})
const emit = defineEmits<Emits>()
const formRef = ref<FormInstance>()
{% if tpl_category == 'tree' %}
const optionData = reactive({
treeData: <any[]>[]
})
{% endif %}
/**
* 弹窗显示状态双向绑定
*/
const visible = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value)
})
/**
* 表单验证规则
*/
const rules = reactive<FormRules>({
{% for column in columns %}
{% if column.is_required == 2 and column.is_pk == 1 %}
{{column.column_name}}: [{ required: true, message: '{{column.column_comment}}必需填写', trigger: 'blur' }],
{% endif %}
{% endfor %}
})
/**
* 初始数据
*/
const initialFormData = {
{% for column in columns %}
{% if column.is_pk == 2 %}
{{column.column_name}}: null,
{% elseif column.is_insert == 2 %}
{% if column.column_type == 'int' or column.column_type == 'smallint' or column.column_type == 'tinyint' %}
{{column.column_name}}: {{column.default_value | parseNumber}},
{% elseif column.view_type == 'inputTag' or column.view_type == 'checkbox' or column.options.limit > 1 %}
{{column.column_name}}: [],
{% elseif column.view_type == 'userSelect' %}
{{column.column_name}}: null,
{% else %}
{{column.column_name}}: '{{column.default_value}}',
{% endif %}
{% endif %}
{% endfor %}
}
/**
* 表单数据
*/
const formData = reactive({ ...initialFormData })
/**
* 监听弹窗打开,初始化表单数据
*/
watch(
() => props.modelValue,
(newVal) => {
if (newVal) {
initPage()
}
}
)
/**
* 初始化页面数据
*/
const initPage = async () => {
// 先重置为初始值
Object.assign(formData, initialFormData)
{% if tpl_category == 'tree' %}
// 初始化树形数据
const data = await api.list({ tree: true })
optionData.treeData = [
{
id: 0,
value: 0,
label: '无上级分类',
children: data
}
]
{% endif %}
// 如果有数据,则填充数据
if (props.data) {
await nextTick()
initForm()
}
}
/**
* 初始化表单数据
*/
const initForm = () => {
if (props.data) {
for (const key in formData) {
if (props.data[key] != null && props.data[key] != undefined) {
;(formData as any)[key] = props.data[key]
}
}
}
}
/**
* 关闭弹窗并重置表单
*/
const handleClose = () => {
visible.value = false
formRef.value?.resetFields()
}
/**
* 提交表单
*/
const handleSubmit = async () => {
if (!formRef.value) return
try {
await formRef.value.validate()
if (props.dialogType === 'add') {
await api.save(formData)
ElMessage.success('新增成功')
} else {
await api.update(formData)
ElMessage.success('修改成功')
}
emit('success')
handleClose()
} catch (error) {
console.log('表单验证失败:', error)
}
}
</script>

View File

@@ -0,0 +1,189 @@
<template>
<div class="art-full-height">
<!-- 搜索面板 -->
<TableSearch v-model="searchForm" @search="handleSearch" @reset="resetSearchParams" />
<ElCard class="art-table-card" shadow="never">
<!-- 表格头部 -->
<ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
<template #left>
<ElSpace wrap>
<ElButton v-permission="'{{namespace}}:{{package_name}}:{{business_name}}:save'" @click="showDialog('add')" v-ripple>
<template #icon>
<ArtSvgIcon icon="ri:add-fill" />
</template>
新增
</ElButton>
<ElButton
v-permission="'{{namespace}}:{{package_name}}:{{business_name}}:destroy'"
:disabled="selectedRows.length === 0"
@click="deleteSelectedRows(api.delete, refreshData)"
v-ripple
>
<template #icon>
<ArtSvgIcon icon="ri:delete-bin-5-line" />
</template>
删除
</ElButton>
{% if tpl_category == 'tree' %}
<ElButton @click="toggleExpand" v-ripple>
<template #icon>
<ArtSvgIcon v-if="isExpanded" icon="ri:collapse-diagonal-line" />
<ArtSvgIcon v-else icon="ri:expand-diagonal-line" />
</template>
{{ isExpanded ? '收起' : '展开' }}
</ElButton>
{% endif %}
</ElSpace>
</template>
</ArtTableHeader>
<!-- 表格 -->
<ArtTable
ref="tableRef"
rowKey="id"
:loading="loading"
:data="data"
:columns="columns"
:pagination="pagination"
@sort-change="handleSortChange"
@selection-change="handleSelectionChange"
@pagination:size-change="handleSizeChange"
@pagination:current-change="handleCurrentChange"
>
<!-- 操作列 -->
<template #operation="{ row }">
<div class="flex gap-2">
<SaButton
v-permission="'{{namespace}}:{{package_name}}:{{business_name}}:update'"
type="secondary"
@click="showDialog('edit', row)"
/>
<SaButton
v-permission="'{{namespace}}:{{package_name}}:{{business_name}}:destroy'"
type="error"
@click="deleteRow(row, api.delete, refreshData)"
/>
</div>
</template>
</ArtTable>
</ElCard>
<!-- 编辑弹窗 -->
<EditDialog
v-model="dialogVisible"
:dialog-type="dialogType"
:data="dialogData"
@success="refreshData"
/>
</div>
</template>
<script setup lang="ts">
import { useTable } from '@/hooks/core/useTable'
import { useSaiAdmin } from '@/composables/useSaiAdmin'
import api from '../../api/{{package_name}}/{{business_name}}'
import TableSearch from './modules/table-search.vue'
import EditDialog from './modules/edit-dialog.vue'
{% if tpl_category == 'tree' %}
// 状态管理
const isExpanded = ref(false)
const tableRef = ref()
{% endif %}
// 搜索表单
const searchForm = ref({
{% for column in columns %}
{% if column.is_query == 2 and column.query_type != 'between' %}
{{column.column_name}}: undefined,
{% endif %}
{% if column.is_query == 2 and column.query_type == 'between' %}
{{column.column_name}}: [],
{% endif %}
{% endfor %}
})
// 搜索处理
const handleSearch = (params: Record<string, any>) => {
Object.assign(searchParams, params)
getData()
}
// 表格配置
const {
columns,
columnChecks,
data,
loading,
getData,
searchParams,
pagination,
resetSearchParams,
handleSortChange,
handleSizeChange,
handleCurrentChange,
refreshData
} = useTable({
core: {
apiFn: api.list,
columnsFactory: () => [
{ type: 'selection' },
{% for column in columns %}
{% if column.is_list == 2 %}
{% if column.view_type == 'uploadImage' or column.view_type == 'imagePicker' %}
{ prop: '{{column.column_name}}', label: '{{column.column_comment}}', saiType: 'image' },
{% else %}
{% if column.is_sort == 2 %}
{% if column.view_type == 'saSelect' or column.view_type == 'radio' %}
{ prop: '{{column.column_name}}', label: '{{column.column_comment}}', saiType: 'dict', saiDict: '{{column.dict_type}}', sortable: true },
{% else %}
{ prop: '{{column.column_name}}', label: '{{column.column_comment}}', sortable: true },
{% endif %}
{% else %}
{% if column.view_type == 'saSelect' or column.view_type == 'radio' %}
{ prop: '{{column.column_name}}', label: '{{column.column_comment}}', saiType: 'dict', saiDict: '{{column.dict_type}}' },
{% else %}
{ prop: '{{column.column_name}}', label: '{{column.column_comment}}' },
{% endif %}
{% endif %}
{% endif %}
{% endif %}
{% endfor %}
{ prop: 'operation', label: '操作', width: 100, fixed: 'right', useSlot: true }
]
}
})
// 编辑配置
const {
dialogType,
dialogVisible,
dialogData,
showDialog,
deleteRow,
deleteSelectedRows,
handleSelectionChange,
selectedRows
} = useSaiAdmin()
{% if tpl_category == 'tree' %}
// 切换展开/收起所有菜单
const toggleExpand = (): void => {
isExpanded.value = !isExpanded.value
nextTick(() => {
if (tableRef.value?.elTableRef && data.value) {
const processRows = (rows: any[]) => {
rows.forEach((row) => {
if (row.children?.length) {
tableRef.value.elTableRef.toggleRowExpansion(row, isExpanded.value)
processRows(row.children)
}
})
}
processRows(data.value)
}
})
}
{% endif %}
</script>

View File

@@ -0,0 +1,115 @@
<template>
<sa-search-bar
ref="searchBarRef"
v-model="formData"
label-width="100px"
:showExpand="false"
@reset="handleReset"
@search="handleSearch"
@expand="handleExpand"
>
{% for column in columns %}
{% if column.is_query == 2 %}
{% if column.view_type == 'select' %}
<el-col v-bind="setSpan(6)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-select v-model="formData.{{column.column_name}}" :options="[]" placeholder="请选择{{column.column_comment}}" clearable />
</el-form-item>
</el-col>
{% endif %}
{% if column.view_type == 'saSelect' or column.view_type == 'radio' %}
<el-col v-bind="setSpan(6)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<sa-select v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" placeholder="请选择{{column.column_comment}}" clearable />
</el-form-item>
</el-col>
{% endif %}
{% if column.view_type == 'cascader' %}
<el-col v-bind="setSpan(6)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-cascader v-model="formData.{{column.column_name}}" :options="[]" placeholder="请选择{{column.column_comment}}" clearable />
</el-form-item>
</el-col>
{% endif %}
{% if column.view_type == 'date' and column.options.mode == 'date' and column.query_type == 'between' %}
<el-col v-bind="setSpan(6)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-date-picker v-model="formData.{{column.column_name}}" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" clearable />
</el-form-item>
</el-col>
{% endif %}
{% if column.view_type == 'date' and column.options.mode == 'datetime' and column.query_type == 'between' %}
<el-col v-bind="setSpan(12)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-date-picker v-model="formData.{{column.column_name}}" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" clearable />
</el-form-item>
</el-col>
{% endif %}
{% if column.view_type == 'date' and column.query_type != 'between' %}
<el-col v-bind="setSpan(6)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-date-picker v-model="formData.{{column.column_name}}" type="{{column.options.mode}}" placeholder="请选择{{column.column_comment}}" value-format="YYYY-MM-DD HH:mm:ss" clearable />
</el-form-item>
</el-col>
{% endif %}
{% if column.view_type != 'select' and column.view_type != 'radio' and column.view_type != 'saSelect' and column.view_type != 'cascader' and column.view_type != 'date' %}
<el-col v-bind="setSpan(6)">
<el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
<el-input v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" clearable />
</el-form-item>
</el-col>
{% endif %}
{% endif %}
{% endfor %}
</sa-search-bar>
</template>
<script setup lang="ts">
interface Props {
modelValue: Record<string, any>
}
interface Emits {
(e: 'update:modelValue', value: Record<string, any>): void
(e: 'search', params: Record<string, any>): void
(e: 'reset'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
// 展开/收起
const isExpanded = ref<boolean>(false)
// 表单数据双向绑定
const searchBarRef = ref()
const formData = computed({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val)
})
// 重置
function handleReset() {
searchBarRef.value?.ref.resetFields()
emit('reset')
}
// 搜索
async function handleSearch() {
emit('search', formData.value)
}
// 展开/收起
function handleExpand(expanded: boolean) {
isExpanded.value = expanded
}
// 栅格占据的列数
const setSpan = (span: number) => {
return {
span: span,
xs: 24, // 手机:满宽显示
sm: span >= 12 ? span : 12, // 平板大于等于12保持否则用半宽
md: span >= 8 ? span : 8, // 中等屏幕大于等于8保持否则用三分之一宽
lg: span,
xl: span
}
}
</script>