初始化-安装依赖

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,204 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\utils;
/**
* Array操作类
* Class Arr
*/
class Arr
{
/**
* 获取数组中指定的列
* @param array $source
* @param string $column
* @return array
*/
public static function getArrayColumn($source, $column): array
{
$columnArr = [];
foreach ($source as $item) {
$columnArr[] = $item[$column];
}
return $columnArr;
}
/**
* 批量获取数组中指定的列
* @param array $source
* @param array $column
* @return array
*/
public static function getArrayColumns($source, $columns): array
{
$columnArr = [];
foreach ($source as $item) {
$tempArr = [];
foreach ($columns as $key) {
$temp = explode('.', $key);
if (count($temp) > 1) {
$tempArr[$key] = $item[$temp[0]][$temp[1]];
} else {
$tempArr[$key] = $item[$key];
}
}
$columnArr[] = $tempArr;
}
return $columnArr;
}
/**
* 把二维数组中某列设置为key返回
* @param array $array 输入数组
* @param string $field 要作为键的字段名
* @param bool $unique 要做键的字段是否唯一(该字段与记录是否一一对应)
* @return array
*/
public static function fieldAsKey($array, $field, $unique = false) {
$result = [];
foreach ($array as $item) {
if (isset($item[$field])) {
if (!$unique && isset($result[$item[$field]])) {
$unique = true;
$result[$item[$field]] = [($result[$item[$field]])];
$result[$item[$field]][] = $item;
} elseif ($unique) {
$result[$item[$field]][] = $item;
} else {
$result[$item[$field]] = $item;
}
}
}
return $result;
}
/**
* 数组转字符串去重复
* @param array $data
* @return false|string[]
*/
public static function unique(array $data)
{
return array_unique(explode(',', implode(',', $data)));
}
/**
* 获取数组中去重复过后的指定key值
* @param array $list
* @param string $key
* @return array
*/
public static function getUniqueKey(array $list, string $key)
{
return array_unique(array_column($list, $key));
}
/**
* 合并二维数组并且指定key去重, 第一个覆盖第二个
* @param array $arr1
* @param array $arr2
* @param string $key
* @return array
*/
public static function mergeArray(array $arr1, array $arr2, string $key)
{
$arr = array_merge($arr1,$arr2);
$tmp_arr = [];
foreach($arr as $k => $v) {
if(in_array($v[$key], $tmp_arr)) {
unset($arr[$k]);
} else {
$tmp_arr[] = $v[$key];
}
}
return $arr;
}
/**
* 相同键值的合并作为键生成新数组
* @param array $data
* @param string $field
* @return array
*/
public static function groupSameField(array $data, string $field)
{
$result= [];
foreach ($data as $key => $info) {
$result[$info[$field]][] = $info;
}
return $result;
}
/**
* 生成无限级树算法
* @param array $arr 输入数组
* @param number $pid 根级的pid
* @param string $column_name 列名,id|pid父id的名字|children子数组的键名
* @return array $ret
*/
public static function makeTree($arr, $pid = 0, $column_name = 'id|pid|children') {
list($idname, $pidname, $cldname) = explode('|', $column_name);
$ret = array();
foreach ($arr as $k => $v) {
if ($v [$pidname] == $pid) {
$tmp = $arr [$k];
unset($arr [$k]);
$tmp [$cldname] = self::makeTree($arr, $v [$idname], $column_name);
$ret [] = $tmp;
}
}
return $ret;
}
/**
* 二位数组按某个键值排序
* @param array $arr
* @param string $key
* @param int $sort
* @return array
*/
public static function sortArray($arr, $key, $sort = SORT_ASC)
{
array_multisort(array_column($arr,$key),$sort,$arr);
return $arr;
}
/**
* 数组中根据某一列中某个字段的值来查询这一列数据
* @param $array
* @param $column
* @param $value
* @return array
*/
public static function getArrayByColumn($array, $column, $value): array
{
$result = [];
foreach ($array as $key => $item) {
if ($item[$column] == $value) {
$result = $item;
}
}
return $result;
}
/**
* 数组中根据key值获取value
* @param $array
* @param $key
* @return mixed|string
*/
public static function getConfigValue($array, $key)
{
foreach ($array as $item) {
if ($item['key'] === $key) {
return $item['value'];
}
}
return '';
}
}

View File

@@ -0,0 +1,121 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\utils;
use support\think\Cache;
use Ramsey\Uuid\Uuid;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;
use plugin\saiadmin\exception\ApiException;
/**
* 验证码工具类
*/
class Captcha
{
/**
* 图形验证码
* @return array
*/
public static function imageCaptcha(): array
{
$builder = new PhraseBuilder(4, 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ');
$captcha = new CaptchaBuilder(null, $builder);
$captcha->setBackgroundColor(242, 243, 245);
$captcha->build(120, 36);
$uuid = Uuid::uuid4();
$key = $uuid->toString();
$mode = config('plugin.saiadmin.saithink.captcha.mode', 'session');
$expire = config('plugin.saiadmin.saithink.captcha.expire', 300);
$code = strtolower($captcha->getPhrase());
if ($mode === 'cache') {
try {
Cache::set($key, $code, $expire);
} catch (\Exception $e) {
return [
'result' => -1,
'message' => '验证码获取失败,请检查缓存配置'
];
}
} else {
$request = request();
if ($request) {
$request->session()->set($key, $code);
}
}
$img_content = $captcha->get();
return [
'result' => 1,
'uuid' => $key,
'image' => 'data:image/png;base64,' . base64_encode($img_content)
];
}
/**
* 数字验证码
* @param string $key
* @param int $length
* @return array
*/
public static function numberCaptcha(string $key, int $length = 4): array
{
$code = str_pad(rand(0, 999999), $length, '0', STR_PAD_LEFT);
$mode = config('plugin.saiadmin.saithink.captcha.mode', 'session');
$expire = config('plugin.saiadmin.saithink.captcha.expire', 300);
if ($mode === 'cache') {
try {
Cache::set($key, $code, $expire);
} catch (\Exception $e) {
return [
'result' => -1,
'message' => '验证码获取失败,请检查缓存配置'
];
}
} else {
$request = request();
if ($request) {
$request->session()->set($key, $code);
}
}
return [
'result' => 1,
'uuid' => $key,
'code' => $code,
];
}
/**
* 验证码验证
* @param string $uuid
* @param string|int $captcha
* @return bool
*/
public static function checkCaptcha(string $uuid, string|int $captcha): bool
{
$mode = config('plugin.saiadmin.saithink.captcha.mode', 'session');
if ($mode === 'cache') {
try {
$code = Cache::get($uuid);
Cache::delete($uuid);
} catch (\Exception $e) {
throw new ApiException($e->getMessage());
}
} else {
try {
$code = session($uuid);
session()->forget($uuid);
} catch (\Exception $e) {
throw new ApiException($e->getMessage());
}
}
if (strtolower($captcha) !== $code) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,254 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\utils;
/**
* 帮助类
*/
class Helper
{
/**
* 数据树形化
* @param array $data 数据
* @param string $childrenname 子数据名
* @param string $keyName 数据key名
* @param string $pidName 数据上级key名
* @return array
*/
public static function makeTree(array $data, string $childrenname = 'children', string $keyName = 'id', string $pidName = 'parent_id')
{
$list = [];
foreach ($data as $value) {
$list[$value[$keyName]] = $value;
}
$tree = []; //格式化好的树
foreach ($list as $item) {
if (isset($list[$item[$pidName]])) {
$list[$item[$pidName]][$childrenname][] = &$list[$item[$keyName]];
} else {
$tree[] = &$list[$item[$keyName]];
}
}
return $tree;
}
/**
* 生成Arco菜单
* @param array $data 数据
* @param string $childrenname 子数据名
* @param string $keyName 数据key名
* @param string $pidName 数据上级key名
* @return array
*/
public static function makeArcoMenus(array $data, string $childrenname = 'children', string $keyName = 'id', string $pidName = 'parent_id')
{
$list = [];
foreach ($data as $value) {
if ($value['type'] === 'M'){
$path = '/'.$value['route'];
$layout = isset($value['is_layout']) ? $value['is_layout'] : 1;
$temp = [
$keyName => $value[$keyName],
$pidName => $value[$pidName],
'name' => $value['route'],
'path' => $path,
'component' => $value['component'],
'redirect' => $value['redirect'],
'meta' => [
'title' => $value['name'],
'type' => $value['type'],
'hidden' => $value['is_hidden'] === 1,
'layout' => $layout === 1,
'hiddenBreadcrumb' => false,
'icon' => $value['icon'],
],
];
$list[$value[$keyName]] = $temp;
}
if ($value['type'] === 'I' || $value['type'] === 'L'){
$temp = [
$keyName => $value[$keyName],
$pidName => $value[$pidName],
'name' => $value['code'],
'path' => $value['route'],
'meta' => [
'title' => $value['name'],
'type' => $value['type'],
'hidden' => $value['is_hidden'] === 1,
'hiddenBreadcrumb' => false,
'icon' => $value['icon'],
],
];
$list[$value[$keyName]] = $temp;
}
}
$tree = []; //格式化好的树
foreach ($list as $item) {
if (isset($list[$item[$pidName]])) {
$list[$item[$pidName]][$childrenname][] = &$list[$item[$keyName]];
} else {
$tree[] = &$list[$item[$keyName]];
}
}
return $tree;
}
/**
* 生成Artd菜单
* @param array $data
* @param string $childrenname
* @param string $keyName
* @param string $pidName
* @return array
*/
public static function makeArtdMenus(array $data, string $childrenname = 'children', string $keyName = 'id', string $pidName = 'parent_id')
{
$list = [];
foreach ($data as $value) {
$component = '';
if ($value['type'] === 1) {
$component = '/index/index';
}
if ($value['type'] === 2) {
$component = $value['component'];
}
$temp = [
$keyName => $value[$keyName],
$pidName => $value[$pidName],
'name' => $value['code'],
'path' => $value['path'],
'component' => $component,
'meta' => [
'title' => $value['name'],
'icon' => $value['icon'],
'isIframe' => $value['is_iframe'] === 1,
'keepAlive' => $value['is_keep_alive'] === 1,
'isHide' => $value['is_hidden'] === 1,
'fixedTab' => $value['is_fixed_tab'] === 1,
'isFullPage' => $value['is_full_page'] === 1,
],
];
if ($value['type'] === 4) {
$temp['path'] = '/outside/Iframe';
$temp['meta']['link'] = $value['link_url'];
}
$list[$value[$keyName]] = $temp;
}
$tree = [];
foreach ($list as $item) {
if (isset($list[$item[$pidName]])) {
$list[$item[$pidName]][$childrenname][] = &$list[$item[$keyName]];
} else {
$tree[] = &$list[$item[$keyName]];
}
}
return $tree;
}
/**
* 下划线转驼峰
*/
public static function camelize($uncamelized_words,$separator='_')
{
$uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}
/**
* 驼峰命名转下划线命名
*/
public static function uncamelize($camelCaps,$separator='_')
{
return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}
/**
* 转换为驼峰
* @param string $value
* @return string
*/
public static function camel(string $value): string
{
static $cache = [];
$key = $value;
if (isset($cache[$key])) {
return $cache[$key];
}
$value = ucwords(str_replace(['-', '_'], ' ', $value));
return $cache[$key] = str_replace(' ', '', $value);
}
/**
* 获取业务名称
* @param string $tableName
* @return mixed
*/
public static function get_business(string $tableName)
{
$start = strrpos($tableName,'_');
if ($start !== false) {
$result = substr($tableName, $start + 1);
} else {
$result = $tableName;
}
return static::camelize($result);
}
/**
* 获取业务名称
* @param string $tableName
* @return mixed
*/
public static function get_big_business(string $tableName)
{
$start = strrpos($tableName,'_');
$result = substr($tableName, $start + 1);
return static::camel($result);
}
/**
* 只替换一次字符串
* @param $needle
* @param $replace
* @param $haystack
* @return array|mixed|string|string[]
*/
public static function str_replace_once($needle, $replace, $haystack)
{
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
/**
* 遍历目录
* @param $template_name
* @return array
*/
public static function get_dir($template_name)
{
$dir = base_path($template_name);
$fileDir = [];
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
array_push($fileDir, $file);
}
}
closedir($dh);
}
}
return $fileDir;
}
}

View File

@@ -0,0 +1,253 @@
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\utils;
/**
* 服务器监控信息
*/
class ServerMonitor
{
/**
* 获取内存信息
* @return array
*/
public function getMemoryInfo(): array
{
$totalMem = 0; // 总内存 (Bytes)
$freeMem = 0; // 可用/剩余内存 (Bytes)
if (stristr(PHP_OS, 'WIN')) {
// Windows 系统
// 一次性获取 总可见内存 和 空闲物理内存 (单位都是 KB)
// TotalVisibleMemorySize: 操作系统可识别的内存总数 (比物理内存条总数略少,更准确反映可用上限)
// FreePhysicalMemory: 当前可用物理内存
$cmd = 'wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /format:csv';
$output = shell_exec($cmd);
$output = mb_convert_encoding($output ?? '', 'UTF-8', 'GBK, UTF-8, ASCII');
$lines = explode("\n", trim($output));
foreach ($lines as $line) {
$line = trim($line);
if (empty($line)) continue;
// CSV 格式: Node,FreePhysicalMemory,TotalVisibleMemorySize
$parts = str_getcsv($line);
// 确保解析正确且排除标题行 (通常索引1是Free, 2是Total)
if (count($parts) >= 3 && is_numeric($parts[1])) {
$freeMem = floatval($parts[1]) * 1024; // KB -> Bytes
$totalMem = floatval($parts[2]) * 1024; // KB -> Bytes
break;
}
}
} else {
// Linux 系统
// 读取 /proc/meminfo效率远高于 shell_exec('cat ...')
$memInfo = @file_get_contents('/proc/meminfo');
if ($memInfo) {
// 使用正则提取 MemTotal 和 MemAvailable (单位 kB)
// MemAvailable 是较新的内核指标,比单纯的 MemFree 更准确(包含可回收的缓存)
if (preg_match('/^MemTotal:\s+(\d+)\s+kB/m', $memInfo, $matches)) {
$totalMem = floatval($matches[1]) * 1024;
}
if (preg_match('/^MemAvailable:\s+(\d+)\s+kB/m', $memInfo, $matches)) {
$freeMem = floatval($matches[1]) * 1024;
} else {
// 如果内核太老没有 MemAvailable退化使用 MemFree
if (preg_match('/^MemFree:\s+(\d+)\s+kB/m', $memInfo, $matches)) {
$freeMem = floatval($matches[1]) * 1024;
}
}
}
}
// 计算已用内存
$usedMem = $totalMem - $freeMem;
// 避免除以0
$rate = ($totalMem > 0) ? ($usedMem / $totalMem) * 100 : 0;
// PHP 自身占用
$phpMem = memory_get_usage(true);
return [
// 人类可读格式 (String)
'total' => $this->formatBytes($totalMem),
'free' => $this->formatBytes($freeMem),
'used' => $this->formatBytes($usedMem),
'php' => $this->formatBytes($phpMem),
'rate' => sprintf('%.2f', $rate) . '%',
// 原始数值 (Float/Int),方便前端图表使用或逻辑判断,统一单位 Bytes
'raw' => [
'total' => $totalMem,
'free' => $freeMem,
'used' => $usedMem,
'php' => $phpMem,
'rate' => round($rate, 2)
]
];
}
/**
* 获取PHP及环境信息
* @return array
*/
public function getPhpAndEnvInfo(): array
{
return [
'php_version' => PHP_VERSION,
'os' => PHP_OS,
'project_path' => BASE_PATH,
'memory_limit' => ini_get('memory_limit'),
'max_execution_time' => ini_get('max_execution_time'),
'error_reporting' => ini_get('error_reporting'),
'display_errors' => ini_get('display_errors'),
'upload_max_filesize' => ini_get('upload_max_filesize'),
'post_max_size' => ini_get('post_max_size'),
'extension_dir' => ini_get('extension_dir'),
'loaded_extensions' => implode(', ', get_loaded_extensions()),
];
}
/**
* 获取磁盘信息
* @return array
*/
public function getDiskInfo(): array
{
$disk = [];
if (stristr(PHP_OS, 'WIN')) {
// Windows 系统
// 使用 CSV 格式输出避免空格解析错误SkipTop=1 跳过空行
// LogicalDisk 包含: Caption(盘符), FreeSpace(剩余字节), Size(总字节)
$cmd = 'wmic logicaldisk get Caption,FreeSpace,Size /format:csv';
$output = shell_exec($cmd);
// 转换编码,防止中文乱码(视服务器环境而定,通常 Windows CMD 输出为 GBK
$output = mb_convert_encoding($output ?? '', 'UTF-8', 'GBK, UTF-8, ASCII');
$lines = explode("\n", trim($output));
foreach ($lines as $line) {
$line = trim($line);
if (empty($line)) continue;
// CSV 格式: Node,Caption,FreeSpace,Size
$parts = str_getcsv($line);
// 确保数据列足够且是一个盘符 (例如 "C:")
// 索引通常是: 1=>Caption, 2=>FreeSpace, 3=>Size (索引0通常是计算机名)
if (count($parts) >= 4 && preg_match('/^[A-Z]:$/', $parts[1])) {
$caption = $parts[1];
$freeSpace = floatval($parts[2]);
$totalSize = floatval($parts[3]);
// 避免除以 0 错误(如光驱未放入光盘时 Size 可能为 0 或 null
if ($totalSize <= 0) continue;
$usedSpace = $totalSize - $freeSpace;
$disk[] = [
'filesystem' => $caption,
'mounted_on' => $caption,
'size' => $this->formatBytes($totalSize),
'available' => $this->formatBytes($freeSpace),
'used' => $this->formatBytes($usedSpace),
'use_percentage' => sprintf('%.2f', ($usedSpace / $totalSize) * 100) . '%',
'raw' => [ // 保留原始数据以便前端或其他逻辑使用
'size' => $totalSize,
'available' => $freeSpace,
'used' => $usedSpace
]
];
}
}
} else {
// Linux 系统
// -P: POSIX 输出格式(强制在一行显示,防止长挂载点换行)
// -T: 显示文件系统类型
// 默认单位是 1K-blocks (1024字节)
$output = shell_exec('df -TP 2>/dev/null');
$lines = explode("\n", trim($output ?? ''));
// 过滤表头
array_shift($lines);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line)) continue;
// 限制分割数量,防止挂载点名称中有空格导致解析错位(虽然 -P 很大程度避免了这个问题,但仍需谨慎)
$parts = preg_split('/\s+/', $line);
// df -TP 输出列: Filesystem(0), Type(1), 1024-blocks(2), Used(3), Available(4), Capacity(5), Mounted on(6)
if (count($parts) >= 7) {
$filesystem = $parts[0];
$type = $parts[1];
$totalKB = floatval($parts[2]); // 单位是 KB
$usedKB = floatval($parts[3]);
$availKB = floatval($parts[4]);
$mountedOn = $parts[6];
// 过滤逻辑:只显示物理硬盘或特定挂载点
// 通常过滤掉 tmpfs, devtmpfs, overlay, squashfs(snap) 等
// 如果你只想看 /dev/ 开头的物理盘,保留原来的正则即可
if (!preg_match('/^\/dev\//', $filesystem)) {
// continue; // 根据需求决定是否取消注释此行
}
// 过滤掉 Docker overlay 或 kubelet 等产生的繁杂挂载
if (strpos($filesystem, 'overlay') !== false) continue;
// 转换为字节
$totalSize = $totalKB * 1024;
$usedSize = $usedKB * 1024;
$freeSize = $availKB * 1024;
if ($totalSize <= 0) continue;
$disk[] = [
'filesystem' => $filesystem,
'type' => $type,
'mounted_on' => $mountedOn,
'size' => $this->formatBytes($totalSize),
'available' => $this->formatBytes($freeSize),
'used' => $this->formatBytes($usedSize),
'use_percentage' => sprintf('%.2f', ($usedSize / $totalSize) * 100) . '%',
'raw' => [
'size' => $totalSize,
'available' => $freeSize,
'used' => $usedSize
]
];
}
}
}
return $disk;
}
/**
* 格式化字节为可读格式 (B, KB, MB, GB, TB...)
* @param int|float $bytes 字节数
* @param int $precision 小数点后保留位数
* @return string
*/
private function formatBytes($bytes, int $precision = 2): string
{
if ($bytes <= 0) {
return '0 B';
}
$base = log($bytes, 1024);
$suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
// 确保不会数组越界
$class = min((int)floor($base), count($suffixes) - 1);
return sprintf("%." . $precision . "f", $bytes / pow(1024, $class)) . ' ' . $suffixes[$class];
}
}

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>