diff --git a/app/admin/scheme/TestGoods.php b/app/admin/scheme/TestGoods.php
new file mode 100644
index 0000000..ffbf0fb
--- /dev/null
+++ b/app/admin/scheme/TestGoods.php
@@ -0,0 +1,121 @@
+ 'mall_cate', 'relationBindSelect' => 'title'])]
+ public $cate_id;
+
+ #[Field(type: 'char', length: 20, precision: 20, nullable: false, default: '', comment: '商品名称')]
+ public $title;
+
+ #[Field(type: 'char', length: 255, precision: 255, nullable: false, comment: '商品logo')]
+ #[Component(type: 'image', options: [])]
+ public $logo;
+
+ #[Field(type: 'text', nullable: false, comment: '商品图片')]
+ #[Component(type: 'images', options: [])]
+ public $images;
+
+ #[Field(type: 'text', nullable: false, comment: '商品描述')]
+ #[Component(type: 'editor', options: [])]
+ public $describe;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', comment: '总库存', unsigned: true)]
+ public $total_stock;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', comment: '排序', unsigned: true)]
+ public $sort;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', comment: '状态', unsigned: true)]
+ #[Component(type: 'radio', options: ['正常', '禁用'])]
+ public $status;
+
+ #[Field(length: 100, precision: 100, nullable: false, comment: '合格证')]
+ #[Component(type: 'file', options: [])]
+ public $cert_file;
+
+ #[Field(type: 'text', nullable: false, comment: '检测报告')]
+ #[Component(type: 'files', options: [])]
+ public $verfiy_file;
+
+ #[Field(type: 'char', length: 255, precision: 255, nullable: false, default: '', comment: '备注说明')]
+ public $remark;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', unsigned: true)]
+ public $create_time;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', unsigned: true)]
+ public $update_time;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', unsigned: true)]
+ public $delete_time;
+
+ #[Field(type: 'datetime', nullable: false, comment: '发布日期')]
+ #[Component(type: 'date', options: ['date'])]
+ public $publish_time;
+
+ #[Field(type: 'date', nullable: false, comment: '售卖日期')]
+ #[Component(type: 'date', options: ['datetime'])]
+ public $sale_time;
+
+ #[Field(length: 100, precision: 100, nullable: false, comment: '简介')]
+ #[Component(type: 'textarea', options: [])]
+ public $intro;
+
+ #[Field(type: 'int', length: 11, nullable: false, comment: '秒杀状态', unsigned: true)]
+ #[Component(type: 'select', options: [0 => '未参加', 1 => '已开始', 3 => '已结束'])]
+ public $time_status;
+
+ #[Field(type: 'int', length: 11, nullable: false, default: '0', comment: '是否推荐')]
+ #[Component(type: 'switch', options: ['不推荐', '推荐'])]
+ public $is_recommend;
+
+ #[Field(length: 100, precision: 100, nullable: false, default: '0', comment: '商品类型')]
+ #[Component(type: 'checkbox', options: ['taobao' => '淘宝', 'jd' => '京东'])]
+ public $shop_type;
+
+ #[Field(length: 100, precision: 100, nullable: false, comment: '商品标签')]
+ #[Component(type: 'table', options: ['table' => 'mall_tag', 'type' => 'checkbox', 'valueField' => 'id', 'fieldName' => 'title'])]
+ public $tag;
+
+ #[Field(length: 100, precision: 100, comment: '商品标签(单选)')]
+ #[Component(type: 'table', options: ['table' => 'mall_tag', 'type' => 'radio', 'valueField' => 'id', 'fieldName' => 'title'])]
+ public $tag_backup;
+
+ #[Field(length: 100, precision: 100, nullable: false, comment: '产地')]
+ #[Component(type: 'city', options: ['name-province' => '0', 'code' => '0'])]
+ public $from_area;
+
+ #[Field(length: 100, precision: 100, nullable: false, default: '山东省/临沂市', comment: '仓库')]
+ #[Component(type: 'city', options: ['level' => 'city'])]
+ public $store_city;
+
+ #[Field(length: 100, precision: 100, nullable: false, comment: '商品标签 (输入)')]
+ #[Component(type: 'tag', options: [])]
+ public $tag_input;
+
+ #[Field(length: 100, precision: 100, nullable: false, comment: '唯一id')]
+ public $uid;
+
+ #[Field(type: 'decimal', length: 10, precision: 10, comment: '价格')]
+ public $price;
+
+ #[Field(type: 'text', comment: '详情')]
+ public $detail;
+}
\ No newline at end of file
diff --git a/app/common/command/tools/ua/ToolsUaBuild.php b/app/common/command/tools/ua/ToolsUaBuild.php
new file mode 100644
index 0000000..c1de5b3
--- /dev/null
+++ b/app/common/command/tools/ua/ToolsUaBuild.php
@@ -0,0 +1,9 @@
+setName('tools:ua:build')
+ ->setDescription('构建 ulthon-admin 静态合并文件')
+ ->addOption('config', null, Option::VALUE_OPTIONAL, '配置文件路径', 'public/static/plugs/ulthon-admin/ua.build.json')
+ ->addOption('help', 'h', Option::VALUE_NONE, '显示帮助信息');
+ }
+
+ protected function execute(Input $input, Output $output)
+ {
+ $service = new ToolsUaServiceBase();
+ $configOption = $input->getOption('config');
+ $configPath = $service->getConfigPath($configOption);
+ [$ok, $config] = $service->readConfig($configPath);
+ if (!$ok) {
+ $output->writeln($config);
+ return 1;
+ }
+ if (!isset($config['sources']) || !is_array($config['sources']) || count($config['sources']) === 0) {
+ $output->writeln('配置文件 sources 不能为空');
+ return 1;
+ }
+ if (!isset($config['output']) || !$config['output']) {
+ $output->writeln('配置文件 output 不能为空');
+ return 1;
+ }
+ $baseDir = dirname($configPath);
+ $outputPath = $service->resolvePath($config['output'], $baseDir);
+ $contents = [];
+ foreach ($config['sources'] as $source) {
+ if (!is_string($source) || $source === '') {
+ $output->writeln('sources 中存在无效路径');
+ return 1;
+ }
+ $sourcePath = $service->resolvePath($source, $baseDir);
+ if (!is_file($sourcePath)) {
+ $output->writeln('源文件不存在: ' . $sourcePath);
+ return 1;
+ }
+ $contents[] = file_get_contents($sourcePath);
+ }
+ $final = implode("\n\n", $contents);
+ $outputDir = dirname($outputPath);
+ if (!is_dir($outputDir)) {
+ mkdir($outputDir, 0755, true);
+ }
+ file_put_contents($outputPath, $final);
+ $output->writeln('构建完成: ' . $outputPath);
+ $output->writeln('源文件数量: ' . count($contents));
+ $output->writeln('输出大小: ' . strlen($final));
+ return 0;
+ }
+}
diff --git a/extend/base/common/service/ToolsUaServiceBase.php b/extend/base/common/service/ToolsUaServiceBase.php
new file mode 100644
index 0000000..921420a
--- /dev/null
+++ b/extend/base/common/service/ToolsUaServiceBase.php
@@ -0,0 +1,49 @@
+isAbsolutePath($configPath)) {
+ return $configPath;
+ }
+ $root = App::getRootPath();
+ return rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($configPath, DIRECTORY_SEPARATOR);
+ }
+
+ public function readConfig($configPath)
+ {
+ if (!is_file($configPath)) {
+ return [false, '配置文件不存在: ' . $configPath];
+ }
+ $content = file_get_contents($configPath);
+ $data = json_decode($content, true);
+ if (!$data || !is_array($data)) {
+ return [false, '配置文件JSON格式不正确: ' . $configPath];
+ }
+ return [true, $data];
+ }
+
+ public function resolvePath($path, $baseDir)
+ {
+ if ($this->isAbsolutePath($path)) {
+ return $path;
+ }
+ return rtrim($baseDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR);
+ }
+
+ public function isAbsolutePath($path)
+ {
+ if ($path === '' || $path === null) {
+ return false;
+ }
+ if ($path[0] === '/' || $path[0] === '\\') {
+ return true;
+ }
+ return preg_match('/^[a-zA-Z]:[\\\\\\/]/', $path) === 1;
+ }
+}
diff --git a/extend/think/UlthonAdminService.php b/extend/think/UlthonAdminService.php
index 8a16c49..39b3b9d 100644
--- a/extend/think/UlthonAdminService.php
+++ b/extend/think/UlthonAdminService.php
@@ -9,6 +9,7 @@ use app\common\command\tools\db\ToolsDbExecute;
use app\common\command\tools\db\ToolsDbInfo;
use app\common\command\tools\db\ToolsDbQuery;
use app\common\command\tools\db\ToolsDbTable;
+use app\common\command\tools\ua\ToolsUaBuild;
use app\common\command\Test;
use app\common\event\AdminLoginSuccess\LogEvent;
use app\common\event\AdminLoginType\DemoEvent;
@@ -64,6 +65,7 @@ class UlthonAdminService extends Service
ToolsDbInfo::class,
ToolsDbDesc::class,
ToolsDbCount::class,
+ ToolsUaBuild::class,
]);
// 绑定标识容器
diff --git a/public/static/plugs/ulthon-admin/README.md b/public/static/plugs/ulthon-admin/README.md
new file mode 100644
index 0000000..54d34b5
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/README.md
@@ -0,0 +1,101 @@
+# Ulthon Admin 前端静态构建说明
+
+本目录使用纯 PHP 的 ThinkPHP 命令进行静态合并构建,不依赖前端构建工具。拆分后的模块文件都会“完善 ua 对象”,最终合并为单文件供页面直接引用。
+
+## 设计结构
+
+**目录结构**
+- `src/`:拆分后的源码模块
+- `ua.build.json`:构建清单(sources + output)
+- `ulthon-admin.js`:合并输出文件(运行时引用)
+
+**模块划分**
+- `ulthon-admin.01-core.js`:基础上下文与核心能力(ctx、init、config、url、headers、checkAuth、parame)
+- `ulthon-admin.02-common.js`:请求/消息/公共方法(request、common、msg)
+- `ulthon-admin.03-table.js`:表格能力(admin.table)
+- `ulthon-admin.04-listen.js`:统一监听入口(admin.listen、open、checkMobile)
+- `ulthon-admin.05-api.js`:组件 API 能力(admin.api)
+- `ulthon-admin.06-utils.js`:工具能力(查询、缓存、页面设置、扩展名识别等)
+
+**设计要点**
+- 每个模块都只做“补全 ua 对象”的工作,避免模块间互相覆盖。
+- 使用 `window.__uaCtx` 做跨模块上下文共享,保证拆分后仍能共享变量。
+- 构建顺序严格依赖 `ua.build.json`,以顺序决定覆盖与依赖关系。
+
+## 如何使用
+
+**前端引用**
+- 页面只需要引用合并后的 `ulthon-admin.js`,无需加载 `src/` 内的拆分文件。
+- 全局入口保持不变:`window.ua` / `window.ulAdmin`。
+
+**常见调用**
+- `ua.listen()`:初始化页面常规行为
+- `ua.table.render(...)`:渲染表格
+- `ua.request.post(...)`:通用请求
+- `ua.msg.success(...)`:统一消息
+
+## 如何开发
+
+**新增功能的推荐方式**
+1. 判断属于哪类能力:核心/公共/表格/监听/API/工具
+2. 在对应模块内追加 `admin.xxx = ...` 或 `admin.xxx = { ... }`
+3. 若新增模块,请更新 `ua.build.json` 中的 `sources` 顺序
+4. 执行构建命令生成最新 `ulthon-admin.js`
+
+**新增模块的边界**
+- 只负责“补全 ua 对象”,不引入不必要的全局变量
+- 只引用 `__uaCtx` 中已注册的上下文
+- 避免模块内重复初始化全局配置
+
+**构建命令**
+```bash
+php think tools:ua:build
+```
+
+可通过命令参数指定配置文件路径(默认读取本目录的 `ua.build.json`):
+```bash
+php think tools:ua:build --config public/static/plugs/ulthon-admin/ua.build.json
+```
+
+## 构建清单说明
+
+`ua.build.json` 使用相对路径时,基于配置文件所在目录解析:
+
+```json
+{
+ "output": "ulthon-admin.js",
+ "sources": [
+ "src/ulthon-admin.01-core.js",
+ "src/ulthon-admin.02-common.js",
+ "src/ulthon-admin.03-table.js",
+ "src/ulthon-admin.04-listen.js",
+ "src/ulthon-admin.05-api.js",
+ "src/ulthon-admin.06-utils.js"
+ ]
+}
+```
+
+## 兼容性与约定
+
+- 兼容原有 `ua` 对外 API,保持使用方式不变
+- 不依赖前端打包工具
+- 模块拆分后只影响维护方式,不改变运行结果
+
+## 常见问题
+
+**1. 构建后功能异常**
+- 检查 `ua.build.json` 的顺序是否符合依赖
+- 检查新增模块是否遗漏 `window.ulAdmin = window.ua = admin;`
+
+**2. 新方法不可用**
+- 确认方法定义在 `admin` 上
+- 确认构建文件已更新(重新执行构建)
+
+**3. 引用未更新**
+- 页面只引用 `ulthon-admin.js`,不要引用 `src/` 文件
+
+## 进一步建议
+
+- 若模块继续增大,建议细分 `admin.api` 为 upload/editor/form 等更小模块
+- 对外 API 建议保持稳定,避免破坏老页面
+- 合并构建可纳入发布流程,避免线上文件与源码不一致
diff --git a/public/static/plugs/ulthon-admin/src/ulthon-admin.01-core.js b/public/static/plugs/ulthon-admin/src/ulthon-admin.01-core.js
new file mode 100644
index 0000000..116d3a3
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/src/ulthon-admin.01-core.js
@@ -0,0 +1,147 @@
+(function () {
+
+ var ctx = window.__uaCtx || {};
+
+ window.onInitElemStyle = function () {
+ miniTheme.renderElemStyle();
+
+ $('iframe').each(function (index, iframe) {
+
+ if (typeof iframe.contentWindow.onInitElemStyle == "function") {
+ iframe.contentWindow.onInitElemStyle();
+ }
+ });
+
+ };
+ window.onInitElemStyle();
+
+ const { createEditor, createToolbar } = window.wangEditor;
+
+ var form = layui.form,
+ layer = layui.layer,
+ laydate = layui.laydate,
+ upload = layui.upload,
+ element = layui.element,
+ laytpl = layui.laytpl,
+ util = layui.util;
+
+ layer.config({
+ skin: 'layui-layer-easy'
+ });
+
+ var init = {
+ tableElem: '#currentTable',
+ tableRenderId: 'currentTableRenderId',
+ uploadUrl: 'ajax/upload',
+ uploadExts: '',
+ extGroup: {}
+ };
+
+ var table;
+
+ table = layui.table;
+
+ var extGroup = {
+ // 图片扩展名数组
+ 'image': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'ico', 'webp', 'svg'],
+ // word扩展名数组
+ 'word': ['doc', 'docx'],
+ // excel扩展名数组
+ 'excel': ['xls', 'xlsx'],
+ // ppt扩展名数组
+ 'ppt': ['ppt', 'pptx'],
+ // pdf扩展名数组
+ 'pdf': ['pdf'],
+ // 压缩文件扩展名数组
+ 'zip': ['zip', 'rar', '7z'],
+ // 文本文件扩展名数组
+ 'txt': ['txt'],
+ // 音乐文件扩展名数组
+ 'music': ['mp3', 'wma', 'wav', 'mid', 'm4a'],
+ // 视频文件扩展名数组
+ 'video': ['mp4', 'avi', 'wmv', '3gp', 'flv'],
+ // visio扩展名数组
+ 'visio': ['vsd', 'vsdx'],
+ 'file': []
+ };
+
+ var allExtGroup = [];
+
+ for (const extGroupName in extGroup) {
+ if (Object.hasOwnProperty.call(extGroup, extGroupName)) {
+ const extGroupList = extGroup[extGroupName];
+
+ allExtGroup = allExtGroup.concat(extGroupList);
+
+ }
+ }
+
+ extGroup['office'] = [].concat(extGroup['word'], extGroup['excel'], extGroup['ppt'], extGroup['pdf']);
+ extGroup['media'] = [].concat(extGroup['image'], extGroup['music'], extGroup['video']);
+
+ init.uploadExts += allExtGroup.join('|');
+ init.extGroup = extGroup;
+
+ ctx.createEditor = createEditor;
+ ctx.createToolbar = createToolbar;
+ ctx.layui = {
+ form: form,
+ layer: layer,
+ laydate: laydate,
+ upload: upload,
+ element: element,
+ laytpl: laytpl,
+ util: util,
+ };
+ ctx.init = init;
+ ctx.table = table;
+ ctx.extGroup = extGroup;
+ ctx.lastTableWhere = ctx.lastTableWhere || {};
+ ctx.selectMode = ctx.selectMode;
+ ctx.selectConfirmCallback = ctx.selectConfirmCallback;
+
+ window.__uaCtx = ctx;
+
+ var admin = window.ua || {};
+ admin.init = init;
+ admin.config = {
+ shade: [0.02, '#000'],
+ };
+ admin.url = function (url) {
+
+ var urlPrefixCheck = ['/', 'http://', 'https://'];
+
+ for (const index in urlPrefixCheck) {
+ if (Object.hasOwnProperty.call(urlPrefixCheck, index)) {
+ const prefix = urlPrefixCheck[index];
+ if (url.indexOf(prefix) === 0) {
+ return url;
+ }
+ }
+ }
+
+ return '/' + CONFIG.ADMIN + '/' + url;
+ };
+ admin.headers = function () {
+ return { 'X-CSRF-TOKEN': window.CONFIG.CSRF_TOKEN };
+ };
+
+ admin.checkAuth = function (node, elem) {
+ if (node === '1') {
+ return true;
+ }
+ if (CONFIG.IS_SUPER_ADMIN) {
+ return true;
+ }
+ if ($(elem).attr('data-auth-' + node) === '1') {
+ return true;
+ } else {
+ return false;
+ }
+ };
+ admin.parame = function (param, defaultParam) {
+ return param !== undefined ? param : defaultParam;
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
diff --git a/public/static/plugs/ulthon-admin/src/ulthon-admin.02-common.js b/public/static/plugs/ulthon-admin/src/ulthon-admin.02-common.js
new file mode 100644
index 0000000..0e598fa
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/src/ulthon-admin.02-common.js
@@ -0,0 +1,170 @@
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var layer = ctx.layui.layer;
+
+ admin.request = {
+ post: function (option, ok, no, ex, complete) {
+ return admin.request.ajax('post', option, ok, no, ex, complete);
+ },
+ get: function (option, ok, no, ex, complete) {
+ return admin.request.ajax('get', option, ok, no, ex, complete);
+ },
+ ajax: function (type, option, ok, no, ex, complete) {
+ type = type || 'get';
+ option.url = option.url || '';
+ option.data = option.data || {};
+ option.prefix = option.prefix || false;
+ option.statusName = option.statusName || 'code';
+ option.statusCode = option.statusCode || 0;
+ ok = ok || function (res) { };
+
+ var originalOk = ok;
+ ok = function (res) {
+ originalOk(res);
+ complete()
+ }
+ complete = complete || function () {
+ };
+
+ if (no) {
+ var originalNo = no;
+ no = function (res) {
+ originalNo(res);
+ complete();
+ };
+ } else {
+ no = function (res) {
+ var msg = res.msg == undefined ? '返回数据格式有误' : res.msg;
+ admin.msg.error(msg);
+ complete();
+ return false;
+ };
+ }
+
+ if (ex) {
+ var originalEx = ex;
+ ex = function (res) {
+ originalEx(res);
+ complete();
+ };
+ } else {
+ ex = function (res) {
+ complete();
+ };
+ }
+ if (option.url == '') {
+ admin.msg.error('请求地址不能为空');
+ return false;
+ }
+ if (option.prefix == true) {
+ option.url = admin.url(option.url);
+ }
+ loading.show();
+ $.ajax({
+ url: option.url,
+ type: type,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+ dataType: "json",
+ headers: admin.headers(),
+ data: option.data,
+ timeout: 60000,
+ success: function (res) {
+ loading.hide();
+ if (eval('res.' + option.statusName) == option.statusCode) {
+ return ok(res);
+ } else {
+ return no(res);
+ }
+ },
+ error: function (xhr, textstatus, thrown) {
+ var errorMsg = '';
+ if (xhr.responseJSON.message) {
+ errorMsg = xhr.responseJSON.message;
+ }
+ loading.hide();
+ admin.msg.error('Status:' + xhr.status + ',' + xhr.statusText + ',请稍后再试!
' + errorMsg, function () {
+ ex(this);
+ });
+ return false;
+ },
+ });
+ }
+ };
+ admin.common = {
+ parseNodeStr: function (node) {
+ var array = node.split('/');
+ $.each(array, function (key, val) {
+ if (key === 0) {
+ val = val.split('.');
+ $.each(val, function (i, v) {
+ val[i] = admin.common.humpToLine(v.replace(v[0], v[0].toLowerCase()));
+ });
+ val = val.join(".");
+ array[key] = val;
+ }
+ });
+ node = array.join("/");
+ return node;
+ },
+ lineToHump: function (name) {
+ return name.replace(/\_(\w)/g, function (all, letter) {
+ return letter.toUpperCase();
+ });
+ },
+ humpToLine: function (name) {
+ return name.replace(/([A-Z])/g, "_$1").toLowerCase();
+ },
+ };
+ admin.msg = {
+ // 成功消息
+ success: function (msg, callback) {
+ if (callback === undefined) {
+ callback = function () {
+ };
+ }
+ var index = layer.msg(msg, { icon: 1, shade: admin.config.shade, scrollbar: false, time: 800, shadeClose: true }, callback);
+ return index;
+ },
+ // 失败消息
+ error: function (msg, callback) {
+ if (callback === undefined) {
+ callback = function () {
+ };
+ }
+ var index = layer.msg(msg, { icon: 2, shade: admin.config.shade, scrollbar: false, time: -1, shadeClose: true }, callback);
+ return index;
+ },
+ // 警告消息框
+ alert: function (msg, callback) {
+ var index = layer.alert(msg, { end: callback, scrollbar: false });
+ return index;
+ },
+ // 对话框
+ confirm: function (msg, ok, no) {
+ var index = layer.confirm(msg, { title: '操作确认', btn: ['确认', '取消'] }, function () {
+ typeof ok === 'function' && ok.call(this);
+ }, function () {
+ typeof no === 'function' && no.call(this);
+ });
+ return index;
+ },
+ // 消息提示
+ tips: function (msg, time, callback) {
+ var index = layer.msg(msg, { time: (time || 0.8) * 1000, shade: this.shade, end: callback, shadeClose: true });
+ return index;
+ },
+ // 加载中提示
+ loading: function (msg, callback) {
+ var index = msg ? layer.msg(msg, { icon: 16, scrollbar: false, shade: this.shade, time: 0, end: callback }) : layer.load(2, { time: 0, scrollbar: false, shade: this.shade, end: callback });
+ return index;
+ },
+ // 关闭消息框
+ close: function (index) {
+ return layer.close(index);
+ }
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
diff --git a/public/static/plugs/ulthon-admin/src/ulthon-admin.03-table.js b/public/static/plugs/ulthon-admin/src/ulthon-admin.03-table.js
new file mode 100644
index 0000000..89c1d55
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/src/ulthon-admin.03-table.js
@@ -0,0 +1,1577 @@
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var init = ctx.init;
+ var table = ctx.table;
+ var form = ctx.layui.form;
+ var layer = ctx.layui.layer;
+ var lastTableWhere = ctx.lastTableWhere || {};
+ var selectMode = ctx.selectMode;
+ var selectConfirmCallback = ctx.selectConfirmCallback;
+
+ ctx.lastTableWhere = lastTableWhere;
+
+ admin.table = {
+ render: function (options) {
+ options.init = options.init || init;
+ options.modifyReload = admin.parame(options.modifyReload, true);
+ options.elem = options.elem || options.init.tableElem;
+ options.id = options.id || options.init.tableRenderId;
+ options.scrollPos = options.scrollPos || 'fixed';
+ options.layFilter = options.id + '_LayFilter';
+ options.url = options.url || admin.url(options.init.indexUrl);
+ options.headers = admin.headers();
+ options.page = admin.parame(options.page, true);
+ options.search = admin.parame(options.search, true);
+ options.layout = admin.parame(options.layout, true);
+ options.layoutList = admin.parame(options.layoutList,
+ [
+ 'table',
+ 'card',
+ {
+ name: 'usercard',
+ // 优先级1
+ tplFunction() {
+
+ },
+ // 优先级3
+ tplVue() {
+
+ },
+ // 优先级2
+ tplLay() {
+
+ },
+ // 优先级4
+ tplLayId: '',
+ // 优先级5
+ tplVueId: ''
+ }
+ ]
+ );
+ options.layoutDefault = admin.parame(options.layoutDefault, true);
+ options.skin = options.skin || 'line';
+ options.autoSort = options.autoSort || false;
+ options.limit = options.limit || 15;
+ options.limits = options.limits || [10, 15, 20, 25, 50, 100];
+ options.cols = options.cols || [];
+ options.rowDisableCallback = options.rowDisableCallback || null;
+
+ var defaultToolbar = ['filter', 'print'];
+ if (options.layout === true) {
+ defaultToolbar.push({
+ title: '视图',
+ layEvent: 'TABLE_LAYOUT',
+ icon: 'layui-icon-template-1',
+ extend: 'data-table-id="' + options.id + '"'
+ });
+
+ if (options.layoutDefault === true) {
+ // 自动判断,手机端默认card,电脑端默认table
+ if (admin.checkMobile()) {
+ options.layoutDefault = 'card';
+ } else {
+ options.layoutDefault = 'table';
+ }
+ }
+
+ options.layoutDefault = admin.trySetPageSetting('table-layout-default', options.layoutDefault);
+
+
+ }
+
+ if (options.search) {
+ defaultToolbar.push({
+ title: '搜索',
+ layEvent: 'TABLE_SEARCH',
+ icon: 'layui-icon-search',
+ extend: 'data-table-id="' + options.id + '"'
+ });
+ }
+ if (options.defaultToolbar === undefined) {
+ options.defaultToolbar = defaultToolbar;
+ }
+
+
+ var optionBefore = function () { };
+ if (options.before != undefined) {
+ optionBefore = options.before;
+ }
+ options.before = function (tableIns) {
+ optionBefore(tableIns);
+ };
+
+ var optionDone = function () { };
+ if (options.done != undefined) {
+ optionDone = options.done;
+ }
+ options.done = function (res, curr, count) {
+ optionDone(res, curr, count);
+
+ // 监听表格内的复制组件
+ admin.api.copyText('[lay-id=' + options.id + ']');
+ };
+
+ /**
+ * 为空时认为自己是普通状态,否则是单选、多选、子页面,此时添加等默认行为走弹框而不是新标签页
+ */
+ selectMode = admin.getQueryVariable("select_mode");
+
+ selectConfirmCallback = admin.getQueryVariable('select_confirm_callback', 'onTableDataConfirm');
+
+ ctx.selectMode = selectMode;
+ ctx.selectConfirmCallback = selectConfirmCallback;
+
+ if (selectMode == 'checkbox') {
+ if (options.cols[0][0].type == 'radio') {
+ options.cols[0][0].type = 'checkbox';
+ } else if (options.cols[0][0].type != 'checkbox') {
+ options.cols[0].unshift({
+ type: 'checkbox'
+ });
+ }
+ } else if (selectMode == 'radio') {
+ if (options.cols[0][0].type == 'checkbox') {
+ options.cols[0][0].type = 'radio';
+
+ } else if (options.cols[0][0].type != 'radio') {
+ options.cols[0].unshift({
+ type: 'radio'
+ });
+
+ }
+ } else {
+ if (!admin.isParentIndex()) {
+ selectMode = 'childPage'
+ ctx.selectMode = selectMode;
+ }
+ }
+
+
+ // 判断元素对象是否有嵌套的
+ options.cols = admin.table.formatCols(options.cols, options.init);
+
+ // 初始化表格lay-filter
+ $(options.elem).attr('lay-filter', options.layFilter);
+
+ // 初始化表格搜索
+ if (options.search === true) {
+ options = admin.table.renderSearch(options.cols, options.elem, options.id, options);
+ }
+
+ // 初始化模板切换
+ if (options.layout === true) {
+
+ options = admin.table.renderLayout(options);
+ }
+
+ // 初始化表格左上方工具栏
+ options.toolbar = options.toolbar || ['refresh', 'add', 'delete', 'export'];
+
+ if (selectMode == 'checkbox' || selectMode == 'radio') {
+ options.toolbar.unshift('selectConfirm');
+
+ options.height = 'full-85';
+ }
+
+ if (options.init.formFullScreen == true) {
+ options.init.formFullScreen = 'true';
+ } else {
+ options.init.formFullScreen = 'false';
+ }
+
+ options.toolbar = admin.table.renderToolbar(options.toolbar, options.elem, options.id, options.init);
+
+ // 判断是否有操作列表权限
+ options.cols = admin.table.renderOperat(options.cols, options.elem);
+
+ // 判断是否有操作列表权限
+ options.cols = admin.table.renderTrueHide(options.cols, options);
+
+
+ var parseData = function (res) { return res; };
+
+ if (typeof options.parseData === 'function') {
+ parseData = options.parseData;
+ }
+
+ options.parseData = function (res) {
+
+ // 初始化已经选择的值
+ if (selectMode == 'checkbox' || selectMode == 'radio') {
+ if (typeof options.rowDisableCallback == 'function') {
+ for (let index = 0; index < res.data.length; index++) {
+ const dataItem = res.data[index];
+
+ var rowDisableResult = options.rowDisableCallback(dataItem);
+ if (rowDisableResult === false || rowDisableResult === true) {
+ res.data[index].LAY_DISABLED = rowDisableResult;
+ }
+ }
+ }
+
+ var selectedIds = admin.getQueryVariable('selectedIds', '');
+
+ if (selectedIds.length > 0) {
+ var selectedIdArr = selectedIds.split(',');
+
+ for (let index = 0; index < res.data.length; index++) {
+ const dataItem = res.data[index];
+
+ if (selectedIdArr.indexOf(dataItem.id.toString()) > -1) {
+ res.data[index].LAY_DISABLED = true;
+ }
+ }
+ }
+ }
+
+ res = parseData(res);
+ return res;
+ };
+
+
+ // 初始化表格
+ var newTable = table.render(options);
+
+ // 监听表格搜索开关显示
+ admin.table.listenToolbar(options.layFilter, options.id);
+
+ // 监听表格瓶排序
+ admin.table.listenTableSort(options);
+
+ // 监听表格开关切换
+ admin.table.renderSwitch(options.cols, options.init, options.id, options.modifyReload);
+
+ // 监听表格开关切换
+ admin.table.listenEdit(options.init, options.layFilter, options.id, options.modifyReload);
+
+ // 监听导出事件
+ admin.table.listenExport(options);
+
+ // 监听表格选择器
+ admin.table.listenTableSelectConfirm(options);
+
+ return newTable;
+ },
+ renderToolbar: function (data, elem, tableId, init) {
+ data = data || [];
+ var toolbarHtml = '';
+ $.each(data, function (i, v) {
+ if (v === 'refresh') {
+ toolbarHtml += ' \n';
+ } else if (v === 'add') {
+ if (admin.checkAuth('add', elem)) {
+ if (selectMode) {
+ toolbarHtml += '\n';
+ } else {
+ toolbarHtml += '\n';
+ }
+ }
+ } else if (v === 'delete') {
+ if (admin.checkAuth('delete', elem)) {
+ toolbarHtml += '\n';
+ }
+ } else if (v === 'export') {
+ if (admin.checkAuth('export', elem)) {
+ toolbarHtml += '\n';
+ }
+ } else if (v === 'selectConfirm') {
+ toolbarHtml += '\n';
+ } else if (typeof v === "object") {
+ $.each(v, function (ii, vv) {
+ vv.class = vv.class || '';
+ vv.icon = vv.icon || '';
+ vv.auth = vv.auth || 'add';
+ vv.url = vv.url || '';
+ vv.method = vv.method || 'open';
+ vv.title = vv.title || vv.text;
+ vv.text = vv.text || vv.title;
+ vv.extend = vv.extend || '';
+ vv.checkbox = vv.checkbox || false;
+ if (admin.checkAuth(vv.auth, elem)) {
+ toolbarHtml += admin.table.buildToolbarHtml(vv, tableId);
+ }
+ });
+ }
+ });
+ return '
' + toolbarHtml + '
';
+ },
+ renderSearch: function (cols, elem, tableId, options) {
+ // TODO 只初始化第一个table搜索字段,如果存在多个(绝少数需求),得自己去扩展
+ cols = cols[0] || {};
+ var newCols = [];
+ var formHtml = '';
+ var tabSetting = {};
+ var formatFilter = {},
+ formatOp = {};
+ $.each(cols, function (i, d) {
+ d.field = d.field || false;
+ d.fieldAlias = admin.parame(d.fieldAlias, d.field);
+ d.title = d.title || d.field || '';
+ d.selectList = d.selectList || {};
+ d.search = admin.parame(d.search, true);
+ d.searchTip = d.searchTip || '请输入' + d.title || '';
+ d.searchValue = d.searchValue || undefined;
+ d.searchHide = d.searchHide || '';
+ d.defaultSearchValue = d.defaultSearchValue;
+ d.searchOp = d.searchOp || '%*%';
+ d.timeType = d.timeType || 'datetime';
+
+ d.elemIdName = d.fieldAlias;
+
+ var a = '';
+ var b = '';
+
+ if (typeof d.fieldAlias == 'string') {
+
+ if (d.fieldAlias.indexOf('[') == 0) {
+
+ var fieldPlusArr = d.fieldAlias.replace('[').split(']');
+
+ d.elemIdName = fieldPlusArr.join('-');
+ }
+
+ d.elemIdName = d.elemIdName.replace('.', '-');
+ }
+
+
+ if (d.defaultSearchValue !== undefined) {
+ if (!d.searchValue || d.searchValue.length == 0) {
+ d.searchValue = d.defaultSearchValue;
+ }
+ } else {
+ if (d.field) {
+ d.defaultSearchValue = admin.getQueryVariable(d.field);
+ if (d.defaultSearchValue != undefined) {
+ d.searchValue = d.defaultSearchValue;
+ }
+ }
+ }
+
+ if (d.searchValue !== undefined) {
+
+ if (d.search == 'number_limit') {
+ var paramsArr = d.searchValue.split(',');
+
+ a = paramsArr[0];
+ b = paramsArr[1];
+
+ if (a) {
+ formatFilter['[' + d.field + ']min'] = a;
+ formatOp['[' + d.field + ']min'] = 'min';
+ }
+
+ if (b) {
+ formatFilter['[' + d.field + ']max'] = b;
+ formatOp['[' + d.field + ']max'] = 'max';
+ }
+ } else if (d.search == 'time_limit') {
+ var paramsArr = d.searchValue.split(',');
+
+ a = paramsArr[0];
+ b = paramsArr[1];
+
+ if (a) {
+ formatFilter['[' + d.field + ']min_date'] = a;
+ formatOp['[' + d.field + ']min_date'] = 'min_date';
+ }
+
+ if (b) {
+ formatFilter['[' + d.field + ']max_date'] = b;
+ formatOp['[' + d.field + ']max_date'] = 'max_date';
+ }
+ } else {
+ formatFilter[d.field] = d.searchValue;
+ formatOp[d.field] = d.searchOp;
+ }
+ }
+
+ var formSearchHideClass = '';
+ if (d.searchHide == true) {
+ formSearchHideClass = ' layui-hide';
+ }
+
+ if (d.search == true || d.search == 'text') {
+ formHtml += '\n';
+ } else if (d.search == 'select') {
+ formHtml += '\n';
+ } else if (d.search == 'time_limit') {
+ if (d.timeType == undefined) {
+ d.timeType = 'datetime';
+ }
+ formHtml += '\n';
+ tabSetting[tableId + '_' + d.field + '_min'] = {
+ elem: '#c-' + d.elemIdName + '-min',
+ type: d.timeType,
+ range: false,
+ };
+ tabSetting[tableId + '_' + d.field + '_max'] = {
+ elem: '#c-' + d.elemIdName + '-max',
+ type: d.timeType,
+ range: false,
+ };
+
+ } else if (d.search == 'number_limit') {
+ formHtml += '\n';
+ }
+
+ if (d.search !== false) {
+ newCols.push(d);
+ }
+ });
+ var html = '';
+ html += '\n';
+
+ if ($(elem).prev().hasClass("search-form")) {
+ $(elem).prev().remove();
+ }
+ $(elem).before(html);
+
+ form.render();
+
+ $.each(tabSetting, function (key, val) {
+ laydate.render(val);
+ });
+
+ // 监听表单提交事件
+ form.on('submit(' + tableId + '_filter_form_submit)', function (data) {
+ var dataField = data.field;
+ var formatFilter = {},
+ formatOp = {};
+ $.each(dataField, function (key, val) {
+ if (val !== '') {
+ formatFilter[key] = val;
+
+ var elemId = admin.table.renderSearchFormItemElementId(key);
+
+ var op = $('#c-' + elemId).attr('data-search-op');
+ op = op || '%*%';
+ formatOp[key] = op;
+ }
+ });
+ var where = {
+ filter: JSON.stringify(formatFilter),
+ op: JSON.stringify(formatOp)
+ };
+ lastTableWhere[tableId] = where;
+ table.reloadData(tableId, {
+ page: {
+ curr: 1
+ }
+ , where: where
+ }, 'data');
+ return false;
+ });
+ return options;
+ },
+ renderLayout: function (options) {
+ var tableId = options.id;
+ var layoutList = options.layoutList;
+ var layoutDefault = options.layoutDefault;
+ var layoutElemIdName = '#layout-' + tableId;
+ var layoulElem = null;
+ if (!Array.isArray(layoutList)) {
+ layoutList = ['table', 'card'];
+ }
+ options.layoutList = layoutList;
+
+ var toolbarLayoutElem = $('[lay-table-id="' + tableId + '"]').find('[lay-event="TABLE_LAYOUT"]');
+ if (toolbarLayoutElem.length == 0) {
+ toolbarLayoutElem = $('[lay-filter="' + tableId + '_LayFilter"]').find('[lay-event="TABLE_LAYOUT"]');
+ }
+
+ options.done = function (res, curr, count) {
+ if (options.before) {
+ options.before(options);
+ }
+ var layuiTableElemName = '#layui-table-' + tableId;
+ var layuiTableElem = $(layuiTableElemName);
+
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+ var layoutList = options.layoutList || [];
+
+ if (currentLayout != 'table') {
+ for (let index = 0; index < layoutList.length; index++) {
+ const item = layoutList[index];
+ if (item.name == currentLayout) {
+ currentLayout = item.name;
+ break;
+ }
+ }
+ }
+
+ if (currentLayout != 'table') {
+ layuiTableElem.find('.layui-table-box').hide();
+ }
+
+ if (currentLayout != 'table') {
+ if (!layuiTableElem.find('.layui-table-custom.layui-table-custom-' + currentLayout).length) {
+ layuiTableElem.find('.layui-table-box').before('');
+ }
+ }
+
+ layoutList.forEach((item) => {
+ if (item.name == 'table') {
+ layuiTableElem.find('.layui-table-box').hide();
+ } else {
+ layuiTableElem.find('.layui-table-custom.layui-table-custom-' + item.name).hide();
+ }
+ });
+
+ if (currentLayout == 'table') {
+ layuiTableElem.find('.layui-table-box').show();
+ } else {
+ var className = '.layui-table-custom.layui-table-custom-' + currentLayout;
+ // 如果不存在则创建
+ if (!layuiTableElem.find(className).length) {
+ layuiTableElem.find('.layui-table-box').before('');
+ }
+ layuiTableElem.find(className).show();
+ loading.show();
+ }
+
+ var optionDone = options.done;
+ options.done = function (res, curr, count) {
+ optionDone(res, curr, count);
+ console.log('layout done fun');
+
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+ // 隐藏所有数据体内容
+ var layuiTableElem = $(layuiTableElemName);
+
+ options.layoutList.forEach((item) => {
+ if (currentLayout == 'table') {
+ // 如果是table,则不用生成数据,显示出来就行,before已经显示过了
+ return;
+ }
+
+ if (currentLayout != item.name) {
+ // 如果不是,则不进行任何操作
+ return;
+ }
+
+ var className = '.layui-table-custom.layui-table-custom-' + item.name;
+
+ // 清空里面的数据
+ layuiTableElem.find(className).html('');
+ loading.hide();
+
+ item.tplFunction(options, res, layuiTableElem.find(className));
+
+
+
+
+ });
+
+ };
+
+ return options;
+
+ };
+
+ return options;
+ },
+
+ renderSwitch: function (cols, tableInit, tableId, modifyReload) {
+ tableInit.modifyUrl = tableInit.modifyUrl || false;
+ cols = cols[0] || {};
+ tableId = tableId || init.tableRenderId;
+ if (cols.length > 0) {
+ $.each(cols, function (i, v) {
+ v.filter = v.filter || false;
+ if (v.filter !== false && tableInit.modifyUrl !== false) {
+ admin.table.listenSwitch({ filter: v.filter, url: tableInit.modifyUrl, tableId: tableId, modifyReload: modifyReload });
+ }
+ });
+ }
+ },
+ renderOperat(data, elem) {
+ for (dk in data) {
+ var col = data[dk];
+ var operat = col[col.length - 1].operat;
+ if (operat !== undefined) {
+ var check = false;
+ for (key in operat) {
+ var item = operat[key];
+ if (typeof item === 'string') {
+ if (admin.checkAuth(item, elem)) {
+ check = true;
+ break;
+ }
+ } else {
+ for (k in item) {
+ var v = item[k];
+ if (v.auth == undefined) {
+ v.auth = 'add';
+ }
+ if (admin.checkAuth(v.auth, elem)) {
+ check = true;
+ break;
+ }
+ }
+ }
+ }
+ if (!check) {
+ data[dk].pop();
+ }
+ }
+
+ }
+ return data;
+ },
+ renderTrueHide(data, options) {
+ var newData = [];
+ for (dk in data) {
+ var newCol = [];
+ var col = data[dk];
+
+ col.forEach(colItem => {
+ var trueHide = false;
+ if (typeof colItem.trueHide == 'function') {
+ trueHide = colItem.trueHide(colItem, col, options);
+ } else if (typeof colItem.trueHide == 'string') {
+ trueHide = !admin.checkAuth(colItem.trueHide, options.elem);
+ } else {
+ trueHide = colItem.trueHide;
+ }
+
+ if (!trueHide) {
+ newCol.push(colItem);
+ }
+ });
+
+ newData.push(newCol);
+ }
+
+ return newData;
+ },
+ buildToolbarHtml: function (toolbar, tableId) {
+ var html = '';
+ toolbar.class = toolbar.class || '';
+ toolbar.icon = toolbar.icon || '';
+ toolbar.auth = toolbar.auth || 'add';
+ toolbar.url = toolbar.url || '';
+ toolbar.extend = toolbar.extend || '';
+ toolbar.method = toolbar.method || 'open';
+ toolbar.field = toolbar.field || 'id';
+ toolbar.title = toolbar.title || toolbar.text;
+ toolbar.text = toolbar.text || toolbar.title;
+ toolbar.checkbox = toolbar.checkbox || false;
+
+ var formatToolbar = toolbar;
+ formatToolbar.icon = formatToolbar.icon !== '' ? ' ' : '';
+ formatToolbar.class = formatToolbar.class !== '' ? 'class="' + formatToolbar.class + '" ' : '';
+ if (toolbar.method === 'open') {
+ formatToolbar.method = formatToolbar.method !== '' ? 'data-open="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
+ } else if (toolbar.method === 'none') { // 常用于与extend配合,自定义监听按钮
+ formatToolbar.method = '';
+ } else if (toolbar.method === 'blank') {
+ formatToolbar.method = ' href="' + formatToolbar.url + '" target="_blank" ';
+ } else if (operat.method === 'tab') {
+ formatToolbar.method = ' layuimini-content-href="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '"';
+ } else {
+ formatToolbar.method = formatToolbar.method !== '' ? 'data-request="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
+ }
+ formatToolbar.checkbox = toolbar.checkbox ? ' data-checkbox="true" ' : '';
+ formatToolbar.tableId = tableId !== undefined ? ' data-table="' + tableId + '" ' : '';
+ html = '';
+
+ return html;
+ },
+ buildOperatHtml: function (operat, data) {
+ var html = '';
+ operat.class = operat.class || '';
+ operat.icon = operat.icon || '';
+ operat.auth = operat.auth || 'add';
+ operat.url = operat.url || '';
+ operat.extend = operat.extend || '';
+ operat.method = operat.method || 'open';
+ operat.field = operat.field || 'id';
+ operat.data = operat.data || ['id'];
+ operat.titleField = operat.titleField || 'title';
+ operat.title = operat.title || operat.text;
+ operat.text = operat.text || operat.title;
+
+ var titleEndfix = '';
+
+ if (typeof operat.titleField == 'function') {
+ titleEndfix = operat.titleField(data, operat);
+
+ } else if (data[operat.titleField]) {
+ titleEndfix = '-' + data[operat.titleField];
+ }
+
+ if (typeof operat.text == 'function') {
+ operat.text = operat.text(data, operat);
+ }
+
+ if (typeof operat.title == 'function') {
+ operat.title = operat.title(data, operat);
+ }
+
+ var formatOperat = operat;
+ formatOperat.icon = formatOperat.icon !== '' ? ' ' : '';
+ formatOperat.class = formatOperat.class !== '' ? 'class="' + formatOperat.class + '" ' : '';
+ if (operat.method === 'open') {
+ formatOperat.method = formatOperat.method !== '' ? 'data-open="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
+ } else if (operat.method === 'none') { // 常用于与extend配合,自定义监听按钮
+ formatOperat.method = '';
+ } else if (operat.method === 'blank') {
+ formatOperat.method = ' href="' + formatOperat.url + '" target="_blank" ';
+ } else if (operat.method === 'tab') {
+ formatOperat.method = ' layuimini-content-href="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '"';
+ } else {
+ formatOperat.method = formatOperat.method !== '' ? 'data-request="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
+ }
+
+ formatOperat.dataBind = ' ';
+ operat.data.forEach((item, index) => {
+ formatOperat.dataBind += 'data-' + item + '="' + data[item] + '" ';
+ });
+
+ html = '' + formatOperat.icon + formatOperat.text + '';
+
+ return html;
+ },
+ toolSpliceUrl(url, field, data) {
+ url = url.indexOf("?") !== -1 ? url + '&' + field + '=' + data[field] : url + '?' + field + '=' + data[field];
+ return url;
+ },
+ formatCols: function (cols, init) {
+ for (i in cols) {
+ var col = cols[i];
+ for (index in col) {
+ var val = col[index];
+
+ if (typeof val.hide == 'function') {
+ cols[i][index]['hide'] = val.hide(val, cols, init);
+ }
+ if (val['width'] == undefined && val['minWidth'] == undefined) {
+ var width = null;
+ if (val.title) {
+ width = val.title.length * 15 + 55;
+ }
+
+ if (width != null) {
+ cols[i][index]['minWidth'] = width;
+ }
+ }
+
+ // if str end with _time
+ if (val.field && val.field.indexOf('_time') !== -1) {
+ cols[i][index]['minWidth'] = 160;
+ }
+
+
+ if (val.sort === undefined) {
+ cols[i][index]['sort'] = true;
+ }
+ if (val.defaultValue === undefined) {
+ cols[i][index]['defaultValue'] = '';
+ }
+
+ // 判断是否包含初始化数据
+ if (val.init === undefined) {
+ cols[i][index]['init'] = init;
+ }
+
+ // 格式化列操作栏
+ if (val.templet === admin.table.tool && val.operat === undefined) {
+ cols[i][index]['operat'] = ['edit', 'delete'];
+ }
+ // 格式化列操作栏
+ if (val.templet === admin.table.tool) {
+ cols[i][index]['sort'] = false;
+ }
+
+ // 判断是否包含开关组件
+ if (val.templet === admin.table.switch && val.filter === undefined) {
+ cols[i][index]['filter'] = val.field;
+ }
+
+ // 判断是否含有搜索下拉列表
+ if (val.selectList !== undefined && val.search === undefined) {
+ cols[i][index]['search'] = 'select';
+ }
+
+ // 判断是否初始化对齐方式
+ if (val.align === undefined) {
+ cols[i][index]['align'] = 'left';
+ }
+
+ // 部分字段开启排序
+ var sortDefaultFields = ['id', 'sort'];
+ if (val.sort === undefined && sortDefaultFields.indexOf(val.field) >= 0) {
+ cols[i][index]['sort'] = true;
+ }
+
+ // 初始化图片高度
+ if (val.templet === admin.table.image && val.imageHeight === undefined) {
+ cols[i][index]['imageHeight'] = 26;
+ cols[i][index]['sort'] = false;
+ }
+ // 图片默认不搜索
+ if (val.templet === admin.table.image && val.search === undefined) {
+ cols[i][index]['search'] = false;
+ }
+
+ // 判断是否列表数据转换
+ if (val.selectList !== undefined && val.templet === undefined) {
+ cols[i][index]['templet'] = admin.table.list;
+ }
+
+ // 判断是否多层对象
+ if (val.field !== undefined && val.field.split(".").length > 1) {
+ if (val.templet === undefined) {
+ cols[i][index]['templet'] = admin.table.value;
+ }
+ }
+
+ // 如果未定义则默认使用value
+ if (cols[i][index]['templet'] === undefined) {
+ cols[i][index]['templet'] = admin.table.value;
+ } else {
+ // 针对特定的模板做数据调整
+
+ if (cols[i][index]['templet'] == admin.table.list) {
+ if (val.selectValue) {
+
+ var newSelectList = {};
+ val.selectList.map(item => {
+ newSelectList[item[val.selectValue]] = item[val.selectLabel];
+ });
+
+ cols[i][index]['selectList'] = newSelectList;
+
+ }
+ }
+ }
+
+ if (val.fieldFormat == undefined) {
+
+ switch (val.templet) {
+ case admin.table.image:
+ val.fieldFormat = 'image';
+ break;
+ case admin.table.date:
+ val.fieldFormat = 'date';
+ break;
+ default:
+ val.fieldFormat = 'text';
+
+ if (val.selectList !== undefined) {
+ val.fieldFormat = 'select';
+ }
+ break;
+ }
+ }
+ }
+ }
+ return cols;
+ },
+ tool: function (data) {
+ var option = data.LAY_COL;
+ option.operat = option.operat || ['edit', 'delete'];
+ var elem = option.init.tableElem || init.tableElem;
+ var html = '';
+ $.each(option.operat, function (i, item) {
+ if (typeof item === 'string') {
+ switch (item) {
+ case 'edit':
+ var editMethod = 'tab';
+ if (selectMode) {
+ editMethod = 'open';
+ }
+ var operat = {
+ class: 'layui-btn layui-btn-success layui-btn-xs',
+ method: editMethod,
+ field: 'id',
+ icon: '',
+ text: '编辑',
+ title: '编辑信息',
+ auth: 'edit',
+ url: option.init.editUrl,
+ extend: option.init.formFullScreen == 'true' ? ' data-full="true"' : ''
+ };
+ operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
+ if (admin.checkAuth(operat.auth, elem)) {
+ html += admin.table.buildOperatHtml(operat, data);
+ }
+ break;
+ case 'delete':
+ var operat = {
+ class: 'layui-btn layui-btn-danger layui-btn-xs',
+ method: 'get',
+ field: 'id',
+ icon: '',
+ text: '删除',
+ title: '确定删除?',
+ auth: 'delete',
+ url: option.init.deleteUrl,
+ extend: ""
+ };
+ operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
+ if (admin.checkAuth(operat.auth, elem)) {
+ html += admin.table.buildOperatHtml(operat, data);
+ }
+ break;
+ }
+
+ } else if (typeof item === 'object') {
+ $.each(item, function (i, operat) {
+ operat.class = operat.class || '';
+ operat.icon = operat.icon || '';
+ operat.auth = operat.auth || 'add';
+ operat.url = operat.url || '';
+ operat.method = operat.method || 'open';
+ operat.field = operat.field || 'id';
+ operat.title = operat.title || operat.text;
+ operat.text = operat.text || operat.title;
+ operat.extend = operat.extend || '';
+
+ operat._if = operat._if || function () { return true; };
+
+ if (typeof operat._if == 'function') {
+ if (operat._if(data, operat) !== true) {
+ return '';
+ }
+ } else if (typeof operat._if == 'string') {
+ var ifValue = admin.table.returnColumnValue(data, operat._if, false);
+ if (!ifValue) {
+ return '';
+ }
+ }
+
+ // 自定义表格opreat按钮的弹窗标题风格,extra是表格里的欲加入标题中的字段
+ operat.extra = operat.extra || '';
+ if (data[operat.extra] !== undefined) {
+ operat.title = data[operat.extra] + ' - ' + operat.title;
+ }
+
+ if (typeof operat.url == 'function') {
+ operat.url = operat.url(data, operat);
+ }
+
+
+ if (typeof operat.field != 'function') {
+ if (!admin.empty(operat.field)) {
+ operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
+ }
+ } else {
+
+ var fieldParam = operat.field(data, operat);
+
+ if (typeof fieldParam == 'string') {
+ operat.url = fieldParam;
+ } else if (typeof fieldParam == 'object') {
+ for (const key in fieldParam) {
+ if (Object.hasOwnProperty.call(fieldParam, key)) {
+ const value = fieldParam[key];
+ operat.url = admin.table.toolSpliceUrl(operat.url, key, fieldParam);
+ }
+ }
+ }
+ }
+
+
+ if (operat.method == 'get' && !admin.empty(operat.url)) {
+ operat.url = admin.url(operat.url);
+ }
+
+ if (admin.checkAuth(operat.auth, elem)) {
+ html += admin.table.buildOperatHtml(operat, data);
+ }
+ });
+ }
+ });
+ return html;
+ },
+ value: function (data) {
+ var option = data.LAY_COL;
+ var value = data;
+ if (option.field.split('.').length > 1) {
+ var field = option.field;
+ option.field = field.split('.');
+ value = admin.dataGet(data, option.field);
+ } else {
+ value = data[option.field];
+ }
+ return value;
+ },
+ returnColumnValue: function (data, field, defaultValue) {
+ var option = data.LAY_COL || {};
+ var targetField = field || option.field;
+ var targetDefaultValue = defaultValue;
+ if (targetDefaultValue === undefined) {
+ targetDefaultValue = option.defaultValue;
+ }
+ if (!targetField) {
+ return targetDefaultValue;
+ }
+ if (Array.isArray(targetField) || (typeof targetField === 'string' && targetField.split('.').length > 1)) {
+ return admin.dataGet(data, targetField, targetDefaultValue);
+ }
+ var value = data[targetField];
+ if (value === undefined || value === null) {
+ return targetDefaultValue;
+ }
+ return value;
+ },
+ list: function (data) {
+ var option = data.LAY_COL;
+ option.selectList = option.selectList || {};
+
+ var value = admin.table.returnColumnValue(data);
+ if (option.selectList[value] === undefined || option.selectList[value] === '' || option.selectList[value] === null) {
+ return value;
+ } else {
+ return option.selectList[value];
+ }
+ },
+ filePreview: function (data) {
+ var mimeName = data.mime_type.split('/')[0];
+
+ if (mimeName == 'image') {
+ return admin.table.image(data);
+ } else {
+
+ var value = admin.table.returnColumnValue(data);
+
+ var groupName = admin.getExtGroupName(data.file_ext);
+
+ return '
';
+ }
+
+ },
+ image: function (data) {
+ var option = data.LAY_COL;
+ option.imageWidth = option.imageWidth || 200;
+ option.imageHeight = option.imageHeight || 26;
+ option.imageSplit = option.imageSplit || '|';
+ option.imageJoin = option.imageJoin || '
';
+ option.title = option.title || option.field;
+ var title = data[option.title];
+ var value = admin.table.returnColumnValue(data);
+ if (value === undefined || value === null) {
+ return '
';
+ } else {
+ var values = value.split(option.imageSplit),
+ valuesHtml = [];
+ values.forEach((value, index) => {
+ valuesHtml.push('
');
+ });
+ return valuesHtml.join(option.imageJoin);
+ }
+ },
+ url: function (data) {
+ var option = data.LAY_COL;
+
+ var urlNameField = option.urlNameField || '';
+
+ var value = admin.table.returnColumnValue(data);
+
+ if (admin.empty(value)) {
+ return value;
+ }
+
+ var urlName = '';
+ if (!admin.empty(urlNameField)) {
+ urlName = data[urlNameField] || '';
+ }
+
+ if (admin.empty(urlName)) {
+ urlName = value;
+ }
+
+ return '' + urlName + '';
+ },
+ date: function (data) {
+ var option = data.LAY_COL;
+ var value = admin.table.returnColumnValue(data);
+ if (value === undefined || value === null) {
+ return value;
+ }
+ if (option.timeFormat === undefined) {
+ return layui.util.toDateString(value * 1000, 'yyyy-MM-dd HH:mm:ss');
+ } else {
+ return layui.util.toDateString(value * 1000, option.timeFormat);
+ }
+ },
+ switch: function (data) {
+ var option = data.LAY_COL;
+ option.filter = option.filter || option.field;
+ option.openText = option.openText || '开';
+ option.closeText = option.closeText || '关';
+ option.open = option.open || '1';
+ option.close = option.close || '0';
+ option.url = option.url || '';
+ option.switchStyle = option.switchStyle || 'switch';
+ var value = admin.table.returnColumnValue(data);
+
+ if (admin.empty(value)) {
+ return '';
+ }
+
+ var renderSwitch = '';
+
+ if (option.switchStyle == 'checkbox') {
+ renderSwitch = '';
+ } else if (option.switchStyle == 'switch') {
+ renderSwitch = '';
+ }
+
+ return renderSwitch;
+ },
+ listenSwitch: function (data) {
+ var filter = data.filter,
+ url = data.url,
+ tableId = data.tableId,
+ modifyReload = data.modifyReload;
+ form.on('switch(' + filter + ')', function (obj) {
+ var id = obj.elem.getAttribute('data-id');
+ var field = obj.elem.getAttribute('name');
+ var value = this.checked ? 1 : 0;
+ admin.request.post({
+ url: url,
+ prefix: true,
+ data: {
+ id: id,
+ field: field,
+ value: value,
+ },
+ }, function (res) {
+ if (modifyReload) {
+ table.reloadData(tableId);
+ }
+ }, function (res) {
+ admin.msg.error(res.msg, function () {
+ table.reloadData(tableId);
+ });
+ }, function () {
+ table.reloadData(tableId);
+ });
+ return false;
+ });
+ },
+ listenTableSort: function (options) {
+ table.on('sort(' + options.layFilter + ')', function (obj) {
+ var type = obj.type;
+ var sort = obj.field;
+ var tableId = options.id;
+
+ if (options.autoSort != undefined && options.autoSort == true) {
+ var sortVal;
+ if (type === undefined || type === null || type === '') {
+ sortVal = 'default';
+ } else {
+ sortVal = type;
+ }
+ var sortData = {
+ sort: sort,
+ order: sortVal
+ };
+ var where = admin.table.formatWhere(options, sortData, tableId);
+ options.where = where;
+ table.reloadData(tableId, {
+ initSort: obj,
+ where: where,
+ });
+ }
+ });
+ },
+ listenToolbar: function (layFilter, tableId) {
+ table.on('toolbar(' + layFilter + ')', function (obj) {
+ var item = obj.event;
+ switch (item) {
+ case 'TABLE_SEARCH':
+ if (!$('#' + tableId + '_filter_form').is(':visible')) {
+ $('#' + tableId + '_filter_form').removeClass('layui-hide');
+ $('#' + tableId + '_filter_form').show();
+ } else {
+ $('#' + tableId + '_filter_form').hide();
+ }
+ break;
+ case 'TABLE_LAYOUT':
+ var layoutElemIdName = '#layout-' + tableId;
+ if ($(layoutElemIdName).length > 0) {
+ // If it is, remove the HTML
+ $(layoutElemIdName).remove();
+ }
+ if (!Array.isArray(options.layoutList)) {
+ options.layoutList = ['table', 'card'];
+ }
+ var layoutList = [];
+ var defaultLayout = 'table';
+ var layoutListDefault = [
+ {
+ name: 'table',
+ title: '表格',
+ icon: 'layui-icon-table'
+ },
+ {
+ name: 'card',
+ title: '卡片',
+ icon: 'layui-icon-table'
+ },
+ ];
+ options.layoutList.forEach((item) => {
+ if (typeof item == 'string') {
+ layoutListDefault.forEach((layout) => {
+ if (layout.name == item) {
+ layoutList.push(layout);
+ }
+ });
+ } else {
+ if (item.name == 'table') {
+ layoutList.push({
+ name: 'table',
+ title: '表格',
+ icon: 'layui-icon-table'
+ });
+ } else if (item.name == 'card') {
+ layoutList.push({
+ name: 'card',
+ title: '卡片',
+ icon: 'layui-icon-table'
+ });
+ } else {
+ item.icon = item.icon || 'layui-icon-table';
+ item.title = item.title || item.name;
+ layoutList.push(item);
+ }
+ }
+ });
+
+ var layoutHtml = '';
+ layoutList.forEach((item) => {
+ var currentClassName = '';
+ var currentLayout = admin.getPageSetting('table-layout-default', defaultLayout);
+ if (currentLayout == item.name) {
+ currentClassName = 'current';
+ }
+ layoutHtml += `
+
`;
+ });
+
+ layoutHtml += '
';
+
+ var toolbarLayoutElem = $('[lay-table-id="' + tableId + '"]').find('[lay-event="TABLE_LAYOUT"]');
+ if (toolbarLayoutElem.find(layoutElemIdName).length > 0) {
+ // If it is, remove the HTML
+ $(layoutElemIdName).remove();
+ }
+ layoulElem = $(layoutHtml);
+ layoulElem.appendTo(toolbarLayoutElem);
+
+
+ layoulElem.on('click', function (event) {
+
+ var item = $(event.target).closest('.item');
+ if (item.length > 0) {
+ // 点击操作
+ item.addClass('current').siblings().removeClass('current');
+
+ var layoutName = item.data('name');
+ admin.setPageSetting('table-layout-default', layoutName);
+
+ table.reloadData(tableId, {}, true);
+ } else {
+ // 其他区域操作
+ }
+
+ // 不要冒泡
+ event.stopPropagation();
+ });
+
+ // Remove any existing click event listeners to avoid duplicates
+ $(document).off('click.table-layout').on('click.table-layout', function (event) {
+
+ if (!$(event.target).closest(toolbarLayoutElem).length) {
+ // If it is, remove the HTML
+ $(layoutElemIdName).remove();
+ }
+ });
+ break;
+ }
+ });
+ },
+ listenEdit: function (tableInit, layFilter, tableId, modifyReload) {
+ tableInit.modifyUrl = tableInit.modifyUrl || false;
+ tableId = tableId || init.tableRenderId;
+ if (tableInit.modifyUrl !== false) {
+ table.on('edit(' + layFilter + ')', function (obj) {
+ var value = obj.value,
+ data = obj.data,
+ id = data.id,
+ field = obj.field;
+ var _data = {
+ id: id,
+ field: field,
+ value: value,
+ };
+ admin.request.post({
+ url: tableInit.modifyUrl,
+ prefix: true,
+ data: _data,
+ }, function (res) {
+ if (modifyReload) {
+ table.reloadData(tableId);
+ }
+ }, function (res) {
+ admin.msg.error(res.msg, function () {
+ table.reloadData(tableId);
+ });
+ }, function () {
+ table.reloadData(tableId);
+ });
+ });
+ }
+ },
+ formatWhere: function (options, sortData, tableId) {
+ var where = {};
+ if (options.where != undefined) {
+ where = options.where;
+ }
+ if (options.where && options.where.filter && options.where.op) {
+ where = options.where;
+ }
+
+ if (sortData !== undefined) {
+ where['sort'] = sortData.sort;
+ where['order'] = sortData.order;
+ }
+
+ lastTableWhere[tableId] = where;
+
+ return where;
+ },
+ renderLayoutBefore: function (options) {
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+
+ if (currentLayout != 'table') {
+ // 隐藏所有数据体内容
+ var layuiTableElemName = '#layui-table-' + options.id;
+ var layuiTableElem = $(layuiTableElemName);
+ layuiTableElem.find('.layui-table-box').hide();
+ }
+ },
+ renderLayoutAfter: function (options, res) {
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+
+ if (currentLayout != 'table') {
+ // 隐藏所有数据体内容
+ var layuiTableElemName = '#layui-table-' + options.id;
+ var layuiTableElem = $(layuiTableElemName);
+ if (!Array.isArray(options.layoutList)) {
+ options.layoutList = ['table', 'card'];
+ }
+
+ options.layoutList.forEach((item) => {
+ if (currentLayout == 'table') {
+ // 如果是table,则不用生成数据,显示出来就行,before已经显示过了
+ return;
+ }
+
+ if (currentLayout != item.name) {
+ // 如果不是,则不进行任何操作
+ return;
+ }
+
+ var className = '.layui-table-custom.layui-table-custom-' + item.name;
+
+ // 清空里面的数据
+ layuiTableElem.find(className).html('');
+ loading.hide();
+
+ item.tplFunction(options, res, layuiTableElem.find(className));
+
+
+
+
+ });
+
+ }
+ },
+ listenTableSelectConfirm(options) {
+ $('.select-confirm').click(function () {
+ var checkStatus = table.checkStatus(options.id);
+
+ if (checkStatus.data.length == 0) {
+ layer.msg('请选择数据');
+ return false;
+ }
+
+ parent.window[selectConfirmCallback](checkStatus.data);
+ });
+ },
+ listenExport: function (options) {
+
+ var exportFields = {};
+
+ var imageFields = [];
+
+ var selectFields = {};
+
+ var dateFields = [];
+
+ options.cols[0].forEach(col => {
+ if (col.field) {
+
+ exportFields[col.field] = col.title;
+
+ options.cols[0].forEach(col => {
+ if (col.field) {
+
+ exportFields[col.field] = col.title;
+
+ switch (col.fieldFormat) {
+ case 'image':
+ imageFields.push(col.field);
+ break;
+
+ case 'select':
+ if (Object.keys(col.selectList).length > 0) {
+ selectFields[col.field] = col.selectList;
+ }
+ break;
+
+ case 'date':
+
+ dateFields.push(col.field);
+ break;
+
+ default:
+ break;
+ }
+
+ }
+ });
+
+ }
+ });
+
+ // excel导出
+ $('body').on('click', '[data-table-export]', function () {
+ var tableId = $(this).attr('data-table-export'),
+ url = $(this).attr('data-url');
+
+ var searchVals = form.val(tableId + '_filter_form');
+
+ var dataField = searchVals;
+
+ var formatFilter = {},
+ formatOp = {};
+ $.each(dataField, function (key, val) {
+ if (val !== '') {
+ formatFilter[key] = val;
+
+ var elemId = admin.table.renderSearchFormItemElementId(key);
+
+ var op = $('#c-' + elemId).attr('data-search-op');
+ op = op || '%*%';
+ formatOp[key] = op;
+ }
+ });
+
+ var searchQuery = {
+ filter: JSON.stringify(formatFilter),
+ op: JSON.stringify(formatOp),
+ fields: JSON.stringify(exportFields),
+ image_fields: JSON.stringify(imageFields),
+ select_fields: JSON.stringify(selectFields),
+ date_fields: JSON.stringify(dateFields),
+ };
+
+ var query = $.param(searchQuery);
+
+ var index = admin.msg.confirm('根据查询进行导出,确定导出?', function () {
+
+ toUrl = admin.url(url);
+ if (toUrl.indexOf('?') < 0) {
+ toUrl += '?';
+ } else {
+ toUrl += '&';
+ }
+ toUrl += query;
+
+ window.open(toUrl);
+
+ layer.close(index);
+ });
+ });
+ },
+ renderSearchFormItemElementId(key) {
+
+ var elemId = key;
+ if (key.indexOf('[') == 0) {
+ var keyArr = key.replace('[', '').split(']');
+
+ elemId = keyArr[0] + '-' + keyArr[1];
+ }
+
+ elemId = elemId.replace('.', '-');
+
+ return elemId;
+ }
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
diff --git a/public/static/plugs/ulthon-admin/src/ulthon-admin.04-listen.js b/public/static/plugs/ulthon-admin/src/ulthon-admin.04-listen.js
new file mode 100644
index 0000000..fbf107f
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/src/ulthon-admin.04-listen.js
@@ -0,0 +1,360 @@
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var init = ctx.init;
+ var table = ctx.table;
+ var form = ctx.layui.form;
+ var layer = ctx.layui.layer;
+
+ admin.checkMobile = function () {
+ return tools.checkMobile();
+ };
+ admin.open = function (title, url, width, height, isResize, shadeClose = false) {
+ isResize = isResize === undefined ? true : isResize;
+ var index = layer.open({
+ title: title,
+ type: 2,
+ area: [width, height],
+ content: url,
+ maxmin: true,
+ moveOut: true,
+ shadeClose: shadeClose,
+ success: function (layero, index) {
+ var body = layer.getChildFrame('body', index);
+ if (body.length > 0) {
+ $.each(body, function (i, v) {
+
+ // todo 优化弹出层背景色修改
+ $(v).before('');
+ });
+ }
+ },
+ end: function () {
+ index = null;
+ }
+ });
+ if (admin.checkMobile() || width === undefined || height === undefined) {
+ layer.full(index);
+ }
+ if (isResize) {
+ $(window).on("resize", function () {
+ index && layer.full(index);
+ });
+ }
+ };
+ admin.listen = function (preposeCallback, ok, no, ex, complete) {
+
+ // 监听表单是否为必填项
+ admin.api.formRequired();
+
+ // 监听表单提交事件
+ admin.api.formSubmit(preposeCallback, ok, no, ex, complete);
+
+ // 监听按钮操作
+ admin.api.button();
+
+ // 初始化图片显示以及监听上传事件
+ admin.api.upload();
+
+ // 监听富文本初始化
+ admin.api.editor();
+
+ // 监听下拉选择生成
+ admin.api.select();
+
+ // 监听原生单选框选中
+ admin.api.nativeRadio();
+ admin.api.nativeSelect();
+
+ // 监听时间控件生成
+ admin.api.date();
+
+ // 监听通用表格数据控件生成
+ admin.api.tableData();
+ // 监听地图组件
+ admin.api.mapLocation();
+
+ // 监听标签输入控件生成
+ admin.api.tagInput();
+ // 监听属性输入控件生成
+ admin.api.propertyInput();
+
+ // 监听点击复制
+ admin.api.copyText();
+
+ // 监听点击粘贴
+ admin.api.pasteText();
+
+ // 监听tab操作
+ miniTab.listen();
+
+ // 初始化layui表单
+ form.render();
+
+ // 表格修改
+ $("body").on("mouseenter", ".table-edit-tips", function () {
+ var openTips = layer.tips('点击行内容可以进行修改', $(this), { tips: [2, '#e74c3c'], time: 4000 });
+ });
+
+ // 监听弹出层的打开
+ $('body').on('click', '[data-open]', function () {
+
+ var clienWidth = $(this).attr('data-width'),
+ clientHeight = $(this).attr('data-height'),
+ dataFull = $(this).attr('data-full'),
+ checkbox = $(this).attr('data-checkbox'),
+ url = $(this).attr('data-open'),
+ external = $(this).attr('data-external') || false,
+ tableId = $(this).attr('data-table');
+
+ if (checkbox === 'true') {
+ tableId = tableId || init.tableRenderId;
+ var checkStatus = table.checkStatus(tableId),
+ data = checkStatus.data;
+ if (data.length <= 0) {
+ admin.msg.error('请勾选需要操作的数据');
+ return false;
+ }
+ var ids = [];
+ $.each(data, function (i, v) {
+ ids.push(v.id);
+ });
+ if (url.indexOf("?") === -1) {
+ url += '?id=' + ids.join(',');
+ } else {
+ url += '&id=' + ids.join(',');
+ }
+ }
+
+ if (clienWidth === undefined || clientHeight === undefined) {
+ var width = document.body.clientWidth,
+ height = document.body.clientHeight;
+ if (width >= 800 && height >= 600) {
+ clienWidth = '800px';
+ clientHeight = '600px';
+ } else {
+ clienWidth = '100%';
+ clientHeight = '100%';
+ }
+ }
+ if (dataFull === 'true') {
+ clienWidth = '100%';
+ clientHeight = '100%';
+ }
+
+ // 如果是手机版,则直接跳转
+ if (admin.checkMobile()) {
+ location.href = external ? url : admin.url(url);
+ } else {
+ admin.open(
+ $(this).attr('data-title'),
+ external ? url : admin.url(url),
+ clienWidth,
+ clientHeight
+ );
+ }
+
+ });
+
+ // 放大图片
+ $('body').on('click', '[data-image]', function () {
+ var title = $(this).attr('data-image'),
+ src = $(this).attr('src'),
+ alt = $(this).attr('alt');
+ var photos = {
+ "title": title,
+ "id": Math.random(),
+ "data": [
+ {
+ "alt": alt,
+ "pid": Math.random(),
+ "src": src,
+ "thumb": src
+ }
+ ]
+ };
+ layer.photos({
+ photos: photos,
+ anim: 5
+ });
+ return false;
+ });
+
+ // 放大一组图片
+ $('body').on('click', '[data-images]', function () {
+ var doms = $(this).closest(".layuimini-upload-show").children("li"), // 从当前元素向上找layuimini-upload-show找到第一个后停止, 再找其所有子元素li
+ currentSrc = $(this).attr('src'), // 被点击的图片地址
+ start = 0,
+ data = [];
+ $.each(doms, function (key, value) {
+ var img = $(value).find('img'),
+ src = img.attr('src'),
+ alt = img.attr('alt');
+ data.push({
+ "alt": alt,
+ "pid": Math.random(),
+ "src": src,
+ "thumb": src
+ });
+ if (src === currentSrc) {
+ start = key;
+ }
+ });
+ var photos = {
+ "title": '',
+ "start": start,
+ "id": Math.random(),
+ "data": data,
+ };
+
+ layer.photos({
+ photos: photos,
+ anim: 5
+ });
+ return false;
+ });
+
+
+ // 监听动态表格刷新
+ $('body').on('click', '[data-table-refresh]', function () {
+ var tableId = $(this).attr('data-table-refresh');
+ if (tableId === undefined || tableId === '' || tableId == null) {
+ tableId = init.tableRenderId;
+ }
+ table.reloadData(tableId);
+ });
+
+ // 监听搜索表格重置
+ $('body').on('click', '[data-table-reset]', function () {
+ var tableId = $(this).attr('data-table-reset');
+ if (tableId === undefined || tableId === '' || tableId == null) {
+ tableId = init.tableRenderId;
+ }
+
+ setTimeout(() => {
+ var searchVals = form.val(tableId + '_filter_form');
+ var dataField = searchVals;
+ var formatFilter = {},
+ formatOp = {};
+ $.each(dataField, function (key, val) {
+ if (val !== '') {
+ formatFilter[key] = val;
+
+ var elemId = admin.table.renderSearchFormItemElementId(key);
+
+ var op = $('#c-' + elemId).attr('data-search-op');
+ op = op || '%*%';
+ formatOp[key] = op;
+ }
+ });
+
+ var where = {
+ filter: JSON.stringify(formatFilter),
+ op: JSON.stringify(formatOp)
+ };
+ table.reloadData(tableId, {
+ page: {
+ curr: 1
+ }
+ , where: where
+ }, 'data');
+ }, 100);
+ });
+
+ // 监听请求
+ $('body').on('click', '[data-request]', function () {
+ var title = $(this).attr('data-title'),
+ url = $(this).attr('data-request'),
+ tableId = $(this).attr('data-table'),
+ checkbox = $(this).attr('data-checkbox'),
+ direct = $(this).attr('data-direct'),
+ field = $(this).attr('data-field') || 'id',
+ endMethod = $(this).attr('data-end-method') || 'reload-table';
+
+ title = title || '确定进行该操作?';
+
+ if (direct === 'true') {
+ admin.msg.confirm(title, function () {
+ window.location.href = url;
+ });
+ return false;
+ }
+
+ var postData = {};
+ if (checkbox === 'true') {
+ tableId = tableId || init.tableRenderId;
+ var checkStatus = table.checkStatus(tableId),
+ data = checkStatus.data;
+ if (data.length <= 0) {
+ admin.msg.error('请勾选需要操作的数据');
+ return false;
+ }
+ var ids = [];
+ $.each(data, function (i, v) {
+ ids.push(v[field]);
+ });
+ postData[field] = ids;
+ }
+
+ url = admin.url(url);
+
+ admin.msg.confirm(title, function () {
+ admin.request.post({
+ url: url,
+ data: postData,
+ }, function (res) {
+ admin.msg.success(res.msg, function () {
+ if (endMethod == 'reload-table') {
+ tableId = tableId || init.tableRenderId;
+ table.reloadData(tableId);
+ } else if (endMethod == 'refresh-page') {
+ location.reload();
+ }
+ });
+ });
+ });
+ return false;
+ });
+
+
+
+ // 数据表格多删除
+ $('body').on('click', '[data-table-delete]', function () {
+ var tableId = $(this).attr('data-table-delete'),
+ url = $(this).attr('data-url');
+ tableId = tableId || init.tableRenderId;
+ url = url !== undefined ? admin.url(url) : window.location.href;
+ var checkStatus = table.checkStatus(tableId),
+ data = checkStatus.data;
+ if (data.length <= 0) {
+ admin.msg.error('请勾选需要删除的数据');
+ return false;
+ }
+ var ids = [];
+ $.each(data, function (i, v) {
+ ids.push(v.id);
+ });
+ admin.msg.confirm('确定删除?', function () {
+ admin.request.post({
+ url: url,
+ data: {
+ id: ids
+ },
+ }, function (res) {
+ admin.msg.success(res.msg, function () {
+ table.reloadData(tableId);
+ });
+ });
+ });
+ return false;
+ });
+
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
diff --git a/public/static/plugs/ulthon-admin/src/ulthon-admin.05-api.js b/public/static/plugs/ulthon-admin/src/ulthon-admin.05-api.js
new file mode 100644
index 0000000..38b736d
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/src/ulthon-admin.05-api.js
@@ -0,0 +1,802 @@
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var init = ctx.init;
+ var table = ctx.table;
+ var form = ctx.layui.form;
+ var layer = ctx.layui.layer;
+ var laydate = ctx.layui.laydate;
+ var upload = ctx.layui.upload;
+ var extGroup = ctx.extGroup;
+ var createEditor = ctx.createEditor;
+ var createToolbar = ctx.createToolbar;
+
+ admin.api = {
+ button: function () {
+ $('button[target="_blank"]').click(function () {
+ window.open(admin.url($(this).attr('href')));
+ });
+ },
+
+ closeCurrentOpen: function (option) {
+ option = option || {};
+ option.backHref = option.backHref || '';
+ option.refreshTable = option.refreshTable || false;
+ option.refreshFrame = option.refreshFrame || false;
+ option.onClose = option.onClose || function () { };
+ if (option.refreshTable === true) {
+ option.refreshTable = init.tableRenderId;
+ }
+ var backWindow = window.parent;
+ if (option.backHref) {
+ // 标签打开页面,需要返回上一个标签刷新的情况
+ backWindow = admin.findPageId(option.backHref);
+ if (backWindow) {
+ backWindow.layui.table.reloadData(option.refreshTable);
+ } else {
+ admin.findIndexPage(function (w) {
+ var menu = w.miniTab.searchMenu(option.backHref);
+ var title = option.backHref;
+
+ if (menu) {
+ title = menu.title;
+ }
+ w.miniTab.create({
+ tabId: option.backHref,
+ href: option.backHref,
+ title: title,
+ });
+ });
+ }
+ admin.findIndexPage(function (w) {
+ w.layui.element.tabDelete('layuiminiTab', admin.getCurrentPageId());
+ w.layui.element.tabChange('layuiminiTab', option.backHref);
+ });
+ return;
+ }
+ // 弹框保存后刷新的情况
+ var index = parent.layer.getFrameIndex(window.name);
+ backWindow.layer.close(index, option.onClose);
+ if (option.refreshTable !== false) {
+ backWindow.layui.table.reloadData(option.refreshTable);
+ }
+ if (option.refreshFrame) {
+ backWindow.location.reload();
+ }
+ return false;
+ },
+ refreshFrame: function () {
+ parent.location.reload();
+ return false;
+ },
+ refreshTable: function (tableName, mode) {
+ tableName = tableName || 'currentTableRenderId';
+ if (mode == 'table') {
+ table.reload(tableName);
+ } else {
+ table.reloadData(tableName);
+ }
+ },
+ // var options = {
+ // url :'system.menu/index?id=1'
+ // }
+ // ua.api.reloadTable('currentTableRenderId',options)
+ reloadTable: function (tableName, options, mode) {
+ tableName = tableName || 'currentTableRenderId';
+ if (mode == 'table') {
+ table.reload(tableName, options);
+ } else {
+ table.reloadData(tableName, options);
+ }
+ },
+ formRequired: function () {
+ var verifyList = document.querySelectorAll("[lay-verify]");
+ if (verifyList.length > 0) {
+ $.each(verifyList, function (i, v) {
+ var verify = $(this).attr('lay-verify');
+
+ // todo 必填项处理
+ if (verify.includes('required')) {
+ var label = $(this).parent().prev();
+ if (label.is('label') && !label.hasClass('required')) {
+ label.addClass('required');
+ }
+ if ($(this).attr('lay-reqtext') === undefined && $(this).attr('placeholder') !== undefined) {
+ $(this).attr('lay-reqtext', $(this).attr('placeholder'));
+ }
+ if ($(this).attr('placeholder') === undefined && $(this).attr('lay-reqtext') !== undefined) {
+ $(this).attr('placeholder', $(this).attr('lay-reqtext'));
+ }
+ }
+
+ });
+ }
+ },
+ formSubmit: function (preposeCallback, ok, no, ex, complete) {
+ var formList = document.querySelectorAll("[lay-submit]");
+
+ // 表单提交自动处理
+ if (formList.length > 0) {
+ $.each(formList, function (i, v) {
+ var filter = $(this).attr('lay-filter'),
+ type = $(this).attr('data-type'),
+ refresh = $(this).attr('data-refresh'),
+ close = $(this).attr('data-close'),
+ url = $(this).attr('lay-submit');
+ // 表格搜索不做自动提交
+ if (type === 'tableSearch') {
+ return false;
+ }
+ // 判断是否需要刷新表格
+ if (refresh === 'false') {
+ refresh = false;
+ } else {
+ refresh = true;
+ }
+ if (close === 'false') {
+ close = false;
+ } else {
+ close = true;
+ }
+ // 自动添加layui事件过滤器
+ if (filter === undefined || filter === '') {
+ filter = 'save_form_' + (i + 1);
+ $(this).attr('lay-filter', filter);
+ }
+ if (url === undefined || url === '' || url === null) {
+ url = window.location.href;
+ } else {
+ url = admin.url(url);
+ }
+ form.on('submit(' + filter + ')', function (data) {
+
+ var btnElem = data.elem;
+
+ var form = $(this).closest('form');
+ if ($(form).hasClass('loading')) return false;
+ $(form).addClass('loading');
+
+ // 判断btn是否具备name和value属性,如果有,则加到表单数据里
+ var btnName = $(btnElem).attr('name');
+ var btnValue = $(btnElem).attr('value');
+ var backHref = $(btnElem).attr('data-back-href');
+ if (btnName !== undefined && btnValue !== undefined) {
+ data.field[btnName] = btnValue;
+ }
+ if (!backHref) {
+ backHref = admin.getQueryVariable('backTagId');
+ }
+
+ var dataField = data.field;
+ dataField = admin.api.formSubmitEditor(dataField, v);
+ dataField = admin.api.formSubmitCity(dataField, v);
+
+ if (typeof preposeCallback === 'function') {
+ dataField = preposeCallback(dataField);
+ }
+ complete = complete || function () {
+ $(form).removeClass('loading');
+ };
+
+ if (ok) {
+ var originalOk = ok;
+ ok = function (res) {
+ originalOk(res);
+ complete();
+ };
+ } else {
+ ok = function (res) {
+ res.msg = res.msg || '';
+ admin.msg.success(res.msg, function () {
+ if (close) {
+
+ admin.api.closeCurrentOpen({
+ refreshTable: refresh,
+ backHref: backHref,
+ onClose: function () {
+ complete();
+ }
+ });
+
+ }
+ });
+ return false;
+ };
+ }
+
+ admin.request.post({
+ url: url,
+ data: dataField,
+ }, ok, no, ex, complete);
+
+ return false;
+ });
+ });
+ }
+
+ },
+ formSubmitEditor(dataField, form) {
+ return dataField;
+ },
+
+ formSubmitCity(dataField, form) {
+
+ var cityList = $(form).closest('.layui-form').find('[data-toggle="city-picker"]');
+
+ if (cityList.length > 0) {
+ $.each(cityList, function (i, v) {
+
+ var fieldName = $(v).attr('name');
+ var code = $(v).data('citypicker').getCode();
+ var text = $(v).data('citypicker').getVal();
+ var level = $(v).data('level');
+ var formatTargetList = {};
+
+ formatTargetList['name'] = 1;
+ formatTargetList['code'] = 1;
+ formatTargetList['name-province'] = 1;
+ formatTargetList['name-city'] = 1;
+ formatTargetList['name-district'] = 1;
+ formatTargetList['code-province'] = 1;
+ formatTargetList['code-city'] = 1;
+ formatTargetList['code-district'] = 1;
+
+
+ $.each(formatTargetList, function (targetType, value) {
+
+ var valueSet = $(v).data('field-' + targetType);
+
+ if (valueSet == 0) {
+ formatTargetList[targetType] = 0;
+ }
+
+ });
+
+ var codeArr = code.split('/');
+ var textArr = text.split('/');
+
+ if (formatTargetList['name'] == 1) {
+ dataField[fieldName] = text;
+ }
+ if (formatTargetList['code'] == 1) {
+ dataField[fieldName + '_code'] = code;
+ }
+ if (formatTargetList['name-province'] == 1) {
+ dataField[fieldName + '_name_province'] = textArr[0] || '';
+ }
+ if (formatTargetList['name-city'] == 1) {
+ dataField[fieldName + '_name_city'] = textArr[1] || '';
+ }
+ if (formatTargetList['name-district'] == 1) {
+ dataField[fieldName + '_name_district'] = textArr[2] || '';
+ }
+ if (formatTargetList['code-province'] == 1) {
+ dataField[fieldName + '_code_province'] = codeArr[0] || '';
+ }
+ if (formatTargetList['code-city'] == 1) {
+ dataField[fieldName + '_code_city'] = codeArr[1] || '';
+ }
+ if (formatTargetList['code-district'] == 1) {
+ dataField[fieldName + '_code_district'] = codeArr[2] || '';
+ }
+
+ });
+ }
+ return dataField;
+ },
+ upload: function () {
+ var uploadList = document.querySelectorAll("[data-upload]");
+ var uploadSelectList = document.querySelectorAll("[data-upload-select]");
+
+ if (uploadList.length > 0) {
+ $.each(uploadList, function (i, v) {
+ var uploadExts = $(this).attr('data-upload-exts'),
+ uploadName = $(this).attr('data-upload'),
+ uploadNumber = $(this).attr('data-upload-number') || 'one',
+ uploadSign = $(this).attr('data-upload-sign') || '|',
+ uploadAccept = $(this).attr('data-upload-accept') || 'file',
+ uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
+ uploadDisablePreview = $(this).attr('data-upload-disable-preview') || '0',
+ uploadFilenameField = $(this).attr('data-upload-filename-field') || '',
+ elem = "input[name='" + uploadName + "']",
+
+ uploadElem = this;
+ if (uploadFilenameField) {
+ var elemFilenameField = "[name='" + uploadFilenameField + "']";
+ }
+ if (uploadExts == '*') {
+ uploadExts = init.uploadExts;
+ } else if (uploadExts.charAt(0) == '*') {
+ var extGroupName = uploadExts.slice(1);
+ if (extGroup[extGroupName]) {
+ uploadExts = extGroup[extGroupName].join('|');
+ }
+ }
+
+ // 监听上传事件
+ upload.render({
+ elem: this,
+ url: admin.url(init.uploadUrl),
+ exts: uploadExts,
+ accept: uploadAccept,//指定允许上传时校验的文件类型
+ acceptMime: uploadAcceptMime,//规定打开文件选择框时,筛选出的文件类型
+ multiple: uploadNumber !== 'one',//是否多文件上传
+ headers: admin.headers(),
+ done: function (res) {
+ if (res.code === 0) {
+ var url = res.data.url;
+ var filename = res.data.original_name;
+ if (uploadNumber !== 'one') {
+ var oldUrl = $(elem).val();
+ if (oldUrl !== '') {
+ url = oldUrl + uploadSign + url;
+ }
+ if (elemFilenameField) {
+ var oldFilename = $(elemFilenameField).val();
+ if (oldFilename !== '') {
+ filename = oldFilename + uploadSign + filename;
+ }
+
+ }
+ }
+ if (elemFilenameField) {
+ $(elemFilenameField).val(filename);
+ }
+ $(elem).val(url);
+ $(elem).trigger("input");
+ admin.msg.success(res.msg);
+ } else {
+ admin.msg.error(res.msg);
+ }
+ return false;
+ }
+ });
+
+ if (uploadDisablePreview == 0) {
+ // 监听上传input值变化
+ $(elem).bind("input propertychange", function (event) {
+ var urlString = $(this).val(),
+ urlArray = urlString.split(uploadSign),
+ uploadIcon = $(uploadElem).attr('data-upload-icon') || "file";
+ var uploadNameKey = uploadName.replace(/\[/g, "-").replace(/\]/g, "-");
+ $('#bing-' + uploadNameKey).remove();
+ if (urlString.length > 0) {
+ var parant = $(this).parent('div');
+ var liHtml = '';
+ var filenameArray = [];
+ if (uploadFilenameField) {
+ var filenameVal = $(elemFilenameField).val() || '';
+ if (filenameVal) {
+ filenameArray = filenameVal.split(uploadSign);
+ }
+ }
+
+ $.each(urlArray, function (i, v) {
+
+ // 获取链接扩展名
+ var ext = v.substr(v.lastIndexOf('.') + 1);
+ var currentFilename = filenameArray[i] || '';
+ currentFilename = currentFilename.replace(/"/g, '"');
+
+ if (extGroup.image.indexOf(ext) != -1) {
+ // 是图片
+ liHtml += '
×\n';
+ } else {
+ // 不是图片
+ // 遍历extGroup数组找到扩展名所在的索引
+
+ uploadIcon = admin.getExtGroupName(ext);
+
+ liHtml += '
×\n';
+
+ }
+
+ });
+ parant.after('');
+
+ var initSortable = function () {
+ var el = document.getElementById('bing-' + uploadNameKey);
+ if (el) {
+ new Sortable(el, {
+ animation: 150,
+ onEnd: function (evt) {
+ var newUrls = [];
+ var newFilenames = [];
+ $(el).find('.uploads-delete-tip').each(function () {
+ newUrls.push($(this).attr('data-upload-url'));
+ newFilenames.push($(this).attr('data-upload-filename'));
+ });
+ $(elem).val(newUrls.join(uploadSign));
+ if (uploadFilenameField) {
+ $(elemFilenameField).val(newFilenames.join(uploadSign));
+ }
+ $(elem).trigger("input");
+ }
+ });
+ }
+ };
+
+ initSortable();
+ }
+
+ });
+
+ // 非空初始化图片显示
+ if ($(elem).val() !== '') {
+ $(elem).trigger("input");
+ }
+ }
+
+ });
+
+ // 监听上传文件的删除事件
+ $('body').on('click', '[data-upload-delete]', function () {
+ var uploadName = $(this).attr('data-upload-delete'),
+ deleteUrl = $(this).attr('data-upload-url'),
+ uploadFilenameField = $(this).attr('data-upload-filename-field'),
+ sign = $(this).attr('data-upload-sign');
+ var confirm = admin.msg.confirm('确定删除?', function () {
+ var elem = "input[name='" + uploadName + "']";
+ var elemFilenameField = "[name='" + uploadFilenameField + "']";
+ var currentUrl = $(elem).val();
+ var currentFilename = $(elemFilenameField).val();
+
+ var currentUrlList = currentUrl.split(sign);
+ var deleteIndex = currentUrlList.indexOf(deleteUrl);
+
+ currentUrlList.splice(deleteIndex, 1);
+ $(elem).val(currentUrlList.join(sign));
+ $(elem).trigger("input");
+
+ if (currentFilename) {
+
+ var currentFilenameList = currentFilename.split(sign);
+ currentFilenameList.splice(deleteIndex, 1);
+
+ $(elemFilenameField).val(currentFilenameList.join(sign));
+ }
+
+ admin.msg.close(confirm);
+ });
+ return false;
+ });
+ }
+
+ if (uploadSelectList.length > 0) {
+ $.each(uploadSelectList, function (i, v) {
+ var uploadName = $(this).attr('data-upload-select'),
+ uploadNumber = $(this).attr('data-upload-number') || 'one',
+ uploadSign = $(this).attr('data-upload-sign') || '|',
+ uploadFilenameField = $(this).attr('data-upload-filename-field') || '';
+
+ if (uploadFilenameField) {
+ var elemFilenameField = "[name='" + uploadFilenameField + "']";
+ var elemFilename = $(elemFilenameField);
+ }
+
+ var selectCheck = uploadNumber === 'one' ? 'radio' : 'checkbox';
+ var elem = "input[name='" + uploadName + "']";
+ var width = document.body.clientWidth,
+ height = document.body.clientHeight;
+
+ if (width >= 800 && height >= 600) {
+ clienWidth = '800px';
+ clientHeight = '600px';
+ } else {
+ clienWidth = '100%';
+ clientHeight = '100%';
+ }
+
+ $(v).click(function () {
+
+ layer.open({
+ title: '选择文件',
+ type: 2,
+ area: [clienWidth, clientHeight],
+ content: admin.url('system.uploadfile/index') + '?select_mode=' + selectCheck,
+ success(layero, index) {
+ window.onTableDataConfirm = function (data) {
+ var currentUrl = $(elem).val();
+ var urlArray = currentUrl.split(uploadSign);
+ if (currentUrl.length == 0 || selectCheck == 'radio') {
+ urlArray = [];
+ }
+ if (uploadFilenameField) {
+ var currentFilename = $(elemFilename).val();
+ var filenameArray = currentFilename.split(uploadSign);
+ if (currentFilename.length == 0 || selectCheck == 'radio') {
+ filenameArray = [];
+ }
+ }
+ $.each(data, function (index, val) {
+ if (urlArray.indexOf(val.url) == -1) {
+ urlArray.push(val.url);
+ }
+ if (uploadFilenameField) {
+ if (filenameArray.indexOf(val.original_name) == -1) {
+ filenameArray.push(val.original_name);
+ }
+ }
+
+ });
+ var url = urlArray.join(uploadSign);
+
+ if (uploadFilenameField) {
+ var filename = filenameArray.join(uploadSign);
+ }
+ $(elem).val(url);
+ if (uploadFilenameField) {
+ $(elemFilenameField).val(filename);
+ }
+ $(elem).trigger("input");
+ layer.close(index);
+ admin.msg.success('选择成功');
+ };
+ }
+ });
+ });
+ });
+
+ }
+ },
+ editor: function () {
+ var editorList = document.querySelectorAll(".editor");
+ if (editorList.length > 0) {
+ $.each(editorList, function (i, v) {
+ var editorConfig = {
+ placeholder: '请输入内容',
+ onChange(editor) {
+ const html = editor.getHtml();
+ $(v).val(html);
+ },
+ MENU_CONF: {
+ uploadImage: {
+ server: admin.url('ajax/uploadEditor'),
+ maxFileSize: 10 * 1024 * 1024,
+ fieldName: 'upload',
+ },
+ }
+ };
+
+ var formName = $(this).attr('name');
+
+ var editorId = 'editor-' + formName.replace(/\[/g, '-').replace(/\]/g, '-');
+ var editorContainer = $('');
+ $(this).after(editorContainer);
+
+ var toolbarId = 'toolbar-' + formName.replace(/\[/g, '-').replace(/\]/g, '-');
+ var toolbarContent = $('');
+ $(this).after(toolbarContent);
+
+ $(this).hide();
+
+ var originalValue = $(this).val();
+ const editor = createEditor({
+ selector: '#' + editorId,
+ html: originalValue,
+ config: editorConfig,
+ mode: 'default',
+ scroll: true
+ });
+ $(v).data('editor', editor);
+
+
+ const toolbarConfig = {
+ excludeKeys: [
+ 'uploadVideo',
+ 'fullScreen',
+ 'todo',
+ ]
+ };
+
+ const toolbar = createToolbar({
+ editor,
+ selector: '#' + toolbarId,
+ config: toolbarConfig,
+ mode: 'default', // or 'simple'
+ });
+
+
+ });
+ }
+ },
+ select: function () {
+
+ var selectList = document.querySelectorAll("[data-select]");
+ $.each(selectList, function (i, v) {
+ var url = $(this).attr('data-select'),
+ selectFields = $(this).attr('data-fields'),
+ value = $(this).attr('data-value'),
+ that = this,
+ html = '';
+
+ var template = $(that).data('template');
+
+ if (typeof template != 'function') {
+ template = function (data, fields) {
+ return data[fields[1]];
+ };
+ }
+
+ var fields = selectFields.replace(/\s/g, "").split(',');
+ if (fields.length < 2) {
+ return admin.msg.error('下拉选择字段有误');
+ }
+ admin.request.get(
+ {
+ url: url,
+ data: {
+ selectFields: selectFields
+ },
+ }, function (res) {
+ var list = res.data;
+
+
+
+ list.forEach(val => {
+ var key = val[fields[0]];
+
+ var valueTitle = template(val, fields);
+
+ if (value !== undefined && key.toString() === value) {
+ html += '';
+ } else {
+ html += '';
+ }
+ });
+ $(that).html(html);
+ form.render();
+ }
+ );
+ });
+ },
+ nativeRadio() {
+ $('[value-checked]').each(function (index, elem) {
+ if ($(this).hasClass('checked-rendered')) {
+ return;
+ }
+ $(this).addClass('checked-rendered');
+ if ($(this).attr('value') == $(this).attr('value-checked')) {
+ $(this).prop('checked', true);
+ }
+ });
+ },
+ nativeSelect() {
+ $('[value-selected]').each(function (index, elem) {
+ if ($(this).hasClass('selected-rendered')) {
+ return;
+ }
+ $(this).addClass('selected-rendered');
+ if ($(this).attr('value') == $(this).attr('value-selected')) {
+ $(this).prop('selected', true);
+ }
+ });
+ },
+ date: function () {
+ var dateList = document.querySelectorAll("[data-date]");
+ if (dateList.length > 0) {
+ $.each(dateList, function (i, v) {
+ var format = $(this).attr('data-date'),
+ type = $(this).attr('data-date-type'),
+ range = $(this).attr('data-date-range');
+ if (type === undefined || type === '' || type === null) {
+ type = 'datetime';
+ }
+ var options = {
+ elem: this,
+ type: type,
+ };
+ if (format !== undefined && format !== '' && format !== null) {
+ options['format'] = format;
+ }
+ if (range !== undefined) {
+ if (range === null || range === '') {
+ range = '-';
+ }
+ options['range'] = range;
+ }
+ laydate.render(options);
+ });
+ }
+ },
+ tableData() {
+ var tableList = document.querySelectorAll('[data-toggle="table-data"]');
+ $.each(tableList, function (i, v) {
+ var data = $(v).data();
+ tableData.render(v, data, admin);
+ });
+
+ },
+ mapLocation() {
+ var mapList = document.querySelectorAll('[data-toggle="map-location"]');
+
+ $.each(mapList, function (i, v) {
+ if ($(v).hasClass('map-rendered')) {
+ return;
+ }
+ $(v).addClass('map-rendered');
+ var data = $(v).data();
+ mapLocation.render(v, data, admin);
+ });
+
+ },
+ tagInput() {
+ var list = document.querySelectorAll('[data-toggle="tag-input"]');
+ $.each(list, function (i, v) {
+ var data = $(v).data();
+ tagInput.render(v, data, admin);
+ });
+
+ },
+ propertyInput() {
+ var list = document.querySelectorAll('[data-toggle="property-input"]');
+ $.each(list, function (i, v) {
+ var data = $(v).data();
+
+ data.value = $(v).text();
+
+ propertyInput.render(v, data, admin);
+ });
+
+ },
+ copyText(elem) {
+ if (elem == undefined) {
+ elem = 'body';
+ }
+ var list = $(elem).find('[data-toggle="copy-text"]');
+
+ $.each(list, function (i, v) {
+
+ if ($(v).hasClass('copy-rendered')) {
+ return;
+ }
+
+ $(v).addClass('copy-rendered');
+ var clipboard = new ClipboardJS(v);
+
+ clipboard.on('success', function (e) {
+ admin.msg.success('复制成功');
+ });
+
+ clipboard.on('error', function (e) {
+ admin.msg.error('复制失败');
+
+ });
+ });
+ },
+ pasteText(elem) {
+ if (elem == undefined) {
+ elem = 'body';
+ }
+ var list = $(elem).find('[data-toggle="paste-text"]');
+
+ $.each(list, function (i, v) {
+
+ if ($(v).hasClass('paste-rendered')) {
+ return;
+ }
+ $(v).addClass('paste-rendered');
+
+ var targetElemName = $(v).data('paste-target');
+ $(v).on('click', function () {
+ if (!navigator.clipboard) {
+ admin.msg.error('您的当前不支持粘贴操作');
+ return;
+ }
+ navigator.clipboard.readText()
+ .then(text => {
+ $(targetElemName).val(text);
+ layer.msg('粘贴成功');
+ })
+ .catch(err => {
+ console.error('Failed to read clipboard contents: ', err);
+ layer.msg('粘贴失败,请手动粘贴');
+ });
+ });
+ });
+ }
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
diff --git a/public/static/plugs/ulthon-admin/src/ulthon-admin.06-utils.js b/public/static/plugs/ulthon-admin/src/ulthon-admin.06-utils.js
new file mode 100644
index 0000000..8726bf5
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/src/ulthon-admin.06-utils.js
@@ -0,0 +1,203 @@
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var extGroup = ctx.extGroup;
+
+ admin.getQueryVariable = function (variable, defaultValue) {
+ if (typeof defaultValue == 'undefined') {
+ defaultValue = undefined;
+ }
+
+ var query = window.location.search.substring(1);
+ query = query.replace(/\+/g, ' ');
+ var vars = query.split("&");
+ for (var i = 0; i < vars.length; i++) {
+ var pair = vars[i].split("=");
+ if (pair[0] == variable) {
+ return decodeURIComponent(pair[1]);
+ }
+ }
+ return defaultValue;
+ };
+ admin.dataBrage = null;
+ admin.getDataBrage = function (keys, defaultValue) {
+ if (this.dataBrage == null) {
+ this.dataBrage = JSON.parse($('#data-brage').text());
+ }
+
+ if (typeof defaultValue == 'undefined') {
+ defaultValue = undefined;
+ }
+
+ return admin.dataGet(this.dataBrage, keys, defaultValue);
+ };
+ admin.dataGet = function (data, keys, defaultValue) {
+ return (
+ (!Array.isArray(keys)
+ ? keys.replace(/\[/g, '.').replace(/\]/g, '').split('.')
+ : keys
+ ).reduce((o, k) => (o || {})[k], data) || defaultValue
+ );
+ };
+ admin.getExtGroupName = function (ext) {
+ var groupName = 'file';
+ for (const extGroupName in extGroup) {
+ if (Object.hasOwnProperty.call(extGroup, extGroupName)) {
+ const extGroupList = extGroup[extGroupName];
+ if (extGroupList.indexOf(ext) != -1) {
+ groupName = extGroupName;
+ break;
+ }
+ }
+ }
+
+ return groupName;
+ };
+ //js版empty,判断变量是否为空
+ admin.empty = function (r) {
+ var n, t, e, f = [void 0, null, !1, 0, "", "0"];
+ for (t = 0, e = f.length; t < e; t++) if (r === f[t]) return !0;
+ if ("object" == typeof r) {
+ for (n in r) if (r.hasOwnProperty(n)) return !1;
+ return !0;
+ }
+ return !1;
+ };
+
+ admin.bytes = function (size) {
+ if (size > 0) {
+ const kb = 1024;
+ const unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
+ const i = Math.floor(Math.log(size) / Math.log(kb));
+ const num = (size / Math.pow(kb, i)).toPrecision(3);
+ const u = unit[i];
+ return num + u;
+ }
+ return '0B';
+ };
+ admin.triggerEventReplaceJs = function (name, defaultCallback, replaceCallback) {
+ var code = $('#event-replace-js-' + name).html();
+
+ if (admin.empty(code)) {
+ defaultCallback();
+ } else {
+ replaceCallback(code);
+ }
+ };
+ admin.randdomString = function (len) {
+ len = len || 32;
+ var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
+ var maxPos = $chars.length;
+ var pwd = '';
+ for (var i = 0; i < len; i++) {
+ pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
+ }
+ return pwd;
+ };
+ admin.getPageSetting = function (key, defaultValue, global = false) {
+ if (!global) {
+ key = window.CONFIG.PAGE_KEY_NAME + '_' + key;
+ }
+ return tools.getLocal(key, defaultValue);
+ };
+ admin.setPageSetting = function (key, value, global) {
+ if (!global) {
+ key = window.CONFIG.PAGE_KEY_NAME + '_' + key;
+ }
+ return tools.setLocal(key, value);
+ };
+ /**
+ * 如果不存在则写入,返回有效的值
+ * 如果不存在则返回新的值,否则返回之前设置的值
+ *
+ * @param {string} key
+ * @param {mixed} value
+ * @param {boolean} global
+ * @returns
+ */
+ admin.trySetPageSetting = function (key, value, global) {
+ var oldValue = admin.getPageSetting(key, undefined, global);
+ if (!oldValue) {
+ admin.setPageSetting(key, value, global);
+ return value;
+ }
+
+ return oldValue;
+ };
+ admin.isCurrentIndex = function () {
+ if (window.pageType && window.pageType == 'index') {
+ return true;
+ }
+ return false;
+ };
+ admin.isParentIndex = function () {
+ try {
+ if (window.parent && window.parent.pageType && window.parent.pageType == 'index') {
+ return true;
+ }
+ } catch (e) {
+ return false;
+ }
+ return false;
+ };
+ admin.findIndexPage = function (findCallback, missCallback) {
+ if (!findCallback) {
+ findCallback = function (w) { return w; };
+ }
+ if (!missCallback) {
+ missCallback = function (w) { return w; };
+ }
+ if (this.isCurrentIndex()) {
+ return findCallback(window);
+ }
+
+ var parent = window.parent;
+ if (parent && parent != window) {
+ return parent.ua.findIndexPage(findCallback, missCallback);
+ }
+
+ return missCallback(null);
+ };
+ admin.getCurrentPageId = function () {
+ // pageId就是路径加参数
+ var path = location.pathname;
+ var params = location.search;
+ return path + params;
+ };
+ admin.findPageId = function (tabId) {
+ var iframeWindow;
+ this.findIndexPage(function (window) {
+ // 查找对应的tab内容区域
+ var tabContent = window.layui.$('.layui-tab-content .layui-tab-item[lay-id="' + tabId + '"]');
+ if (tabContent.length > 0) {
+ var iframe = tabContent.find('iframe')[0];
+ if (iframe) {
+ iframeWindow = iframe.contentWindow;
+ }
+ }
+ });
+ return iframeWindow;
+ };
+ admin.getMenuInfoByTabId = function (tabId) {
+ var menuValue = null;
+ this.findIndexPage(function (w) {
+ var menu = w.miniTab.searchMenu(tabId);
+ if (menu) {
+ menuValue = menu;
+ }
+ });
+ return menuValue;
+ };
+ admin.getMenuTitleByTabId = function (tabId, defaultValue) {
+ var menuTitle = defaultValue;
+ var menu = this.getMenuInfoByTabId(tabId);
+
+ if (menu) {
+ menuTitle = menu.title;
+ }
+ return menuTitle;
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
diff --git a/public/static/plugs/ulthon-admin/ua.build.json b/public/static/plugs/ulthon-admin/ua.build.json
new file mode 100644
index 0000000..cd7bf6f
--- /dev/null
+++ b/public/static/plugs/ulthon-admin/ua.build.json
@@ -0,0 +1,11 @@
+{
+ "output": "ulthon-admin.js",
+ "sources": [
+ "src/ulthon-admin.01-core.js",
+ "src/ulthon-admin.02-common.js",
+ "src/ulthon-admin.03-table.js",
+ "src/ulthon-admin.04-listen.js",
+ "src/ulthon-admin.05-api.js",
+ "src/ulthon-admin.06-utils.js"
+ ]
+}
diff --git a/public/static/plugs/ulthon-admin/ulthon-admin.js b/public/static/plugs/ulthon-admin/ulthon-admin.js
index 561bee3..97fa002 100644
--- a/public/static/plugs/ulthon-admin/ulthon-admin.js
+++ b/public/static/plugs/ulthon-admin/ulthon-admin.js
@@ -1,6 +1,7 @@
-
(function () {
+ var ctx = window.__uaCtx || {};
+
window.onInitElemStyle = function () {
miniTheme.renderElemStyle();
@@ -16,10 +17,6 @@
const { createEditor, createToolbar } = window.wangEditor;
- var lastTableWhere = {};
-
- var selectMode, selectConfirmCallback;
-
var form = layui.form,
layer = layui.layer,
laydate = layui.laydate,
@@ -44,7 +41,6 @@
table = layui.table;
-
var extGroup = {
// 图片扩展名数组
'image': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'ico', 'webp', 'svg'],
@@ -86,910 +82,829 @@
init.uploadExts += allExtGroup.join('|');
init.extGroup = extGroup;
- var admin = {
- init: init,
- config: {
- shade: [0.02, '#000'],
- },
- url: function (url) {
+ ctx.createEditor = createEditor;
+ ctx.createToolbar = createToolbar;
+ ctx.layui = {
+ form: form,
+ layer: layer,
+ laydate: laydate,
+ upload: upload,
+ element: element,
+ laytpl: laytpl,
+ util: util,
+ };
+ ctx.init = init;
+ ctx.table = table;
+ ctx.extGroup = extGroup;
+ ctx.lastTableWhere = ctx.lastTableWhere || {};
+ ctx.selectMode = ctx.selectMode;
+ ctx.selectConfirmCallback = ctx.selectConfirmCallback;
- var urlPrefixCheck = ['/', 'http://', 'https://'];
+ window.__uaCtx = ctx;
- for (const index in urlPrefixCheck) {
- if (Object.hasOwnProperty.call(urlPrefixCheck, index)) {
- const prefix = urlPrefixCheck[index];
- if (url.indexOf(prefix) === 0) {
- return url;
- }
+ var admin = window.ua || {};
+ admin.init = init;
+ admin.config = {
+ shade: [0.02, '#000'],
+ };
+ admin.url = function (url) {
+
+ var urlPrefixCheck = ['/', 'http://', 'https://'];
+
+ for (const index in urlPrefixCheck) {
+ if (Object.hasOwnProperty.call(urlPrefixCheck, index)) {
+ const prefix = urlPrefixCheck[index];
+ if (url.indexOf(prefix) === 0) {
+ return url;
}
}
+ }
- return '/' + CONFIG.ADMIN + '/' + url;
- },
- headers: function () {
- return { 'X-CSRF-TOKEN': window.CONFIG.CSRF_TOKEN };
- },
+ return '/' + CONFIG.ADMIN + '/' + url;
+ };
+ admin.headers = function () {
+ return { 'X-CSRF-TOKEN': window.CONFIG.CSRF_TOKEN };
+ };
- checkAuth: function (node, elem) {
- if (node === '1') {
- return true;
+ admin.checkAuth = function (node, elem) {
+ if (node === '1') {
+ return true;
+ }
+ if (CONFIG.IS_SUPER_ADMIN) {
+ return true;
+ }
+ if ($(elem).attr('data-auth-' + node) === '1') {
+ return true;
+ } else {
+ return false;
+ }
+ };
+ admin.parame = function (param, defaultParam) {
+ return param !== undefined ? param : defaultParam;
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
+
+
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var layer = ctx.layui.layer;
+
+ admin.request = {
+ post: function (option, ok, no, ex, complete) {
+ return admin.request.ajax('post', option, ok, no, ex, complete);
+ },
+ get: function (option, ok, no, ex, complete) {
+ return admin.request.ajax('get', option, ok, no, ex, complete);
+ },
+ ajax: function (type, option, ok, no, ex, complete) {
+ type = type || 'get';
+ option.url = option.url || '';
+ option.data = option.data || {};
+ option.prefix = option.prefix || false;
+ option.statusName = option.statusName || 'code';
+ option.statusCode = option.statusCode || 0;
+ ok = ok || function (res) { };
+
+ var originalOk = ok;
+ ok = function (res) {
+ originalOk(res);
+ complete()
}
- if (CONFIG.IS_SUPER_ADMIN) {
- return true;
- }
- if ($(elem).attr('data-auth-' + node) === '1') {
- return true;
+ complete = complete || function () {
+ };
+
+ if (no) {
+ var originalNo = no;
+ no = function (res) {
+ originalNo(res);
+ complete();
+ };
} else {
+ no = function (res) {
+ var msg = res.msg == undefined ? '返回数据格式有误' : res.msg;
+ admin.msg.error(msg);
+ complete();
+ return false;
+ };
+ }
+
+ if (ex) {
+ var originalEx = ex;
+ ex = function (res) {
+ originalEx(res);
+ complete();
+ };
+ } else {
+ ex = function (res) {
+ complete();
+ };
+ }
+ if (option.url == '') {
+ admin.msg.error('请求地址不能为空');
return false;
}
- },
- parame: function (param, defaultParam) {
- return param !== undefined ? param : defaultParam;
- },
- request: {
- post: function (option, ok, no, ex, complete) {
- return admin.request.ajax('post', option, ok, no, ex, complete);
- },
- get: function (option, ok, no, ex, complete) {
- return admin.request.ajax('get', option, ok, no, ex, complete);
- },
- ajax: function (type, option, ok, no, ex, complete) {
- type = type || 'get';
- option.url = option.url || '';
- option.data = option.data || {};
- option.prefix = option.prefix || false;
- option.statusName = option.statusName || 'code';
- option.statusCode = option.statusCode || 0;
- ok = ok || function (res) {};
-
- var originalOk = ok;
- ok = function (res) {
- originalOk(res);
- complete()
- }
- complete = complete || function () {
- };
-
- if (no) {
- var originalNo = no;
- no = function (res) {
- originalNo(res);
- complete();
- };
- } else {
- no = function (res) {
- var msg = res.msg == undefined ? '返回数据格式有误' : res.msg;
- admin.msg.error(msg);
- complete();
- return false;
- };
- }
-
- if (ex) {
- var originalEx = ex;
- ex = function (res) {
- originalEx(res);
- complete();
- };
- } else {
- ex = function (res) {
- complete();
- };
- }
- if (option.url == '') {
- admin.msg.error('请求地址不能为空');
+ if (option.prefix == true) {
+ option.url = admin.url(option.url);
+ }
+ loading.show();
+ $.ajax({
+ url: option.url,
+ type: type,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+ dataType: "json",
+ headers: admin.headers(),
+ data: option.data,
+ timeout: 60000,
+ success: function (res) {
+ loading.hide();
+ if (eval('res.' + option.statusName) == option.statusCode) {
+ return ok(res);
+ } else {
+ return no(res);
+ }
+ },
+ error: function (xhr, textstatus, thrown) {
+ var errorMsg = '';
+ if (xhr.responseJSON.message) {
+ errorMsg = xhr.responseJSON.message;
+ }
+ loading.hide();
+ admin.msg.error('Status:' + xhr.status + ',' + xhr.statusText + ',请稍后再试!
' + errorMsg, function () {
+ ex(this);
+ });
return false;
+ },
+ });
+ }
+ };
+ admin.common = {
+ parseNodeStr: function (node) {
+ var array = node.split('/');
+ $.each(array, function (key, val) {
+ if (key === 0) {
+ val = val.split('.');
+ $.each(val, function (i, v) {
+ val[i] = admin.common.humpToLine(v.replace(v[0], v[0].toLowerCase()));
+ });
+ val = val.join(".");
+ array[key] = val;
}
- if (option.prefix == true) {
- option.url = admin.url(option.url);
+ });
+ node = array.join("/");
+ return node;
+ },
+ lineToHump: function (name) {
+ return name.replace(/\_(\w)/g, function (all, letter) {
+ return letter.toUpperCase();
+ });
+ },
+ humpToLine: function (name) {
+ return name.replace(/([A-Z])/g, "_$1").toLowerCase();
+ },
+ };
+ admin.msg = {
+ // 成功消息
+ success: function (msg, callback) {
+ if (callback === undefined) {
+ callback = function () {
+ };
+ }
+ var index = layer.msg(msg, { icon: 1, shade: admin.config.shade, scrollbar: false, time: 800, shadeClose: true }, callback);
+ return index;
+ },
+ // 失败消息
+ error: function (msg, callback) {
+ if (callback === undefined) {
+ callback = function () {
+ };
+ }
+ var index = layer.msg(msg, { icon: 2, shade: admin.config.shade, scrollbar: false, time: -1, shadeClose: true }, callback);
+ return index;
+ },
+ // 警告消息框
+ alert: function (msg, callback) {
+ var index = layer.alert(msg, { end: callback, scrollbar: false });
+ return index;
+ },
+ // 对话框
+ confirm: function (msg, ok, no) {
+ var index = layer.confirm(msg, { title: '操作确认', btn: ['确认', '取消'] }, function () {
+ typeof ok === 'function' && ok.call(this);
+ }, function () {
+ typeof no === 'function' && no.call(this);
+ });
+ return index;
+ },
+ // 消息提示
+ tips: function (msg, time, callback) {
+ var index = layer.msg(msg, { time: (time || 0.8) * 1000, shade: this.shade, end: callback, shadeClose: true });
+ return index;
+ },
+ // 加载中提示
+ loading: function (msg, callback) {
+ var index = msg ? layer.msg(msg, { icon: 16, scrollbar: false, shade: this.shade, time: 0, end: callback }) : layer.load(2, { time: 0, scrollbar: false, shade: this.shade, end: callback });
+ return index;
+ },
+ // 关闭消息框
+ close: function (index) {
+ return layer.close(index);
+ }
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
+
+
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var init = ctx.init;
+ var table = ctx.table;
+ var form = ctx.layui.form;
+ var layer = ctx.layui.layer;
+ var lastTableWhere = ctx.lastTableWhere || {};
+ var selectMode = ctx.selectMode;
+ var selectConfirmCallback = ctx.selectConfirmCallback;
+
+ ctx.lastTableWhere = lastTableWhere;
+
+ admin.table = {
+ render: function (options) {
+ options.init = options.init || init;
+ options.modifyReload = admin.parame(options.modifyReload, true);
+ options.elem = options.elem || options.init.tableElem;
+ options.id = options.id || options.init.tableRenderId;
+ options.scrollPos = options.scrollPos || 'fixed';
+ options.layFilter = options.id + '_LayFilter';
+ options.url = options.url || admin.url(options.init.indexUrl);
+ options.headers = admin.headers();
+ options.page = admin.parame(options.page, true);
+ options.search = admin.parame(options.search, true);
+ options.layout = admin.parame(options.layout, true);
+ options.layoutList = admin.parame(options.layoutList,
+ [
+ 'table',
+ 'card',
+ {
+ name: 'usercard',
+ // 优先级1
+ tplFunction() {
+
+ },
+ // 优先级3
+ tplVue() {
+
+ },
+ // 优先级2
+ tplLay() {
+
+ },
+ // 优先级4
+ tplLayId: '',
+ // 优先级5
+ tplVueId: ''
+ }
+ ]
+ );
+ options.layoutDefault = admin.parame(options.layoutDefault, true);
+ options.skin = options.skin || 'line';
+ options.autoSort = options.autoSort || false;
+ options.limit = options.limit || 15;
+ options.limits = options.limits || [10, 15, 20, 25, 50, 100];
+ options.cols = options.cols || [];
+ options.rowDisableCallback = options.rowDisableCallback || null;
+
+ var defaultToolbar = ['filter', 'print'];
+ if (options.layout === true) {
+ defaultToolbar.push({
+ title: '视图',
+ layEvent: 'TABLE_LAYOUT',
+ icon: 'layui-icon-template-1',
+ extend: 'data-table-id="' + options.id + '"'
+ });
+
+ if (options.layoutDefault === true) {
+ // 自动判断,手机端默认card,电脑端默认table
+ if (admin.checkMobile()) {
+ options.layoutDefault = 'card';
+ } else {
+ options.layoutDefault = 'table';
+ }
}
- loading.show();
- $.ajax({
- url: option.url,
- type: type,
- contentType: "application/x-www-form-urlencoded; charset=UTF-8",
- dataType: "json",
- headers: admin.headers(),
- data: option.data,
- timeout: 60000,
- success: function (res) {
- loading.hide();
- if (eval('res.' + option.statusName) == option.statusCode) {
- return ok(res);
- } else {
- return no(res);
- }
- },
- error: function (xhr, textstatus, thrown) {
- var errorMsg = '';
- if (xhr.responseJSON.message) {
- errorMsg = xhr.responseJSON.message;
- }
- loading.hide();
- admin.msg.error('Status:' + xhr.status + ',' + xhr.statusText + ',请稍后再试!
' + errorMsg, function () {
- ex(this);
- });
- return false;
- },
+
+ options.layoutDefault = admin.trySetPageSetting('table-layout-default', options.layoutDefault);
+
+
+ }
+
+ if (options.search) {
+ defaultToolbar.push({
+ title: '搜索',
+ layEvent: 'TABLE_SEARCH',
+ icon: 'layui-icon-search',
+ extend: 'data-table-id="' + options.id + '"'
});
}
- },
- common: {
- parseNodeStr: function (node) {
- var array = node.split('/');
- $.each(array, function (key, val) {
- if (key === 0) {
- val = val.split('.');
- $.each(val, function (i, v) {
- val[i] = admin.common.humpToLine(v.replace(v[0], v[0].toLowerCase()));
- });
- val = val.join(".");
- array[key] = val;
- }
- });
- node = array.join("/");
- return node;
- },
- lineToHump: function (name) {
- return name.replace(/\_(\w)/g, function (all, letter) {
- return letter.toUpperCase();
- });
- },
- humpToLine: function (name) {
- return name.replace(/([A-Z])/g, "_$1").toLowerCase();
- },
- },
- msg: {
- // 成功消息
- success: function (msg, callback) {
- if (callback === undefined) {
- callback = function () {
- };
- }
- var index = layer.msg(msg, { icon: 1, shade: admin.config.shade, scrollbar: false, time: 800, shadeClose: true }, callback);
- return index;
- },
- // 失败消息
- error: function (msg, callback) {
- if (callback === undefined) {
- callback = function () {
- };
- }
- var index = layer.msg(msg, { icon: 2, shade: admin.config.shade, scrollbar: false, time: -1, shadeClose: true }, callback);
- return index;
- },
- // 警告消息框
- alert: function (msg, callback) {
- var index = layer.alert(msg, { end: callback, scrollbar: false });
- return index;
- },
- // 对话框
- confirm: function (msg, ok, no) {
- var index = layer.confirm(msg, { title: '操作确认', btn: ['确认', '取消'] }, function () {
- typeof ok === 'function' && ok.call(this);
- }, function () {
- typeof no === 'function' && no.call(this);
- });
- return index;
- },
- // 消息提示
- tips: function (msg, time, callback) {
- var index = layer.msg(msg, { time: (time || 0.8) * 1000, shade: this.shade, end: callback, shadeClose: true });
- return index;
- },
- // 加载中提示
- loading: function (msg, callback) {
- var index = msg ? layer.msg(msg, { icon: 16, scrollbar: false, shade: this.shade, time: 0, end: callback }) : layer.load(2, { time: 0, scrollbar: false, shade: this.shade, end: callback });
- return index;
- },
- // 关闭消息框
- close: function (index) {
- return layer.close(index);
+ if (options.defaultToolbar === undefined) {
+ options.defaultToolbar = defaultToolbar;
}
- },
- table: {
- render: function (options) {
- options.init = options.init || init;
- options.modifyReload = admin.parame(options.modifyReload, true);
- options.elem = options.elem || options.init.tableElem;
- options.id = options.id || options.init.tableRenderId;
- options.scrollPos = options.scrollPos || 'fixed';
- options.layFilter = options.id + '_LayFilter';
- options.url = options.url || admin.url(options.init.indexUrl);
- options.headers = admin.headers();
- options.page = admin.parame(options.page, true);
- options.search = admin.parame(options.search, true);
- options.layout = admin.parame(options.layout, true);
- options.layoutList = admin.parame(options.layoutList,
- [
- 'table',
- 'card',
- {
- name: 'usercard',
- // 优先级1
- tplFunction() {
-
- },
- // 优先级3
- tplVue() {
-
- },
- // 优先级2
- tplLay() {
-
- },
- // 优先级4
- tplLayId: '',
- // 优先级5
- tplVueId: ''
- }
- ]
- );
- options.layoutDefault = admin.parame(options.layoutDefault, true);
- options.skin = options.skin || 'line';
- options.autoSort = options.autoSort || false;
- options.limit = options.limit || 15;
- options.limits = options.limits || [10, 15, 20, 25, 50, 100];
- options.cols = options.cols || [];
- options.rowDisableCallback = options.rowDisableCallback || null;
-
- var defaultToolbar = ['filter', 'print'];
- if (options.layout === true) {
- defaultToolbar.push({
- title: '视图',
- layEvent: 'TABLE_LAYOUT',
- icon: 'layui-icon-template-1',
- extend: 'data-table-id="' + options.id + '"'
- });
-
- if (options.layoutDefault === true) {
- // 自动判断,手机端默认card,电脑端默认table
- if (admin.checkMobile()) {
- options.layoutDefault = 'card';
- } else {
- options.layoutDefault = 'table';
- }
- }
-
- options.layoutDefault = admin.trySetPageSetting('table-layout-default', options.layoutDefault);
- }
+ var optionBefore = function () { };
+ if (options.before != undefined) {
+ optionBefore = options.before;
+ }
+ options.before = function (tableIns) {
+ optionBefore(tableIns);
+ };
- if (options.search) {
- defaultToolbar.push({
- title: '搜索',
- layEvent: 'TABLE_SEARCH',
- icon: 'layui-icon-search',
- extend: 'data-table-id="' + options.id + '"'
+ var optionDone = function () { };
+ if (options.done != undefined) {
+ optionDone = options.done;
+ }
+ options.done = function (res, curr, count) {
+ optionDone(res, curr, count);
+
+ // 监听表格内的复制组件
+ admin.api.copyText('[lay-id=' + options.id + ']');
+ };
+
+ /**
+ * 为空时认为自己是普通状态,否则是单选、多选、子页面,此时添加等默认行为走弹框而不是新标签页
+ */
+ selectMode = admin.getQueryVariable("select_mode");
+
+ selectConfirmCallback = admin.getQueryVariable('select_confirm_callback', 'onTableDataConfirm');
+
+ ctx.selectMode = selectMode;
+ ctx.selectConfirmCallback = selectConfirmCallback;
+
+ if (selectMode == 'checkbox') {
+ if (options.cols[0][0].type == 'radio') {
+ options.cols[0][0].type = 'checkbox';
+ } else if (options.cols[0][0].type != 'checkbox') {
+ options.cols[0].unshift({
+ type: 'checkbox'
});
}
- if (options.defaultToolbar === undefined) {
- options.defaultToolbar = defaultToolbar;
+ } else if (selectMode == 'radio') {
+ if (options.cols[0][0].type == 'checkbox') {
+ options.cols[0][0].type = 'radio';
+
+ } else if (options.cols[0][0].type != 'radio') {
+ options.cols[0].unshift({
+ type: 'radio'
+ });
+
}
-
-
- var optionBefore = function () { };
- if (options.before != undefined) {
- optionBefore = options.before;
- }
- options.before = function (tableIns) {
- optionBefore(tableIns);
- };
-
- var optionDone = function () { };
- if (options.done != undefined) {
- optionDone = options.done;
- }
- options.done = function (res, curr, count) {
- optionDone(res, curr, count);
-
- // 监听表格内的复制组件
- admin.api.copyText('[lay-id=' + options.id + ']');
- };
-
- /**
- * 为空时认为自己是普通状态,否则是单选、多选、子页面,此时添加等默认行为走弹框而不是新标签页
- */
- selectMode = admin.getQueryVariable("select_mode");
-
- selectConfirmCallback = admin.getQueryVariable('select_confirm_callback', 'onTableDataConfirm');
-
- if (selectMode == 'checkbox') {
- if (options.cols[0][0].type == 'radio') {
- options.cols[0][0].type = 'checkbox';
- } else if (options.cols[0][0].type != 'checkbox') {
- options.cols[0].unshift({
- type: 'checkbox'
- });
- }
- } else if (selectMode == 'radio') {
- if (options.cols[0][0].type == 'checkbox') {
- options.cols[0][0].type = 'radio';
-
- } else if (options.cols[0][0].type != 'radio') {
- options.cols[0].unshift({
- type: 'radio'
- });
-
- }
- } else {
- if(!admin.isParentIndex()){
- selectMode = 'childPage'
- }
+ } else {
+ if (!admin.isParentIndex()) {
+ selectMode = 'childPage'
+ ctx.selectMode = selectMode;
}
+ }
- // 判断元素对象是否有嵌套的
- options.cols = admin.table.formatCols(options.cols, options.init);
+ // 判断元素对象是否有嵌套的
+ options.cols = admin.table.formatCols(options.cols, options.init);
- // 初始化表格lay-filter
- $(options.elem).attr('lay-filter', options.layFilter);
+ // 初始化表格lay-filter
+ $(options.elem).attr('lay-filter', options.layFilter);
- // 初始化表格搜索
- if (options.search === true) {
- options = admin.table.renderSearch(options.cols, options.elem, options.id, options);
- }
+ // 初始化表格搜索
+ if (options.search === true) {
+ options = admin.table.renderSearch(options.cols, options.elem, options.id, options);
+ }
- // 初始化模板切换
- if (options.layout === true) {
+ // 初始化模板切换
+ if (options.layout === true) {
- options = admin.table.renderLayout(options);
- }
+ options = admin.table.renderLayout(options);
+ }
- // 初始化表格左上方工具栏
- options.toolbar = options.toolbar || ['refresh', 'add', 'delete', 'export'];
+ // 初始化表格左上方工具栏
+ options.toolbar = options.toolbar || ['refresh', 'add', 'delete', 'export'];
+ if (selectMode == 'checkbox' || selectMode == 'radio') {
+ options.toolbar.unshift('selectConfirm');
+
+ options.height = 'full-85';
+ }
+
+ if (options.init.formFullScreen == true) {
+ options.init.formFullScreen = 'true';
+ } else {
+ options.init.formFullScreen = 'false';
+ }
+
+ options.toolbar = admin.table.renderToolbar(options.toolbar, options.elem, options.id, options.init);
+
+ // 判断是否有操作列表权限
+ options.cols = admin.table.renderOperat(options.cols, options.elem);
+
+ // 判断是否有操作列表权限
+ options.cols = admin.table.renderTrueHide(options.cols, options);
+
+
+ var parseData = function (res) { return res; };
+
+ if (typeof options.parseData === 'function') {
+ parseData = options.parseData;
+ }
+
+ options.parseData = function (res) {
+
+ // 初始化已经选择的值
if (selectMode == 'checkbox' || selectMode == 'radio') {
- options.toolbar.unshift('selectConfirm');
+ if (typeof options.rowDisableCallback == 'function') {
+ for (let index = 0; index < res.data.length; index++) {
+ const dataItem = res.data[index];
- options.height = 'full-85';
+ var rowDisableResult = options.rowDisableCallback(dataItem);
+ if (rowDisableResult === false || rowDisableResult === true) {
+ res.data[index].LAY_DISABLED = rowDisableResult;
+ }
+ }
+ }
+
+ var selectedIds = admin.getQueryVariable('selectedIds', '');
+
+ if (selectedIds.length > 0) {
+ var selectedIdArr = selectedIds.split(',');
+
+ for (let index = 0; index < res.data.length; index++) {
+ const dataItem = res.data[index];
+
+ if (selectedIdArr.indexOf(dataItem.id.toString()) > -1) {
+ res.data[index].LAY_DISABLED = true;
+ }
+ }
+ }
}
- if (options.init.formFullScreen == true) {
- options.init.formFullScreen = 'true';
+ res = parseData(res);
+ return res;
+ };
+
+
+ // 初始化表格
+ var newTable = table.render(options);
+
+ // 监听表格搜索开关显示
+ admin.table.listenToolbar(options.layFilter, options.id);
+
+ // 监听表格瓶排序
+ admin.table.listenTableSort(options);
+
+ // 监听表格开关切换
+ admin.table.renderSwitch(options.cols, options.init, options.id, options.modifyReload);
+
+ // 监听表格开关切换
+ admin.table.listenEdit(options.init, options.layFilter, options.id, options.modifyReload);
+
+ // 监听导出事件
+ admin.table.listenExport(options);
+
+ // 监听表格选择器
+ admin.table.listenTableSelectConfirm(options);
+
+ return newTable;
+ },
+ renderToolbar: function (data, elem, tableId, init) {
+ data = data || [];
+ var toolbarHtml = '';
+ $.each(data, function (i, v) {
+ if (v === 'refresh') {
+ toolbarHtml += ' \n';
+ } else if (v === 'add') {
+ if (admin.checkAuth('add', elem)) {
+ if (selectMode) {
+ toolbarHtml += '\n';
+ } else {
+ toolbarHtml += '\n';
+ }
+ }
+ } else if (v === 'delete') {
+ if (admin.checkAuth('delete', elem)) {
+ toolbarHtml += '\n';
+ }
+ } else if (v === 'export') {
+ if (admin.checkAuth('export', elem)) {
+ toolbarHtml += '\n';
+ }
+ } else if (v === 'selectConfirm') {
+ toolbarHtml += '\n';
+ } else if (typeof v === "object") {
+ $.each(v, function (ii, vv) {
+ vv.class = vv.class || '';
+ vv.icon = vv.icon || '';
+ vv.auth = vv.auth || 'add';
+ vv.url = vv.url || '';
+ vv.method = vv.method || 'open';
+ vv.title = vv.title || vv.text;
+ vv.text = vv.text || vv.title;
+ vv.extend = vv.extend || '';
+ vv.checkbox = vv.checkbox || false;
+ if (admin.checkAuth(vv.auth, elem)) {
+ toolbarHtml += admin.table.buildToolbarHtml(vv, tableId);
+ }
+ });
+ }
+ });
+ return '' + toolbarHtml + '
';
+ },
+ renderSearch: function (cols, elem, tableId, options) {
+ // TODO 只初始化第一个table搜索字段,如果存在多个(绝少数需求),得自己去扩展
+ cols = cols[0] || {};
+ var newCols = [];
+ var formHtml = '';
+ var tabSetting = {};
+ var formatFilter = {},
+ formatOp = {};
+ $.each(cols, function (i, d) {
+ d.field = d.field || false;
+ d.fieldAlias = admin.parame(d.fieldAlias, d.field);
+ d.title = d.title || d.field || '';
+ d.selectList = d.selectList || {};
+ d.search = admin.parame(d.search, true);
+ d.searchTip = d.searchTip || '请输入' + d.title || '';
+ d.searchValue = d.searchValue || undefined;
+ d.searchHide = d.searchHide || '';
+ d.defaultSearchValue = d.defaultSearchValue;
+ d.searchOp = d.searchOp || '%*%';
+ d.timeType = d.timeType || 'datetime';
+
+ d.elemIdName = d.fieldAlias;
+
+ var a = '';
+ var b = '';
+
+ if (typeof d.fieldAlias == 'string') {
+
+ if (d.fieldAlias.indexOf('[') == 0) {
+
+ var fieldPlusArr = d.fieldAlias.replace('[').split(']');
+
+ d.elemIdName = fieldPlusArr.join('-');
+ }
+
+ d.elemIdName = d.elemIdName.replace('.', '-');
+ }
+
+
+ if (d.defaultSearchValue !== undefined) {
+ if (!d.searchValue || d.searchValue.length == 0) {
+ d.searchValue = d.defaultSearchValue;
+ }
} else {
- options.init.formFullScreen = 'false';
- }
-
- options.toolbar = admin.table.renderToolbar(options.toolbar, options.elem, options.id, options.init);
-
- // 判断是否有操作列表权限
- options.cols = admin.table.renderOperat(options.cols, options.elem);
-
- // 判断是否有操作列表权限
- options.cols = admin.table.renderTrueHide(options.cols, options);
-
-
- var parseData = function (res) { return res; };
-
- if (typeof options.parseData === 'function') {
- parseData = options.parseData;
- }
-
- options.parseData = function (res) {
-
- // 初始化已经选择的值
- if (selectMode == 'checkbox' || selectMode == 'radio') {
- if (typeof options.rowDisableCallback == 'function') {
- for (let index = 0; index < res.data.length; index++) {
- const dataItem = res.data[index];
-
- var rowDisableResult = options.rowDisableCallback(dataItem);
- if (rowDisableResult === false || rowDisableResult === true) {
- res.data[index].LAY_DISABLED = rowDisableResult;
- }
- }
- }
-
- var selectedIds = admin.getQueryVariable('selectedIds', '');
-
- if (selectedIds.length > 0) {
- var selectedIdArr = selectedIds.split(',');
-
- for (let index = 0; index < res.data.length; index++) {
- const dataItem = res.data[index];
-
- if (selectedIdArr.indexOf(dataItem.id.toString()) > -1) {
- res.data[index].LAY_DISABLED = true;
- }
- }
- }
- }
-
- res = parseData(res);
- return res;
- };
-
-
- // 初始化表格
- var newTable = table.render(options);
-
- // 监听表格搜索开关显示
- admin.table.listenToolbar(options.layFilter, options.id);
-
- // 监听表格瓶排序
- admin.table.listenTableSort(options);
-
- // 监听表格开关切换
- admin.table.renderSwitch(options.cols, options.init, options.id, options.modifyReload);
-
- // 监听表格开关切换
- admin.table.listenEdit(options.init, options.layFilter, options.id, options.modifyReload);
-
- // 监听导出事件
- admin.table.listenExport(options);
-
- // 监听表格选择器
- admin.table.listenTableSelectConfirm(options);
-
- return newTable;
- },
- renderToolbar: function (data, elem, tableId, init) {
- data = data || [];
- var toolbarHtml = '';
- $.each(data, function (i, v) {
- if (v === 'refresh') {
- toolbarHtml += ' \n';
- } else if (v === 'add') {
- if (admin.checkAuth('add', elem)) {
- if(selectMode){
- toolbarHtml += '\n';
- }else{
- toolbarHtml += '\n';
- }
- }
- } else if (v === 'delete') {
- if (admin.checkAuth('delete', elem)) {
- toolbarHtml += '\n';
- }
- } else if (v === 'export') {
- if (admin.checkAuth('export', elem)) {
- toolbarHtml += '\n';
- }
- } else if (v === 'selectConfirm') {
- toolbarHtml += '\n';
- } else if (typeof v === "object") {
- $.each(v, function (ii, vv) {
- vv.class = vv.class || '';
- vv.icon = vv.icon || '';
- vv.auth = vv.auth || 'add';
- vv.url = vv.url || '';
- vv.method = vv.method || 'open';
- vv.title = vv.title || vv.text;
- vv.text = vv.text || vv.title;
- vv.extend = vv.extend || '';
- vv.checkbox = vv.checkbox || false;
- if (admin.checkAuth(vv.auth, elem)) {
- toolbarHtml += admin.table.buildToolbarHtml(vv, tableId);
- }
- });
- }
- });
- return '' + toolbarHtml + '
';
- },
- renderSearch: function (cols, elem, tableId, options) {
- // TODO 只初始化第一个table搜索字段,如果存在多个(绝少数需求),得自己去扩展
- cols = cols[0] || {};
- var newCols = [];
- var formHtml = '';
- var tabSetting = {};
- var formatFilter = {},
- formatOp = {};
- $.each(cols, function (i, d) {
- d.field = d.field || false;
- d.fieldAlias = admin.parame(d.fieldAlias, d.field);
- d.title = d.title || d.field || '';
- d.selectList = d.selectList || {};
- d.search = admin.parame(d.search, true);
- d.searchTip = d.searchTip || '请输入' + d.title || '';
- d.searchValue = d.searchValue || undefined;
- d.searchHide = d.searchHide || '';
- d.defaultSearchValue = d.defaultSearchValue;
- d.searchOp = d.searchOp || '%*%';
- d.timeType = d.timeType || 'datetime';
-
- d.elemIdName = d.fieldAlias;
-
- var a = '';
- var b = '';
-
- if (typeof d.fieldAlias == 'string') {
-
- if (d.fieldAlias.indexOf('[') == 0) {
-
- var fieldPlusArr = d.fieldAlias.replace('[').split(']');
-
- d.elemIdName = fieldPlusArr.join('-');
- }
-
- d.elemIdName = d.elemIdName.replace('.', '-');
- }
-
-
- if (d.defaultSearchValue !== undefined) {
- if (!d.searchValue || d.searchValue.length == 0) {
+ if (d.field) {
+ d.defaultSearchValue = admin.getQueryVariable(d.field);
+ if (d.defaultSearchValue != undefined) {
d.searchValue = d.defaultSearchValue;
}
+ }
+ }
+
+ if (d.searchValue !== undefined) {
+
+ if (d.search == 'number_limit') {
+ var paramsArr = d.searchValue.split(',');
+
+ a = paramsArr[0];
+ b = paramsArr[1];
+
+ if (a) {
+ formatFilter['[' + d.field + ']min'] = a;
+ formatOp['[' + d.field + ']min'] = 'min';
+ }
+
+ if (b) {
+ formatFilter['[' + d.field + ']max'] = b;
+ formatOp['[' + d.field + ']max'] = 'max';
+ }
+ } else if (d.search == 'time_limit') {
+ var paramsArr = d.searchValue.split(',');
+
+ a = paramsArr[0];
+ b = paramsArr[1];
+
+ if (a) {
+ formatFilter['[' + d.field + ']min_date'] = a;
+ formatOp['[' + d.field + ']min_date'] = 'min_date';
+ }
+
+ if (b) {
+ formatFilter['[' + d.field + ']max_date'] = b;
+ formatOp['[' + d.field + ']max_date'] = 'max_date';
+ }
} else {
- if (d.field) {
- d.defaultSearchValue = admin.getQueryVariable(d.field);
- if (d.defaultSearchValue != undefined) {
- d.searchValue = d.defaultSearchValue;
- }
- }
+ formatFilter[d.field] = d.searchValue;
+ formatOp[d.field] = d.searchOp;
}
+ }
- if (d.searchValue !== undefined) {
+ var formSearchHideClass = '';
+ if (d.searchHide == true) {
+ formSearchHideClass = ' layui-hide';
+ }
- if (d.search == 'number_limit') {
- var paramsArr = d.searchValue.split(',');
-
- a = paramsArr[0];
- b = paramsArr[1];
-
- if (a) {
- formatFilter['[' + d.field + ']min'] = a;
- formatOp['[' + d.field + ']min'] = 'min';
- }
-
- if (b) {
- formatFilter['[' + d.field + ']max'] = b;
- formatOp['[' + d.field + ']max'] = 'max';
- }
- } else if (d.search == 'time_limit') {
- var paramsArr = d.searchValue.split(',');
-
- a = paramsArr[0];
- b = paramsArr[1];
-
- if (a) {
- formatFilter['[' + d.field + ']min_date'] = a;
- formatOp['[' + d.field + ']min_date'] = 'min_date';
- }
-
- if (b) {
- formatFilter['[' + d.field + ']max_date'] = b;
- formatOp['[' + d.field + ']max_date'] = 'max_date';
- }
+ if (d.search == true || d.search == 'text') {
+ formHtml += '\n';
+ } else if (d.search == 'select') {
+ formHtml += '\n';
+ } else if (d.search == 'time_limit') {
+ if (d.timeType == undefined) {
+ d.timeType = 'datetime';
}
+ formHtml += '\n';
+ tabSetting[tableId + '_' + d.field + '_min'] = {
+ elem: '#c-' + d.elemIdName + '-min',
+ type: d.timeType,
+ range: false,
+ };
+ tabSetting[tableId + '_' + d.field + '_max'] = {
+ elem: '#c-' + d.elemIdName + '-max',
+ type: d.timeType,
+ range: false,
+ };
- var formSearchHideClass = '';
+ } else if (d.search == 'number_limit') {
+ formHtml += '\n';
+ }
- if (d.searchHide) {
- formSearchHideClass = ' search-hide-item';
- }
+ if (d.search !== false) {
+ newCols.push(d);
+ }
+ });
+ var html = '';
+ html += '\n';
- if (d.searchValue === undefined) {
- d.searchValue = '';
- }
+ if ($(elem).prev().hasClass("search-form")) {
+ $(elem).prev().remove();
+ }
+ $(elem).before(html);
- if (d.field !== false) {
- if (d.search !== false) {
- switch (d.search) {
- case true:
- formHtml += '\t';
- break;
- case 'select':
- d.searchOp = '=';
- var selectHtml = '';
+ form.render();
- if (d.tab) {
- tabSetting.field = d.field;
- tabSetting.elemIdName = d.elemIdName;
- tabSetting.list = d.selectList;
- tabSetting.index = -1;
- }
+ $.each(tabSetting, function (key, val) {
+ laydate.render(val);
+ });
- var selectListIndex = 0;
- $.each(d.selectList, function (sI, sV) {
- var selected = '';
- if (sI === d.searchValue) {
- selected = 'selected=""';
- if (d.tab) {
- tabSetting.index = selectListIndex;
- }
- }
- selectHtml += '/n';
- selectListIndex++;
- });
- if (d.tab) {
- formHtml += '';
- break;
- }
- formHtml += '\t';
- break;
- case 'range':
- d.searchOp = 'range';
- formHtml += '\t';
- break;
- case 'time':
- d.searchOp = '=';
- formHtml += '\t';
- break;
- case 'time_limit':
- d.searchOp = '=';
- formHtml += '\t';
- break;
- case 'number_limit':
- d.searchOp = '=';
- formHtml += '\t';
- break;
- }
- newCols.push(d);
- } else {
- // TODO:支持更多种类型的初始化,比如number_limit、time_limit
- formHtml += '';
- }
+ // 监听表单提交事件
+ form.on('submit(' + tableId + '_filter_form_submit)', function (data) {
+ var dataField = data.field;
+ var formatFilter = {},
+ formatOp = {};
+ $.each(dataField, function (key, val) {
+ if (val !== '') {
+ formatFilter[key] = val;
+
+ var elemId = admin.table.renderSearchFormItemElementId(key);
+
+ var op = $('#c-' + elemId).attr('data-search-op');
+ op = op || '%*%';
+ formatOp[key] = op;
}
});
-
- if (tabSetting.field) {
- var tabId = 'tabFieldset_' + tableId;
- $(elem).before('');
- var header = [
- {
- title: '全部',
- key: '',
- }
- ];
- for (const tabSettingListKey in tabSetting.list) {
- if (Object.prototype.hasOwnProperty.call(tabSetting.list, tabSettingListKey)) {
- const tabItem = tabSetting.list[tabSettingListKey];
- header.push({
- title: tabItem,
- key: tabSettingListKey,
- });
- }
- }
- layui.tabs.render({
- elem: '#' + tabId,
- header: header,
- index: tabSetting.index + 1,
- });
- layui.tabs.on('afterChange(' + tabId + ')', function (data) {
- var value = $(data.thisHeaderItem).attr('lay-key');
- $('#c-' + tabSetting.elemIdName).val(value);
- $('[lay-filter="' + tableId + '_filter"]').trigger('click');
-
- });
- }
-
- if (formHtml !== '') {
-
- $(elem).before('');
-
- admin.table.listenTableSearch(tableId);
-
- // 初始化form表单
- form.render();
- $.each(newCols, function (ncI, ncV) {
- if (ncV.search === 'range') {
- laydate.render({ range: true, type: ncV.timeType, elem: '[name="' + ncV.fieldAlias + '"]' });
- }
- if (ncV.search === 'time') {
- laydate.render({ type: ncV.timeType, elem: '[name="' + ncV.fieldAlias + '"]' });
- }
- if (ncV.search === 'time_limit') {
- laydate.render({ type: ncV.timeType, elem: '[name="[' + ncV.fieldAlias + ']min_date"]' });
- laydate.render({ type: ncV.timeType, elem: '[name="[' + ncV.fieldAlias + ']max_date"]' });
- }
- });
- }
-
- options.where = {
+ var where = {
filter: JSON.stringify(formatFilter),
op: JSON.stringify(formatOp)
};
+ lastTableWhere[tableId] = where;
+ table.reloadData(tableId, {
+ page: {
+ curr: 1
+ }
+ , where: where
+ }, 'data');
+ return false;
+ });
+ return options;
+ },
+ renderLayout: function (options) {
+ var tableId = options.id;
+ var layoutList = options.layoutList;
+ var layoutDefault = options.layoutDefault;
+ var layoutElemIdName = '#layout-' + tableId;
+ var layoulElem = null;
+ if (!Array.isArray(layoutList)) {
+ layoutList = ['table', 'card'];
+ }
+ options.layoutList = layoutList;
- lastTableWhere[tableId] = options.where;
+ var toolbarLayoutElem = $('[lay-table-id="' + tableId + '"]').find('[lay-event="TABLE_LAYOUT"]');
+ if (toolbarLayoutElem.length == 0) {
+ toolbarLayoutElem = $('[lay-filter="' + tableId + '_LayFilter"]').find('[lay-event="TABLE_LAYOUT"]');
+ }
- return options;
- },
- renderLayout: function (options) {
+ options.done = function (res, curr, count) {
+ if (options.before) {
+ options.before(options);
+ }
+ var layuiTableElemName = '#layui-table-' + tableId;
+ var layuiTableElem = $(layuiTableElemName);
- if (!options.layoutList) {
- return options;
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+ var layoutList = options.layoutList || [];
+
+ if (currentLayout != 'table') {
+ for (let index = 0; index < layoutList.length; index++) {
+ const item = layoutList[index];
+ if (item.name == currentLayout) {
+ currentLayout = item.name;
+ break;
+ }
+ }
}
- var tableId = options.id;
+ if (currentLayout != 'table') {
+ layuiTableElem.find('.layui-table-box').hide();
+ }
- var layuiTableElemName = '[lay-table-id="' + tableId + '"]';
- var elem = options.elem;
-
- // 初始化参数
- options.layoutList = options.layoutList.map((item) => {
- if (item == 'table') {
- return {
- name: 'table',
- icon: 'layui-icon layui-icon-table',
- title: '默认表格',
-
- };
- } else if (item == 'card') {
- return {
- name: 'card',
- title: '默认卡片',
- icon: 'layui-icon layui-icon-form',
- tplFunction: function (options, res, container) {
- console.log('card func');
-
- console.log(options);
- console.log(res);
- console.log(container);
-
- var baseItem = `
- `;
- var baseDataItem = `
- `;
-
- res.data.forEach(row => {
-
- var rowItem = $.extend(true, {}, row);
-
- var baseElem = $(baseItem).appendTo(container);
-
- if (options.cols[0][0].type == 'checkbox' || options.cols[0[0]].type == 'radio') {
- $('')
- .appendTo(baseElem.find('.header').find('.plus'));
-
- }
-
- rowItem.LAY_COL = $.extend(true, {}, options.cols[0][1]);
- baseElem.find('.header').find('.main').find('span').html(
- options.cols[0][1].templet(rowItem)
- );
-
- options.cols[0].forEach(LAY_COL => {
- var dataItem = $.extend(true, {}, row);
- dataItem.LAY_COL = $.extend(true, {}, LAY_COL);
- if (LAY_COL.type == 'checkbox' || LAY_COL.type == 'radio') {
- return;
- }
-
- if (LAY_COL.templet == ua.table.tool) {
- // 暂时隐藏按钮
- // baseElem.find('.footer .plus').html(dataItem.LAY_COL.templet(dataItem));
- return;
- }
-
- if (LAY_COL.field == 'create_time') {
- baseElem.find('.footer .main').html(dataItem.LAY_COL.templet(dataItem));
- return;
- }
-
- var baseDataItemElem = $(baseDataItem).appendTo(baseElem.find('.body .main'));
- baseDataItemElem.find('.item-title').html(
- dataItem.LAY_COL.title + ':'
- );
- baseDataItemElem.find('.item-value').html(
- dataItem.LAY_COL.templet(dataItem)
- );
- });
-
- });
-
- return '';
- }
- };
- } else {
- if (item.icon == undefined) {
- item.icon = 'layui-icon layui-icon-component';
- }
- if (item.title == undefined) {
- item.title = item.name;
- }
+ if (currentLayout != 'table') {
+ if (!layuiTableElem.find('.layui-table-custom.layui-table-custom-' + currentLayout).length) {
+ layuiTableElem.find('.layui-table-box').before('');
+ }
+ }
+
+ layoutList.forEach((item) => {
+ if (item.name == 'table') {
+ layuiTableElem.find('.layui-table-box').hide();
+ } else {
+ layuiTableElem.find('.layui-table-custom.layui-table-custom-' + item.name).hide();
}
- return item;
});
- var optionBefore = options.before;
- options.before = function (res, curr, count) {
- optionBefore(res, curr, count);
- console.log('layout before fun');
-
- var currentLayout = admin.getPageSetting('table-layout-default', 'table');
- // 隐藏所有数据体内容
- var layuiTableElem = $(layuiTableElemName);
-
- options.layoutList.forEach((item) => {
- if (item.name == 'table') {
- layuiTableElem.find('.layui-table-box').hide();
- } else {
- layuiTableElem.find('.layui-table-custom.layui-table-custom-' + item.name).hide();
- }
- });
-
- if (currentLayout == 'table') {
- layuiTableElem.find('.layui-table-box').show();
- } else {
- var className = '.layui-table-custom.layui-table-custom-' + currentLayout;
- // 如果不存在则创建
- if (!layuiTableElem.find(className).length) {
- layuiTableElem.find('.layui-table-box').before('');
- }
- layuiTableElem.find(className).show();
- loading.show();
+ if (currentLayout == 'table') {
+ layuiTableElem.find('.layui-table-box').show();
+ } else {
+ var className = '.layui-table-custom.layui-table-custom-' + currentLayout;
+ // 如果不存在则创建
+ if (!layuiTableElem.find(className).length) {
+ layuiTableElem.find('.layui-table-box').before('');
}
- };
+ layuiTableElem.find(className).show();
+ loading.show();
+ }
var optionDone = options.done;
options.done = function (res, curr, count) {
@@ -1028,1029 +943,1805 @@
return options;
- },
+ };
- renderSwitch: function (cols, tableInit, tableId, modifyReload) {
- tableInit.modifyUrl = tableInit.modifyUrl || false;
- cols = cols[0] || {};
- tableId = tableId || init.tableRenderId;
- if (cols.length > 0) {
- $.each(cols, function (i, v) {
- v.filter = v.filter || false;
- if (v.filter !== false && tableInit.modifyUrl !== false) {
- admin.table.listenSwitch({ filter: v.filter, url: tableInit.modifyUrl, tableId: tableId, modifyReload: modifyReload });
- }
- });
- }
- },
- renderOperat(data, elem) {
- for (dk in data) {
- var col = data[dk];
- var operat = col[col.length - 1].operat;
- if (operat !== undefined) {
- var check = false;
- for (key in operat) {
- var item = operat[key];
- if (typeof item === 'string') {
- if (admin.checkAuth(item, elem)) {
+ return options;
+ },
+
+ renderSwitch: function (cols, tableInit, tableId, modifyReload) {
+ tableInit.modifyUrl = tableInit.modifyUrl || false;
+ cols = cols[0] || {};
+ tableId = tableId || init.tableRenderId;
+ if (cols.length > 0) {
+ $.each(cols, function (i, v) {
+ v.filter = v.filter || false;
+ if (v.filter !== false && tableInit.modifyUrl !== false) {
+ admin.table.listenSwitch({ filter: v.filter, url: tableInit.modifyUrl, tableId: tableId, modifyReload: modifyReload });
+ }
+ });
+ }
+ },
+ renderOperat(data, elem) {
+ for (dk in data) {
+ var col = data[dk];
+ var operat = col[col.length - 1].operat;
+ if (operat !== undefined) {
+ var check = false;
+ for (key in operat) {
+ var item = operat[key];
+ if (typeof item === 'string') {
+ if (admin.checkAuth(item, elem)) {
+ check = true;
+ break;
+ }
+ } else {
+ for (k in item) {
+ var v = item[k];
+ if (v.auth == undefined) {
+ v.auth = 'add';
+ }
+ if (admin.checkAuth(v.auth, elem)) {
check = true;
break;
}
- } else {
- for (k in item) {
- var v = item[k];
- if (v.auth == undefined) {
- v.auth = 'add';
- }
- if (admin.checkAuth(v.auth, elem)) {
- check = true;
- break;
- }
- }
}
}
- if (!check) {
- data[dk].pop();
- }
+ }
+ if (!check) {
+ data[dk].pop();
+ }
+ }
+
+ }
+ return data;
+ },
+ renderTrueHide(data, options) {
+ var newData = [];
+ for (dk in data) {
+ var newCol = [];
+ var col = data[dk];
+
+ col.forEach(colItem => {
+ var trueHide = false;
+ if (typeof colItem.trueHide == 'function') {
+ trueHide = colItem.trueHide(colItem, col, options);
+ } else if (typeof colItem.trueHide == 'string') {
+ trueHide = !admin.checkAuth(colItem.trueHide, options.elem);
+ } else {
+ trueHide = colItem.trueHide;
}
- }
- return data;
- },
- renderTrueHide(data, options) {
- var newData = [];
- for (dk in data) {
- var newCol = [];
- var col = data[dk];
-
- col.forEach(colItem => {
- var trueHide = false;
- if (typeof colItem.trueHide == 'function') {
- trueHide = colItem.trueHide(colItem, col, options);
- } else if (typeof colItem.trueHide == 'string') {
- trueHide = !admin.checkAuth(colItem.trueHide, options.elem);
- } else {
- trueHide = colItem.trueHide;
- }
-
- if (!trueHide) {
- newCol.push(colItem);
- }
- });
-
- newData.push(newCol);
- }
-
- return newData;
- },
- buildToolbarHtml: function (toolbar, tableId) {
- var html = '';
- toolbar.class = toolbar.class || '';
- toolbar.icon = toolbar.icon || '';
- toolbar.auth = toolbar.auth || 'add';
- toolbar.url = toolbar.url || '';
- toolbar.extend = toolbar.extend || '';
- toolbar.method = toolbar.method || 'open';
- toolbar.field = toolbar.field || 'id';
- toolbar.title = toolbar.title || toolbar.text;
- toolbar.text = toolbar.text || toolbar.title;
- toolbar.checkbox = toolbar.checkbox || false;
-
- var formatToolbar = toolbar;
- formatToolbar.icon = formatToolbar.icon !== '' ? ' ' : '';
- formatToolbar.class = formatToolbar.class !== '' ? 'class="' + formatToolbar.class + '" ' : '';
- if (toolbar.method === 'open') {
- formatToolbar.method = formatToolbar.method !== '' ? 'data-open="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
- } else if (toolbar.method === 'none') { // 常用于与extend配合,自定义监听按钮
- formatToolbar.method = '';
- } else if (toolbar.method === 'blank') {
- formatToolbar.method = ' href="' + formatToolbar.url + '" target="_blank" ';
- } else if (operat.method === 'tab') {
- formatToolbar.method = ' layuimini-content-href="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '"';
- } else {
- formatToolbar.method = formatToolbar.method !== '' ? 'data-request="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
- }
- formatToolbar.checkbox = toolbar.checkbox ? ' data-checkbox="true" ' : '';
- formatToolbar.tableId = tableId !== undefined ? ' data-table="' + tableId + '" ' : '';
- html = '';
-
- return html;
- },
- buildOperatHtml: function (operat, data) {
- var html = '';
- operat.class = operat.class || '';
- operat.icon = operat.icon || '';
- operat.auth = operat.auth || 'add';
- operat.url = operat.url || '';
- operat.extend = operat.extend || '';
- operat.method = operat.method || 'open';
- operat.field = operat.field || 'id';
- operat.data = operat.data || ['id'];
- operat.titleField = operat.titleField || 'title';
- operat.title = operat.title || operat.text;
- operat.text = operat.text || operat.title;
-
- var titleEndfix = '';
-
- if (typeof operat.titleField == 'function') {
- titleEndfix = operat.titleField(data, operat);
-
- } else if (data[operat.titleField]) {
- titleEndfix = '-' + data[operat.titleField];
- }
-
- if (typeof operat.text == 'function') {
- operat.text = operat.text(data, operat);
- }
-
- if (typeof operat.title == 'function') {
- operat.title = operat.title(data, operat);
- }
-
- var formatOperat = operat;
- formatOperat.icon = formatOperat.icon !== '' ? ' ' : '';
- formatOperat.class = formatOperat.class !== '' ? 'class="' + formatOperat.class + '" ' : '';
- if (operat.method === 'open') {
- formatOperat.method = formatOperat.method !== '' ? 'data-open="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
- } else if (operat.method === 'none') { // 常用于与extend配合,自定义监听按钮
- formatOperat.method = '';
- } else if (operat.method === 'blank') {
- formatOperat.method = ' href="' + formatOperat.url + '" target="_blank" ';
- } else if (operat.method === 'tab') {
- formatOperat.method = ' layuimini-content-href="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '"';
- } else {
- formatOperat.method = formatOperat.method !== '' ? 'data-request="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
- }
-
- formatOperat.dataBind = ' ';
- operat.data.forEach((item, index) => {
- formatOperat.dataBind += 'data-' + item + '="' + data[item] + '" ';
+ if (!trueHide) {
+ newCol.push(colItem);
+ }
});
- html = '' + formatOperat.icon + formatOperat.text + '';
+ newData.push(newCol);
+ }
- return html;
- },
- toolSpliceUrl(url, field, data) {
- url = url.indexOf("?") !== -1 ? url + '&' + field + '=' + data[field] : url + '?' + field + '=' + data[field];
- return url;
- },
- formatCols: function (cols, init) {
- for (i in cols) {
- var col = cols[i];
- for (index in col) {
- var val = col[index];
+ return newData;
+ },
+ buildToolbarHtml: function (toolbar, tableId) {
+ var html = '';
+ toolbar.class = toolbar.class || '';
+ toolbar.icon = toolbar.icon || '';
+ toolbar.auth = toolbar.auth || 'add';
+ toolbar.url = toolbar.url || '';
+ toolbar.extend = toolbar.extend || '';
+ toolbar.method = toolbar.method || 'open';
+ toolbar.field = toolbar.field || 'id';
+ toolbar.title = toolbar.title || toolbar.text;
+ toolbar.text = toolbar.text || toolbar.title;
+ toolbar.checkbox = toolbar.checkbox || false;
- if (typeof val.hide == 'function') {
- cols[i][index]['hide'] = val.hide(val, cols, init);
- }
- if (val['width'] == undefined && val['minWidth'] == undefined) {
- var width = null;
- if (val.title) {
- width = val.title.length * 15 + 55;
- }
+ var formatToolbar = toolbar;
+ formatToolbar.icon = formatToolbar.icon !== '' ? ' ' : '';
+ formatToolbar.class = formatToolbar.class !== '' ? 'class="' + formatToolbar.class + '" ' : '';
+ if (toolbar.method === 'open') {
+ formatToolbar.method = formatToolbar.method !== '' ? 'data-open="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
+ } else if (toolbar.method === 'none') { // 常用于与extend配合,自定义监听按钮
+ formatToolbar.method = '';
+ } else if (toolbar.method === 'blank') {
+ formatToolbar.method = ' href="' + formatToolbar.url + '" target="_blank" ';
+ } else if (operat.method === 'tab') {
+ formatToolbar.method = ' layuimini-content-href="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '"';
+ } else {
+ formatToolbar.method = formatToolbar.method !== '' ? 'data-request="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
+ }
+ formatToolbar.checkbox = toolbar.checkbox ? ' data-checkbox="true" ' : '';
+ formatToolbar.tableId = tableId !== undefined ? ' data-table="' + tableId + '" ' : '';
+ html = '';
- if (width != null) {
- cols[i][index]['minWidth'] = width;
- }
+ return html;
+ },
+ buildOperatHtml: function (operat, data) {
+ var html = '';
+ operat.class = operat.class || '';
+ operat.icon = operat.icon || '';
+ operat.auth = operat.auth || 'add';
+ operat.url = operat.url || '';
+ operat.extend = operat.extend || '';
+ operat.method = operat.method || 'open';
+ operat.field = operat.field || 'id';
+ operat.data = operat.data || ['id'];
+ operat.titleField = operat.titleField || 'title';
+ operat.title = operat.title || operat.text;
+ operat.text = operat.text || operat.title;
+
+ var titleEndfix = '';
+
+ if (typeof operat.titleField == 'function') {
+ titleEndfix = operat.titleField(data, operat);
+
+ } else if (data[operat.titleField]) {
+ titleEndfix = '-' + data[operat.titleField];
+ }
+
+ if (typeof operat.text == 'function') {
+ operat.text = operat.text(data, operat);
+ }
+
+ if (typeof operat.title == 'function') {
+ operat.title = operat.title(data, operat);
+ }
+
+ var formatOperat = operat;
+ formatOperat.icon = formatOperat.icon !== '' ? ' ' : '';
+ formatOperat.class = formatOperat.class !== '' ? 'class="' + formatOperat.class + '" ' : '';
+ if (operat.method === 'open') {
+ formatOperat.method = formatOperat.method !== '' ? 'data-open="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
+ } else if (operat.method === 'none') { // 常用于与extend配合,自定义监听按钮
+ formatOperat.method = '';
+ } else if (operat.method === 'blank') {
+ formatOperat.method = ' href="' + formatOperat.url + '" target="_blank" ';
+ } else if (operat.method === 'tab') {
+ formatOperat.method = ' layuimini-content-href="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '"';
+ } else {
+ formatOperat.method = formatOperat.method !== '' ? 'data-request="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
+ }
+
+ formatOperat.dataBind = ' ';
+ operat.data.forEach((item, index) => {
+ formatOperat.dataBind += 'data-' + item + '="' + data[item] + '" ';
+ });
+
+ html = '' + formatOperat.icon + formatOperat.text + '';
+
+ return html;
+ },
+ toolSpliceUrl(url, field, data) {
+ url = url.indexOf("?") !== -1 ? url + '&' + field + '=' + data[field] : url + '?' + field + '=' + data[field];
+ return url;
+ },
+ formatCols: function (cols, init) {
+ for (i in cols) {
+ var col = cols[i];
+ for (index in col) {
+ var val = col[index];
+
+ if (typeof val.hide == 'function') {
+ cols[i][index]['hide'] = val.hide(val, cols, init);
+ }
+ if (val['width'] == undefined && val['minWidth'] == undefined) {
+ var width = null;
+ if (val.title) {
+ width = val.title.length * 15 + 55;
}
- // if str end with _time
- if (val.field && val.field.indexOf('_time') !== -1) {
- cols[i][index]['minWidth'] = 160;
+ if (width != null) {
+ cols[i][index]['minWidth'] = width;
}
+ }
+
+ // if str end with _time
+ if (val.field && val.field.indexOf('_time') !== -1) {
+ cols[i][index]['minWidth'] = 160;
+ }
- if (val.sort === undefined) {
- cols[i][index]['sort'] = true;
- }
- if (val.defaultValue === undefined) {
- cols[i][index]['defaultValue'] = '';
- }
+ if (val.sort === undefined) {
+ cols[i][index]['sort'] = true;
+ }
+ if (val.defaultValue === undefined) {
+ cols[i][index]['defaultValue'] = '';
+ }
- // 判断是否包含初始化数据
- if (val.init === undefined) {
- cols[i][index]['init'] = init;
- }
+ // 判断是否包含初始化数据
+ if (val.init === undefined) {
+ cols[i][index]['init'] = init;
+ }
- // 格式化列操作栏
- if (val.templet === admin.table.tool && val.operat === undefined) {
- cols[i][index]['operat'] = ['edit', 'delete'];
- }
- // 格式化列操作栏
- if (val.templet === admin.table.tool) {
- cols[i][index]['sort'] = false;
- }
+ // 格式化列操作栏
+ if (val.templet === admin.table.tool && val.operat === undefined) {
+ cols[i][index]['operat'] = ['edit', 'delete'];
+ }
+ // 格式化列操作栏
+ if (val.templet === admin.table.tool) {
+ cols[i][index]['sort'] = false;
+ }
- // 判断是否包含开关组件
- if (val.templet === admin.table.switch && val.filter === undefined) {
- cols[i][index]['filter'] = val.field;
- }
+ // 判断是否包含开关组件
+ if (val.templet === admin.table.switch && val.filter === undefined) {
+ cols[i][index]['filter'] = val.field;
+ }
- // 判断是否含有搜索下拉列表
- if (val.selectList !== undefined && val.search === undefined) {
- cols[i][index]['search'] = 'select';
- }
+ // 判断是否含有搜索下拉列表
+ if (val.selectList !== undefined && val.search === undefined) {
+ cols[i][index]['search'] = 'select';
+ }
- // 判断是否初始化对齐方式
- if (val.align === undefined) {
- cols[i][index]['align'] = 'left';
- }
+ // 判断是否初始化对齐方式
+ if (val.align === undefined) {
+ cols[i][index]['align'] = 'left';
+ }
- // 部分字段开启排序
- var sortDefaultFields = ['id', 'sort'];
- if (val.sort === undefined && sortDefaultFields.indexOf(val.field) >= 0) {
- cols[i][index]['sort'] = true;
- }
+ // 部分字段开启排序
+ var sortDefaultFields = ['id', 'sort'];
+ if (val.sort === undefined && sortDefaultFields.indexOf(val.field) >= 0) {
+ cols[i][index]['sort'] = true;
+ }
- // 初始化图片高度
- if (val.templet === admin.table.image && val.imageHeight === undefined) {
- cols[i][index]['imageHeight'] = 26;
- cols[i][index]['sort'] = false;
- }
- // 图片默认不搜索
- if (val.templet === admin.table.image && val.search === undefined) {
- cols[i][index]['search'] = false;
- }
+ // 初始化图片高度
+ if (val.templet === admin.table.image && val.imageHeight === undefined) {
+ cols[i][index]['imageHeight'] = 26;
+ cols[i][index]['sort'] = false;
+ }
+ // 图片默认不搜索
+ if (val.templet === admin.table.image && val.search === undefined) {
+ cols[i][index]['search'] = false;
+ }
- // 判断是否列表数据转换
- if (val.selectList !== undefined && val.templet === undefined) {
- cols[i][index]['templet'] = admin.table.list;
- }
+ // 判断是否列表数据转换
+ if (val.selectList !== undefined && val.templet === undefined) {
+ cols[i][index]['templet'] = admin.table.list;
+ }
- // 判断是否多层对象
- if (val.field !== undefined && val.field.split(".").length > 1) {
- if (val.templet === undefined) {
- cols[i][index]['templet'] = admin.table.value;
- }
- }
-
- // 如果未定义则默认使用value
- if (cols[i][index]['templet'] === undefined) {
+ // 判断是否多层对象
+ if (val.field !== undefined && val.field.split(".").length > 1) {
+ if (val.templet === undefined) {
cols[i][index]['templet'] = admin.table.value;
- } else {
- // 针对特定的模板做数据调整
-
- if (cols[i][index]['templet'] == admin.table.list) {
- if (val.selectValue) {
-
- var newSelectList = {};
- val.selectList.map(item => {
- newSelectList[item[val.selectValue]] = item[val.selectLabel];
- });
-
- cols[i][index]['selectList'] = newSelectList;
-
- }
- }
}
+ }
- if (val.fieldFormat == undefined) {
+ // 如果未定义则默认使用value
+ if (cols[i][index]['templet'] === undefined) {
+ cols[i][index]['templet'] = admin.table.value;
+ } else {
+ // 针对特定的模板做数据调整
- switch (val.templet) {
- case admin.table.image:
- val.fieldFormat = 'image';
- break;
- case admin.table.date:
- val.fieldFormat = 'date';
- break;
- default:
- val.fieldFormat = 'text';
+ if (cols[i][index]['templet'] == admin.table.list) {
+ if (val.selectValue) {
+
+ var newSelectList = {};
+ val.selectList.map(item => {
+ newSelectList[item[val.selectValue]] = item[val.selectLabel];
+ });
+
+ cols[i][index]['selectList'] = newSelectList;
- if (val.selectList !== undefined) {
- val.fieldFormat = 'select';
- }
- break;
}
}
}
- }
- return cols;
- },
- tool: function (data) {
- var option = data.LAY_COL;
- option.operat = option.operat || ['edit', 'delete'];
- var elem = option.init.tableElem || init.tableElem;
- var html = '';
- $.each(option.operat, function (i, item) {
- if (typeof item === 'string') {
- switch (item) {
- case 'edit':
- var editMethod = 'tab';
- if(selectMode){
- editMethod = 'open';
- }
- var operat = {
- class: 'layui-btn layui-btn-success layui-btn-xs',
- method: editMethod,
- field: 'id',
- icon: '',
- text: '编辑',
- title: '编辑信息',
- auth: 'edit',
- url: option.init.editUrl,
- extend: option.init.formFullScreen == 'true' ? ' data-full="true"' : ''
- };
- operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
- if (admin.checkAuth(operat.auth, elem)) {
- html += admin.table.buildOperatHtml(operat, data);
- }
+
+ if (val.fieldFormat == undefined) {
+
+ switch (val.templet) {
+ case admin.table.image:
+ val.fieldFormat = 'image';
break;
- case 'delete':
- var operat = {
- class: 'layui-btn layui-btn-danger layui-btn-xs',
- method: 'get',
- field: 'id',
- icon: '',
- text: '删除',
- title: '确定删除?',
- auth: 'delete',
- url: option.init.deleteUrl,
- extend: ""
- };
- operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
- if (admin.checkAuth(operat.auth, elem)) {
- html += admin.table.buildOperatHtml(operat, data);
+ case admin.table.date:
+ val.fieldFormat = 'date';
+ break;
+ default:
+ val.fieldFormat = 'text';
+
+ if (val.selectList !== undefined) {
+ val.fieldFormat = 'select';
}
break;
}
-
- } else if (typeof item === 'object') {
- $.each(item, function (i, operat) {
- operat.class = operat.class || '';
- operat.icon = operat.icon || '';
- operat.auth = operat.auth || 'add';
- operat.url = operat.url || '';
- operat.method = operat.method || 'open';
- operat.field = operat.field || 'id';
- operat.title = operat.title || operat.text;
- operat.text = operat.text || operat.title;
- operat.extend = operat.extend || '';
-
- operat._if = operat._if || function () { return true; };
-
- if (typeof operat._if == 'function') {
- if (operat._if(data, operat) !== true) {
- return '';
- }
- } else if (typeof operat._if == 'string') {
- var ifValue = admin.table.returnColumnValue(data, operat._if, false);
- if (!ifValue) {
- return '';
- }
+ }
+ }
+ }
+ return cols;
+ },
+ tool: function (data) {
+ var option = data.LAY_COL;
+ option.operat = option.operat || ['edit', 'delete'];
+ var elem = option.init.tableElem || init.tableElem;
+ var html = '';
+ $.each(option.operat, function (i, item) {
+ if (typeof item === 'string') {
+ switch (item) {
+ case 'edit':
+ var editMethod = 'tab';
+ if (selectMode) {
+ editMethod = 'open';
}
-
- // 自定义表格opreat按钮的弹窗标题风格,extra是表格里的欲加入标题中的字段
- operat.extra = operat.extra || '';
- if (data[operat.extra] !== undefined) {
- operat.title = data[operat.extra] + ' - ' + operat.title;
- }
-
- if (typeof operat.url == 'function') {
- operat.url = operat.url(data, operat);
- }
-
-
- if (typeof operat.field != 'function') {
- if (!admin.empty(operat.field)) {
- operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
- }
- } else {
-
- var fieldParam = operat.field(data, operat);
-
- if (typeof fieldParam == 'string') {
- operat.url = fieldParam;
- } else {
- var querys = '';
- if (operat.url.indexOf("?") !== -1) {
- if (operat.url.indexOf("?") !== operat.url.length - 1) {
- querys = '&';
- }
- } else {
- querys = '?';
- }
- operat.url += querys + $.param(fieldParam);
- }
-
- }
-
+ var operat = {
+ class: 'layui-btn layui-btn-success layui-btn-xs',
+ method: editMethod,
+ field: 'id',
+ icon: '',
+ text: '编辑',
+ title: '编辑信息',
+ auth: 'edit',
+ url: option.init.editUrl,
+ extend: option.init.formFullScreen == 'true' ? ' data-full="true"' : ''
+ };
+ operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
if (admin.checkAuth(operat.auth, elem)) {
html += admin.table.buildOperatHtml(operat, data);
}
- });
- }
- });
- return html;
- },
- list: function (data) {
- var option = data.LAY_COL;
- option.selectList = option.selectList || {};
-
- var value = admin.table.returnColumnValue(data);
- if (option.selectList[value] === undefined || option.selectList[value] === '' || option.selectList[value] === null) {
- return value;
- } else {
- return option.selectList[value];
- }
- },
- filePreview: function (data) {
- var mimeName = data.mime_type.split('/')[0];
-
- if (mimeName == 'image') {
- return admin.table.image(data);
- } else {
-
- var value = admin.table.returnColumnValue(data);
-
- var groupName = admin.getExtGroupName(data.file_ext);
-
- return '
';
- }
-
- },
- image: function (data) {
- var option = data.LAY_COL;
- option.imageWidth = option.imageWidth || 200;
- option.imageHeight = option.imageHeight || 26;
- option.imageSplit = option.imageSplit || '|';
- option.imageJoin = option.imageJoin || '
';
- option.title = option.title || option.field;
- var title = data[option.title];
- var value = admin.table.returnColumnValue(data);
- if (value === undefined || value === null) {
- return '
';
- } else {
- var values = value.split(option.imageSplit),
- valuesHtml = [];
- values.forEach((value, index) => {
- valuesHtml.push('
');
- });
- return valuesHtml.join(option.imageJoin);
- }
- },
- url: function (data) {
- var option = data.LAY_COL;
-
- var urlNameField = option.urlNameField || '';
-
- var value = admin.table.returnColumnValue(data);
-
- if (admin.empty(value)) {
- return '';
- }
-
- var urlName = value;
-
- if (urlNameField != '') {
- try {
- var urlNameFieldType = typeof urlNameField;
-
- if (urlNameFieldType == 'string') {
- urlName = data[urlNameField];
- } else if (urlNameFieldType == 'function') {
- urlName = urlNameField(data);
- }
-
- } catch (e) {
-
- }
- }
-
- return '' + urlName + '';
- },
- switch: function (data) {
- var option = data.LAY_COL;
-
- if (!admin.checkAuth('modify', option.init.tableElem)) {
- return admin.table.list(data);
- }
-
- option.filter = option.filter || option.field || null;
- option.checked = option.checked || 1;
-
-
- var value = admin.table.returnColumnValue(data);
- var checked = value === option.checked ? 'checked' : '';
- return laytpl('').render(data);
- },
- price: function (data) {
- var value = admin.table.returnColumnValue(data);
- return '¥' + value + '';
- },
- percent: function (data) {
- var value = admin.table.returnColumnValue(data);
- return '' + value + '%';
- },
- icon: function (data) {
- var value = admin.table.returnColumnValue(data);
- return '';
- },
- text: function (data) {
- var value = admin.table.returnColumnValue(data);
- return '' + value + '';
- },
- value: function (data) {
- var value = admin.table.returnColumnValue(data);
- return '' + value + '';
- },
- //时间戳转日期
- date: function (data) {
- var option = data.LAY_COL;
-
- value = admin.table.returnColumnValue(data);
- if (!admin.empty(value)) {
- value = util.toDateString(value * 1000, option.format || 'yyyy-MM-dd HH:mm:ss');
- }
- return '' + value + '';
- },
- bytes: (data) => {
- var size = admin.table.returnColumnValue(data);
- sizeReadable = admin.bytes(size);
- return sizeReadable;
- },
- copyText(data) {
- var option = data.LAY_COL;
- var value = admin.table.returnColumnValue(data);
- var copyValue = value;
- var copyText = option.copyText;
-
- if (typeof copyText === 'function') {
- copyValue = copyText(value, data);
- }
-
- return ' ' + value + '';
- },
- // 统一列返回数据处理
- returnColumnValue(data, field, defaultValue) {
- if (!data.LAY_COL) {
- return '';
- }
- var option = data.LAY_COL;
-
- field = field || option.field;
- defaultValue = defaultValue || option.defaultValue;
-
- var valueParser = option.valueParser;
- var value = undefined;
- try {
- value = eval("data." + field);
- } catch (e) {
-
- }
- if (typeof valueParser == 'function') {
- value = valueParser(value, data);
- }
-
- if (value === null || value === undefined) {
- value = defaultValue;
- }
-
- return value;
- },
- listenTableSearch: function (tableId) {
- form.on('submit(' + tableId + '_filter)', function (data) {
- var dataField = data.field;
- var formatFilter = {},
- formatOp = {};
- $.each(dataField, function (key, val) {
- if (val !== '') {
- formatFilter[key] = val;
-
- var elemId = admin.table.renderSearchFormItemElementId(key);
-
- var op = $('#c-' + elemId).attr('data-search-op');
- op = op || '%*%';
- formatOp[key] = op;
- }
- });
-
- var where = {
- filter: JSON.stringify(formatFilter),
- op: JSON.stringify(formatOp)
- };
- lastTableWhere[tableId] = where;
- table.reloadData(tableId, {
- page: {
- curr: 1
- }
- , where: where
- }, 'data');
- return false;
- });
- },
- listenSwitch: function (option, ok) {
- option.filter = option.filter || '';
- option.url = option.url || '';
- option.field = option.field || option.filter || '';
- option.tableId = option.tableId || init.tableRenderId;
- option.modifyReload = option.modifyReload || false;
- form.on('switch(' + option.filter + ')', function (obj) {
- var checked = obj.elem.checked ? 1 : 0;
- if (typeof ok === 'function') {
- return ok({
- id: obj.value,
- checked: checked,
- });
- } else {
- var data = {
- id: obj.value,
- field: option.field,
- value: checked,
- };
- admin.request.post({
- url: option.url,
- prefix: true,
- data: data,
- }, function (res) {
- if (option.modifyReload) {
- table.reloadData(option.tableId);
- }
- }, function (res) {
- admin.msg.error(res.msg, function () {
- table.reloadData(option.tableId);
- });
- }, function () {
- table.reloadData(option.tableId);
- });
- }
- });
- },
- listenTableSort(option) {
- //触发排序事件
- table.on('sort(' + option.layFilter + ')', function (obj) { //注:sort 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
-
- var lastWhere = lastTableWhere[option.id] ? lastTableWhere[option.id] : {};
-
- lastWhere.sort = {};
- lastWhere.sort[obj.field] = obj.type;
-
- table.reloadData(option.id, {
- initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。
- , where: lastWhere
- });
-
-
- });
- },
- listenToolbar: function (layFilter, tableId) {
- table.on('toolbar(' + layFilter + ')', function (obj) {
- var options = obj.config;
- var tableId = obj.config.id;
- // 搜索表单的显示
- switch (obj.event) {
- case 'TABLE_SEARCH':
- var searchFieldsetId = 'searchFieldset_' + tableId;
- var _that = $("#" + searchFieldsetId);
- if (_that.hasClass("layui-hide")) {
- _that.removeClass('layui-hide');
- } else {
- _that.addClass('layui-hide');
+ break;
+ case 'delete':
+ var operat = {
+ class: 'layui-btn layui-btn-danger layui-btn-xs',
+ method: 'get',
+ field: 'id',
+ icon: '',
+ text: '删除',
+ title: '确定删除?',
+ auth: 'delete',
+ url: option.init.deleteUrl,
+ extend: ""
+ };
+ operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
+ if (admin.checkAuth(operat.auth, elem)) {
+ html += admin.table.buildOperatHtml(operat, data);
}
break;
- case 'TABLE_LAYOUT':
- var layoutElemId = 'layout-list-option-' + tableId;
- var layoutElemIdName = '#' + layoutElemId;
+ }
- var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+ } else if (typeof item === 'object') {
+ $.each(item, function (i, operat) {
+ operat.class = operat.class || '';
+ operat.icon = operat.icon || '';
+ operat.auth = operat.auth || 'add';
+ operat.url = operat.url || '';
+ operat.method = operat.method || 'open';
+ operat.field = operat.field || 'id';
+ operat.title = operat.title || operat.text;
+ operat.text = operat.text || operat.title;
+ operat.extend = operat.extend || '';
- // 构建下拉选择
- var layoutHtml = '';
+ operat._if = operat._if || function () { return true; };
- options.layoutList.forEach(item => {
- var currentClassName = '';
- if (item.name == currentLayout) {
- currentClassName = 'current';
+ if (typeof operat._if == 'function') {
+ if (operat._if(data, operat) !== true) {
+ return '';
+ }
+ } else if (typeof operat._if == 'string') {
+ var ifValue = admin.table.returnColumnValue(data, operat._if, false);
+ if (!ifValue) {
+ return '';
+ }
+ }
+
+ // 自定义表格opreat按钮的弹窗标题风格,extra是表格里的欲加入标题中的字段
+ operat.extra = operat.extra || '';
+ if (data[operat.extra] !== undefined) {
+ operat.title = data[operat.extra] + ' - ' + operat.title;
+ }
+
+ if (typeof operat.url == 'function') {
+ operat.url = operat.url(data, operat);
+ }
+
+
+ if (typeof operat.field != 'function') {
+ if (!admin.empty(operat.field)) {
+ operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
+ }
+ } else {
+
+ var fieldParam = operat.field(data, operat);
+
+ if (typeof fieldParam == 'string') {
+ operat.url = fieldParam;
+ } else if (typeof fieldParam == 'object') {
+ for (const key in fieldParam) {
+ if (Object.hasOwnProperty.call(fieldParam, key)) {
+ const value = fieldParam[key];
+ operat.url = admin.table.toolSpliceUrl(operat.url, key, fieldParam);
+ }
}
- layoutHtml += `
+ }
+ }
+
+
+ if (operat.method == 'get' && !admin.empty(operat.url)) {
+ operat.url = admin.url(operat.url);
+ }
+
+ if (admin.checkAuth(operat.auth, elem)) {
+ html += admin.table.buildOperatHtml(operat, data);
+ }
+ });
+ }
+ });
+ return html;
+ },
+ value: function (data) {
+ var option = data.LAY_COL;
+ var value = data;
+ if (option.field.split('.').length > 1) {
+ var field = option.field;
+ option.field = field.split('.');
+ value = admin.dataGet(data, option.field);
+ } else {
+ value = data[option.field];
+ }
+ return value;
+ },
+ returnColumnValue: function (data, field, defaultValue) {
+ var option = data.LAY_COL || {};
+ var targetField = field || option.field;
+ var targetDefaultValue = defaultValue;
+ if (targetDefaultValue === undefined) {
+ targetDefaultValue = option.defaultValue;
+ }
+ if (!targetField) {
+ return targetDefaultValue;
+ }
+ if (Array.isArray(targetField) || (typeof targetField === 'string' && targetField.split('.').length > 1)) {
+ return admin.dataGet(data, targetField, targetDefaultValue);
+ }
+ var value = data[targetField];
+ if (value === undefined || value === null) {
+ return targetDefaultValue;
+ }
+ return value;
+ },
+ list: function (data) {
+ var option = data.LAY_COL;
+ option.selectList = option.selectList || {};
+
+ var value = admin.table.returnColumnValue(data);
+ if (option.selectList[value] === undefined || option.selectList[value] === '' || option.selectList[value] === null) {
+ return value;
+ } else {
+ return option.selectList[value];
+ }
+ },
+ filePreview: function (data) {
+ var mimeName = data.mime_type.split('/')[0];
+
+ if (mimeName == 'image') {
+ return admin.table.image(data);
+ } else {
+
+ var value = admin.table.returnColumnValue(data);
+
+ var groupName = admin.getExtGroupName(data.file_ext);
+
+ return '

';
+ }
+
+ },
+ image: function (data) {
+ var option = data.LAY_COL;
+ option.imageWidth = option.imageWidth || 200;
+ option.imageHeight = option.imageHeight || 26;
+ option.imageSplit = option.imageSplit || '|';
+ option.imageJoin = option.imageJoin || '
';
+ option.title = option.title || option.field;
+ var title = data[option.title];
+ var value = admin.table.returnColumnValue(data);
+ if (value === undefined || value === null) {
+ return '

';
+ } else {
+ var values = value.split(option.imageSplit),
+ valuesHtml = [];
+ values.forEach((value, index) => {
+ valuesHtml.push('

');
+ });
+ return valuesHtml.join(option.imageJoin);
+ }
+ },
+ url: function (data) {
+ var option = data.LAY_COL;
+
+ var urlNameField = option.urlNameField || '';
+
+ var value = admin.table.returnColumnValue(data);
+
+ if (admin.empty(value)) {
+ return value;
+ }
+
+ var urlName = '';
+ if (!admin.empty(urlNameField)) {
+ urlName = data[urlNameField] || '';
+ }
+
+ if (admin.empty(urlName)) {
+ urlName = value;
+ }
+
+ return '
' + urlName + '';
+ },
+ date: function (data) {
+ var option = data.LAY_COL;
+ var value = admin.table.returnColumnValue(data);
+ if (value === undefined || value === null) {
+ return value;
+ }
+ if (option.timeFormat === undefined) {
+ return layui.util.toDateString(value * 1000, 'yyyy-MM-dd HH:mm:ss');
+ } else {
+ return layui.util.toDateString(value * 1000, option.timeFormat);
+ }
+ },
+ switch: function (data) {
+ var option = data.LAY_COL;
+ option.filter = option.filter || option.field;
+ option.openText = option.openText || '开';
+ option.closeText = option.closeText || '关';
+ option.open = option.open || '1';
+ option.close = option.close || '0';
+ option.url = option.url || '';
+ option.switchStyle = option.switchStyle || 'switch';
+ var value = admin.table.returnColumnValue(data);
+
+ if (admin.empty(value)) {
+ return '';
+ }
+
+ var renderSwitch = '';
+
+ if (option.switchStyle == 'checkbox') {
+ renderSwitch = '
';
+ } else if (option.switchStyle == 'switch') {
+ renderSwitch = '
';
+ }
+
+ return renderSwitch;
+ },
+ listenSwitch: function (data) {
+ var filter = data.filter,
+ url = data.url,
+ tableId = data.tableId,
+ modifyReload = data.modifyReload;
+ form.on('switch(' + filter + ')', function (obj) {
+ var id = obj.elem.getAttribute('data-id');
+ var field = obj.elem.getAttribute('name');
+ var value = this.checked ? 1 : 0;
+ admin.request.post({
+ url: url,
+ prefix: true,
+ data: {
+ id: id,
+ field: field,
+ value: value,
+ },
+ }, function (res) {
+ if (modifyReload) {
+ table.reloadData(tableId);
+ }
+ }, function (res) {
+ admin.msg.error(res.msg, function () {
+ table.reloadData(tableId);
+ });
+ }, function () {
+ table.reloadData(tableId);
+ });
+ return false;
+ });
+ },
+ listenTableSort: function (options) {
+ table.on('sort(' + options.layFilter + ')', function (obj) {
+ var type = obj.type;
+ var sort = obj.field;
+ var tableId = options.id;
+
+ if (options.autoSort != undefined && options.autoSort == true) {
+ var sortVal;
+ if (type === undefined || type === null || type === '') {
+ sortVal = 'default';
+ } else {
+ sortVal = type;
+ }
+ var sortData = {
+ sort: sort,
+ order: sortVal
+ };
+ var where = admin.table.formatWhere(options, sortData, tableId);
+ options.where = where;
+ table.reloadData(tableId, {
+ initSort: obj,
+ where: where,
+ });
+ }
+ });
+ },
+ listenToolbar: function (layFilter, tableId) {
+ table.on('toolbar(' + layFilter + ')', function (obj) {
+ var item = obj.event;
+ switch (item) {
+ case 'TABLE_SEARCH':
+ if (!$('#' + tableId + '_filter_form').is(':visible')) {
+ $('#' + tableId + '_filter_form').removeClass('layui-hide');
+ $('#' + tableId + '_filter_form').show();
+ } else {
+ $('#' + tableId + '_filter_form').hide();
+ }
+ break;
+ case 'TABLE_LAYOUT':
+ var layoutElemIdName = '#layout-' + tableId;
+ if ($(layoutElemIdName).length > 0) {
+ // If it is, remove the HTML
+ $(layoutElemIdName).remove();
+ }
+ if (!Array.isArray(options.layoutList)) {
+ options.layoutList = ['table', 'card'];
+ }
+ var layoutList = [];
+ var defaultLayout = 'table';
+ var layoutListDefault = [
+ {
+ name: 'table',
+ title: '表格',
+ icon: 'layui-icon-table'
+ },
+ {
+ name: 'card',
+ title: '卡片',
+ icon: 'layui-icon-table'
+ },
+ ];
+ options.layoutList.forEach((item) => {
+ if (typeof item == 'string') {
+ layoutListDefault.forEach((layout) => {
+ if (layout.name == item) {
+ layoutList.push(layout);
+ }
+ });
+ } else {
+ if (item.name == 'table') {
+ layoutList.push({
+ name: 'table',
+ title: '表格',
+ icon: 'layui-icon-table'
+ });
+ } else if (item.name == 'card') {
+ layoutList.push({
+ name: 'card',
+ title: '卡片',
+ icon: 'layui-icon-table'
+ });
+ } else {
+ item.icon = item.icon || 'layui-icon-table';
+ item.title = item.title || item.name;
+ layoutList.push(item);
+ }
+ }
+ });
+
+ var layoutHtml = '
';
+ layoutList.forEach((item) => {
+ var currentClassName = '';
+ var currentLayout = admin.getPageSetting('table-layout-default', defaultLayout);
+ if (currentLayout == item.name) {
+ currentClassName = 'current';
+ }
+ layoutHtml += `
`;
- });
+ });
- layoutHtml += '
';
+ layoutHtml += '
';
- var toolbarLayoutElem = $('[lay-table-id="' + tableId + '"]').find('[lay-event="TABLE_LAYOUT"]');
- if (toolbarLayoutElem.find(layoutElemIdName).length > 0) {
+ var toolbarLayoutElem = $('[lay-table-id="' + tableId + '"]').find('[lay-event="TABLE_LAYOUT"]');
+ if (toolbarLayoutElem.find(layoutElemIdName).length > 0) {
+ // If it is, remove the HTML
+ $(layoutElemIdName).remove();
+ }
+ layoulElem = $(layoutHtml);
+ layoulElem.appendTo(toolbarLayoutElem);
+
+
+ layoulElem.on('click', function (event) {
+
+ var item = $(event.target).closest('.item');
+ if (item.length > 0) {
+ // 点击操作
+ item.addClass('current').siblings().removeClass('current');
+
+ var layoutName = item.data('name');
+ admin.setPageSetting('table-layout-default', layoutName);
+
+ table.reloadData(tableId, {}, true);
+ } else {
+ // 其他区域操作
+ }
+
+ // 不要冒泡
+ event.stopPropagation();
+ });
+
+ // Remove any existing click event listeners to avoid duplicates
+ $(document).off('click.table-layout').on('click.table-layout', function (event) {
+
+ if (!$(event.target).closest(toolbarLayoutElem).length) {
// If it is, remove the HTML
$(layoutElemIdName).remove();
}
- layoulElem = $(layoutHtml);
- layoulElem.appendTo(toolbarLayoutElem);
-
-
- layoulElem.on('click', function (event) {
-
- var item = $(event.target).closest('.item');
- if (item.length > 0) {
- // 点击操作
- item.addClass('current').siblings().removeClass('current');
-
- var layoutName = item.data('name');
- admin.setPageSetting('table-layout-default', layoutName);
-
- table.reloadData(tableId, {}, true);
- } else {
- // 其他区域操作
- }
-
- // 不要冒泡
- event.stopPropagation();
- });
-
- // Remove any existing click event listeners to avoid duplicates
- $(document).off('click.table-layout').on('click.table-layout', function (event) {
-
- if (!$(event.target).closest(toolbarLayoutElem).length) {
- // If it is, remove the HTML
- $(layoutElemIdName).remove();
- }
- });
- break;
- }
- });
- },
- listenEdit: function (tableInit, layFilter, tableId, modifyReload) {
- tableInit.modifyUrl = tableInit.modifyUrl || false;
- tableId = tableId || init.tableRenderId;
- if (tableInit.modifyUrl !== false) {
- table.on('edit(' + layFilter + ')', function (obj) {
- var value = obj.value,
- data = obj.data,
- id = data.id,
- field = obj.field;
- var _data = {
- id: id,
- field: field,
- value: value,
- };
- admin.request.post({
- url: tableInit.modifyUrl,
- prefix: true,
- data: _data,
- }, function (res) {
- if (modifyReload) {
- table.reloadData(tableId);
- }
- }, function (res) {
- admin.msg.error(res.msg, function () {
- table.reloadData(tableId);
- });
- }, function () {
+ });
+ break;
+ }
+ });
+ },
+ listenEdit: function (tableInit, layFilter, tableId, modifyReload) {
+ tableInit.modifyUrl = tableInit.modifyUrl || false;
+ tableId = tableId || init.tableRenderId;
+ if (tableInit.modifyUrl !== false) {
+ table.on('edit(' + layFilter + ')', function (obj) {
+ var value = obj.value,
+ data = obj.data,
+ id = data.id,
+ field = obj.field;
+ var _data = {
+ id: id,
+ field: field,
+ value: value,
+ };
+ admin.request.post({
+ url: tableInit.modifyUrl,
+ prefix: true,
+ data: _data,
+ }, function (res) {
+ if (modifyReload) {
+ table.reloadData(tableId);
+ }
+ }, function (res) {
+ admin.msg.error(res.msg, function () {
table.reloadData(tableId);
});
+ }, function () {
+ table.reloadData(tableId);
+ });
+ });
+ }
+ },
+ formatWhere: function (options, sortData, tableId) {
+ var where = {};
+ if (options.where != undefined) {
+ where = options.where;
+ }
+ if (options.where && options.where.filter && options.where.op) {
+ where = options.where;
+ }
+
+ if (sortData !== undefined) {
+ where['sort'] = sortData.sort;
+ where['order'] = sortData.order;
+ }
+
+ lastTableWhere[tableId] = where;
+
+ return where;
+ },
+ renderLayoutBefore: function (options) {
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+
+ if (currentLayout != 'table') {
+ // 隐藏所有数据体内容
+ var layuiTableElemName = '#layui-table-' + options.id;
+ var layuiTableElem = $(layuiTableElemName);
+ layuiTableElem.find('.layui-table-box').hide();
+ }
+ },
+ renderLayoutAfter: function (options, res) {
+ var currentLayout = admin.getPageSetting('table-layout-default', 'table');
+
+ if (currentLayout != 'table') {
+ // 隐藏所有数据体内容
+ var layuiTableElemName = '#layui-table-' + options.id;
+ var layuiTableElem = $(layuiTableElemName);
+ if (!Array.isArray(options.layoutList)) {
+ options.layoutList = ['table', 'card'];
+ }
+
+ options.layoutList.forEach((item) => {
+ if (currentLayout == 'table') {
+ // 如果是table,则不用生成数据,显示出来就行,before已经显示过了
+ return;
+ }
+
+ if (currentLayout != item.name) {
+ // 如果不是,则不进行任何操作
+ return;
+ }
+
+ var className = '.layui-table-custom.layui-table-custom-' + item.name;
+
+ // 清空里面的数据
+ layuiTableElem.find(className).html('');
+ loading.hide();
+
+ item.tplFunction(options, res, layuiTableElem.find(className));
+
+
+
+
+ });
+
+ }
+ },
+ listenTableSelectConfirm(options) {
+ $('.select-confirm').click(function () {
+ var checkStatus = table.checkStatus(options.id);
+
+ if (checkStatus.data.length == 0) {
+ layer.msg('请选择数据');
+ return false;
+ }
+
+ parent.window[selectConfirmCallback](checkStatus.data);
+ });
+ },
+ listenExport: function (options) {
+
+ var exportFields = {};
+
+ var imageFields = [];
+
+ var selectFields = {};
+
+ var dateFields = [];
+
+ options.cols[0].forEach(col => {
+ if (col.field) {
+
+ exportFields[col.field] = col.title;
+
+ options.cols[0].forEach(col => {
+ if (col.field) {
+
+ exportFields[col.field] = col.title;
+
+ switch (col.fieldFormat) {
+ case 'image':
+ imageFields.push(col.field);
+ break;
+
+ case 'select':
+ if (Object.keys(col.selectList).length > 0) {
+ selectFields[col.field] = col.selectList;
+ }
+ break;
+
+ case 'date':
+
+ dateFields.push(col.field);
+ break;
+
+ default:
+ break;
+ }
+
+ }
+ });
+
+ }
+ });
+
+ // excel导出
+ $('body').on('click', '[data-table-export]', function () {
+ var tableId = $(this).attr('data-table-export'),
+ url = $(this).attr('data-url');
+
+ var searchVals = form.val(tableId + '_filter_form');
+
+ var dataField = searchVals;
+
+ var formatFilter = {},
+ formatOp = {};
+ $.each(dataField, function (key, val) {
+ if (val !== '') {
+ formatFilter[key] = val;
+
+ var elemId = admin.table.renderSearchFormItemElementId(key);
+
+ var op = $('#c-' + elemId).attr('data-search-op');
+ op = op || '%*%';
+ formatOp[key] = op;
+ }
+ });
+
+ var searchQuery = {
+ filter: JSON.stringify(formatFilter),
+ op: JSON.stringify(formatOp),
+ fields: JSON.stringify(exportFields),
+ image_fields: JSON.stringify(imageFields),
+ select_fields: JSON.stringify(selectFields),
+ date_fields: JSON.stringify(dateFields),
+ };
+
+ var query = $.param(searchQuery);
+
+ var index = admin.msg.confirm('根据查询进行导出,确定导出?', function () {
+
+ toUrl = admin.url(url);
+ if (toUrl.indexOf('?') < 0) {
+ toUrl += '?';
+ } else {
+ toUrl += '&';
+ }
+ toUrl += query;
+
+ window.open(toUrl);
+
+ layer.close(index);
+ });
+ });
+ },
+ renderSearchFormItemElementId(key) {
+
+ var elemId = key;
+ if (key.indexOf('[') == 0) {
+ var keyArr = key.replace('[', '').split(']');
+
+ elemId = keyArr[0] + '-' + keyArr[1];
+ }
+
+ elemId = elemId.replace('.', '-');
+
+ return elemId;
+ }
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
+
+
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var init = ctx.init;
+ var table = ctx.table;
+ var form = ctx.layui.form;
+ var layer = ctx.layui.layer;
+
+ admin.checkMobile = function () {
+ return tools.checkMobile();
+ };
+ admin.open = function (title, url, width, height, isResize, shadeClose = false) {
+ isResize = isResize === undefined ? true : isResize;
+ var index = layer.open({
+ title: title,
+ type: 2,
+ area: [width, height],
+ content: url,
+ maxmin: true,
+ moveOut: true,
+ shadeClose: shadeClose,
+ success: function (layero, index) {
+ var body = layer.getChildFrame('body', index);
+ if (body.length > 0) {
+ $.each(body, function (i, v) {
+
+ // todo 优化弹出层背景色修改
+ $(v).before('');
});
}
},
- listenTableSelectConfirm(options) {
- $('.select-confirm').click(function () {
- var checkStatus = table.checkStatus(options.id);
+ end: function () {
+ index = null;
+ }
+ });
+ if (admin.checkMobile() || width === undefined || height === undefined) {
+ layer.full(index);
+ }
+ if (isResize) {
+ $(window).on("resize", function () {
+ index && layer.full(index);
+ });
+ }
+ };
+ admin.listen = function (preposeCallback, ok, no, ex, complete) {
- if (checkStatus.data.length == 0) {
- layer.msg('请选择数据');
- return false;
+ // 监听表单是否为必填项
+ admin.api.formRequired();
+
+ // 监听表单提交事件
+ admin.api.formSubmit(preposeCallback, ok, no, ex, complete);
+
+ // 监听按钮操作
+ admin.api.button();
+
+ // 初始化图片显示以及监听上传事件
+ admin.api.upload();
+
+ // 监听富文本初始化
+ admin.api.editor();
+
+ // 监听下拉选择生成
+ admin.api.select();
+
+ // 监听原生单选框选中
+ admin.api.nativeRadio();
+ admin.api.nativeSelect();
+
+ // 监听时间控件生成
+ admin.api.date();
+
+ // 监听通用表格数据控件生成
+ admin.api.tableData();
+ // 监听地图组件
+ admin.api.mapLocation();
+
+ // 监听标签输入控件生成
+ admin.api.tagInput();
+ // 监听属性输入控件生成
+ admin.api.propertyInput();
+
+ // 监听点击复制
+ admin.api.copyText();
+
+ // 监听点击粘贴
+ admin.api.pasteText();
+
+ // 监听tab操作
+ miniTab.listen();
+
+ // 初始化layui表单
+ form.render();
+
+ // 表格修改
+ $("body").on("mouseenter", ".table-edit-tips", function () {
+ var openTips = layer.tips('点击行内容可以进行修改', $(this), { tips: [2, '#e74c3c'], time: 4000 });
+ });
+
+ // 监听弹出层的打开
+ $('body').on('click', '[data-open]', function () {
+
+ var clienWidth = $(this).attr('data-width'),
+ clientHeight = $(this).attr('data-height'),
+ dataFull = $(this).attr('data-full'),
+ checkbox = $(this).attr('data-checkbox'),
+ url = $(this).attr('data-open'),
+ external = $(this).attr('data-external') || false,
+ tableId = $(this).attr('data-table');
+
+ if (checkbox === 'true') {
+ tableId = tableId || init.tableRenderId;
+ var checkStatus = table.checkStatus(tableId),
+ data = checkStatus.data;
+ if (data.length <= 0) {
+ admin.msg.error('请勾选需要操作的数据');
+ return false;
+ }
+ var ids = [];
+ $.each(data, function (i, v) {
+ ids.push(v.id);
+ });
+ if (url.indexOf("?") === -1) {
+ url += '?id=' + ids.join(',');
+ } else {
+ url += '&id=' + ids.join(',');
+ }
+ }
+
+ if (clienWidth === undefined || clientHeight === undefined) {
+ var width = document.body.clientWidth,
+ height = document.body.clientHeight;
+ if (width >= 800 && height >= 600) {
+ clienWidth = '800px';
+ clientHeight = '600px';
+ } else {
+ clienWidth = '100%';
+ clientHeight = '100%';
+ }
+ }
+ if (dataFull === 'true') {
+ clienWidth = '100%';
+ clientHeight = '100%';
+ }
+
+ // 如果是手机版,则直接跳转
+ if (admin.checkMobile()) {
+ location.href = external ? url : admin.url(url);
+ } else {
+ admin.open(
+ $(this).attr('data-title'),
+ external ? url : admin.url(url),
+ clienWidth,
+ clientHeight
+ );
+ }
+
+ });
+
+ // 放大图片
+ $('body').on('click', '[data-image]', function () {
+ var title = $(this).attr('data-image'),
+ src = $(this).attr('src'),
+ alt = $(this).attr('alt');
+ var photos = {
+ "title": title,
+ "id": Math.random(),
+ "data": [
+ {
+ "alt": alt,
+ "pid": Math.random(),
+ "src": src,
+ "thumb": src
+ }
+ ]
+ };
+ layer.photos({
+ photos: photos,
+ anim: 5
+ });
+ return false;
+ });
+
+ // 放大一组图片
+ $('body').on('click', '[data-images]', function () {
+ var doms = $(this).closest(".layuimini-upload-show").children("li"), // 从当前元素向上找layuimini-upload-show找到第一个后停止, 再找其所有子元素li
+ currentSrc = $(this).attr('src'), // 被点击的图片地址
+ start = 0,
+ data = [];
+ $.each(doms, function (key, value) {
+ var img = $(value).find('img'),
+ src = img.attr('src'),
+ alt = img.attr('alt');
+ data.push({
+ "alt": alt,
+ "pid": Math.random(),
+ "src": src,
+ "thumb": src
+ });
+ if (src === currentSrc) {
+ start = key;
+ }
+ });
+ var photos = {
+ "title": '',
+ "start": start,
+ "id": Math.random(),
+ "data": data,
+ };
+
+ layer.photos({
+ photos: photos,
+ anim: 5
+ });
+ return false;
+ });
+
+
+ // 监听动态表格刷新
+ $('body').on('click', '[data-table-refresh]', function () {
+ var tableId = $(this).attr('data-table-refresh');
+ if (tableId === undefined || tableId === '' || tableId == null) {
+ tableId = init.tableRenderId;
+ }
+ table.reloadData(tableId);
+ });
+
+ // 监听搜索表格重置
+ $('body').on('click', '[data-table-reset]', function () {
+ var tableId = $(this).attr('data-table-reset');
+ if (tableId === undefined || tableId === '' || tableId == null) {
+ tableId = init.tableRenderId;
+ }
+
+ setTimeout(() => {
+ var searchVals = form.val(tableId + '_filter_form');
+ var dataField = searchVals;
+ var formatFilter = {},
+ formatOp = {};
+ $.each(dataField, function (key, val) {
+ if (val !== '') {
+ formatFilter[key] = val;
+
+ var elemId = admin.table.renderSearchFormItemElementId(key);
+
+ var op = $('#c-' + elemId).attr('data-search-op');
+ op = op || '%*%';
+ formatOp[key] = op;
+ }
+ });
+
+ var where = {
+ filter: JSON.stringify(formatFilter),
+ op: JSON.stringify(formatOp)
+ };
+ table.reloadData(tableId, {
+ page: {
+ curr: 1
+ }
+ , where: where
+ }, 'data');
+ }, 100);
+ });
+
+ // 监听请求
+ $('body').on('click', '[data-request]', function () {
+ var title = $(this).attr('data-title'),
+ url = $(this).attr('data-request'),
+ tableId = $(this).attr('data-table'),
+ checkbox = $(this).attr('data-checkbox'),
+ direct = $(this).attr('data-direct'),
+ field = $(this).attr('data-field') || 'id',
+ endMethod = $(this).attr('data-end-method') || 'reload-table';
+
+ title = title || '确定进行该操作?';
+
+ if (direct === 'true') {
+ admin.msg.confirm(title, function () {
+ window.location.href = url;
+ });
+ return false;
+ }
+
+ var postData = {};
+ if (checkbox === 'true') {
+ tableId = tableId || init.tableRenderId;
+ var checkStatus = table.checkStatus(tableId),
+ data = checkStatus.data;
+ if (data.length <= 0) {
+ admin.msg.error('请勾选需要操作的数据');
+ return false;
+ }
+ var ids = [];
+ $.each(data, function (i, v) {
+ ids.push(v[field]);
+ });
+ postData[field] = ids;
+ }
+
+ url = admin.url(url);
+
+ admin.msg.confirm(title, function () {
+ admin.request.post({
+ url: url,
+ data: postData,
+ }, function (res) {
+ admin.msg.success(res.msg, function () {
+ if (endMethod == 'reload-table') {
+ tableId = tableId || init.tableRenderId;
+ table.reloadData(tableId);
+ } else if (endMethod == 'refresh-page') {
+ location.reload();
+ }
+ });
+ });
+ });
+ return false;
+ });
+
+
+
+ // 数据表格多删除
+ $('body').on('click', '[data-table-delete]', function () {
+ var tableId = $(this).attr('data-table-delete'),
+ url = $(this).attr('data-url');
+ tableId = tableId || init.tableRenderId;
+ url = url !== undefined ? admin.url(url) : window.location.href;
+ var checkStatus = table.checkStatus(tableId),
+ data = checkStatus.data;
+ if (data.length <= 0) {
+ admin.msg.error('请勾选需要删除的数据');
+ return false;
+ }
+ var ids = [];
+ $.each(data, function (i, v) {
+ ids.push(v.id);
+ });
+ admin.msg.confirm('确定删除?', function () {
+ admin.request.post({
+ url: url,
+ data: {
+ id: ids
+ },
+ }, function (res) {
+ admin.msg.success(res.msg, function () {
+ table.reloadData(tableId);
+ });
+ });
+ });
+ return false;
+ });
+
+ };
+
+ window.ulAdmin = window.ua = admin;
+})();
+
+
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var init = ctx.init;
+ var table = ctx.table;
+ var form = ctx.layui.form;
+ var layer = ctx.layui.layer;
+ var laydate = ctx.layui.laydate;
+ var upload = ctx.layui.upload;
+ var extGroup = ctx.extGroup;
+ var createEditor = ctx.createEditor;
+ var createToolbar = ctx.createToolbar;
+
+ admin.api = {
+ button: function () {
+ $('button[target="_blank"]').click(function () {
+ window.open(admin.url($(this).attr('href')));
+ });
+ },
+
+ closeCurrentOpen: function (option) {
+ option = option || {};
+ option.backHref = option.backHref || '';
+ option.refreshTable = option.refreshTable || false;
+ option.refreshFrame = option.refreshFrame || false;
+ option.onClose = option.onClose || function () { };
+ if (option.refreshTable === true) {
+ option.refreshTable = init.tableRenderId;
+ }
+ var backWindow = window.parent;
+ if (option.backHref) {
+ // 标签打开页面,需要返回上一个标签刷新的情况
+ backWindow = admin.findPageId(option.backHref);
+ if (backWindow) {
+ backWindow.layui.table.reloadData(option.refreshTable);
+ } else {
+ admin.findIndexPage(function (w) {
+ var menu = w.miniTab.searchMenu(option.backHref);
+ var title = option.backHref;
+
+ if (menu) {
+ title = menu.title;
+ }
+ w.miniTab.create({
+ tabId: option.backHref,
+ href: option.backHref,
+ title: title,
+ });
+ });
+ }
+ admin.findIndexPage(function (w) {
+ w.layui.element.tabDelete('layuiminiTab', admin.getCurrentPageId());
+ w.layui.element.tabChange('layuiminiTab', option.backHref);
+ });
+ return;
+ }
+ // 弹框保存后刷新的情况
+ var index = parent.layer.getFrameIndex(window.name);
+ backWindow.layer.close(index, option.onClose);
+ if (option.refreshTable !== false) {
+ backWindow.layui.table.reloadData(option.refreshTable);
+ }
+ if (option.refreshFrame) {
+ backWindow.location.reload();
+ }
+ return false;
+ },
+ refreshFrame: function () {
+ parent.location.reload();
+ return false;
+ },
+ refreshTable: function (tableName, mode) {
+ tableName = tableName || 'currentTableRenderId';
+ if (mode == 'table') {
+ table.reload(tableName);
+ } else {
+ table.reloadData(tableName);
+ }
+ },
+ // var options = {
+ // url :'system.menu/index?id=1'
+ // }
+ // ua.api.reloadTable('currentTableRenderId',options)
+ reloadTable: function (tableName, options, mode) {
+ tableName = tableName || 'currentTableRenderId';
+ if (mode == 'table') {
+ table.reload(tableName, options);
+ } else {
+ table.reloadData(tableName, options);
+ }
+ },
+ formRequired: function () {
+ var verifyList = document.querySelectorAll("[lay-verify]");
+ if (verifyList.length > 0) {
+ $.each(verifyList, function (i, v) {
+ var verify = $(this).attr('lay-verify');
+
+ // todo 必填项处理
+ if (verify.includes('required')) {
+ var label = $(this).parent().prev();
+ if (label.is('label') && !label.hasClass('required')) {
+ label.addClass('required');
+ }
+ if ($(this).attr('lay-reqtext') === undefined && $(this).attr('placeholder') !== undefined) {
+ $(this).attr('lay-reqtext', $(this).attr('placeholder'));
+ }
+ if ($(this).attr('placeholder') === undefined && $(this).attr('lay-reqtext') !== undefined) {
+ $(this).attr('placeholder', $(this).attr('lay-reqtext'));
+ }
}
- parent.window[selectConfirmCallback](checkStatus.data);
});
- },
- listenExport: function (options) {
+ }
+ },
+ formSubmit: function (preposeCallback, ok, no, ex, complete) {
+ var formList = document.querySelectorAll("[lay-submit]");
- var exportFields = {};
+ // 表单提交自动处理
+ if (formList.length > 0) {
+ $.each(formList, function (i, v) {
+ var filter = $(this).attr('lay-filter'),
+ type = $(this).attr('data-type'),
+ refresh = $(this).attr('data-refresh'),
+ close = $(this).attr('data-close'),
+ url = $(this).attr('lay-submit');
+ // 表格搜索不做自动提交
+ if (type === 'tableSearch') {
+ return false;
+ }
+ // 判断是否需要刷新表格
+ if (refresh === 'false') {
+ refresh = false;
+ } else {
+ refresh = true;
+ }
+ if (close === 'false') {
+ close = false;
+ } else {
+ close = true;
+ }
+ // 自动添加layui事件过滤器
+ if (filter === undefined || filter === '') {
+ filter = 'save_form_' + (i + 1);
+ $(this).attr('lay-filter', filter);
+ }
+ if (url === undefined || url === '' || url === null) {
+ url = window.location.href;
+ } else {
+ url = admin.url(url);
+ }
+ form.on('submit(' + filter + ')', function (data) {
- var imageFields = [];
+ var btnElem = data.elem;
- var selectFields = {};
+ var form = $(this).closest('form');
+ if ($(form).hasClass('loading')) return false;
+ $(form).addClass('loading');
- var dateFields = [];
+ // 判断btn是否具备name和value属性,如果有,则加到表单数据里
+ var btnName = $(btnElem).attr('name');
+ var btnValue = $(btnElem).attr('value');
+ var backHref = $(btnElem).attr('data-back-href');
+ if (btnName !== undefined && btnValue !== undefined) {
+ data.field[btnName] = btnValue;
+ }
+ if (!backHref) {
+ backHref = admin.getQueryVariable('backTagId');
+ }
- options.cols[0].forEach(col => {
- if (col.field) {
+ var dataField = data.field;
+ dataField = admin.api.formSubmitEditor(dataField, v);
+ dataField = admin.api.formSubmitCity(dataField, v);
- exportFields[col.field] = col.title;
+ if (typeof preposeCallback === 'function') {
+ dataField = preposeCallback(dataField);
+ }
+ complete = complete || function () {
+ $(form).removeClass('loading');
+ };
- options.cols[0].forEach(col => {
- if (col.field) {
+ if (ok) {
+ var originalOk = ok;
+ ok = function (res) {
+ originalOk(res);
+ complete();
+ };
+ } else {
+ ok = function (res) {
+ res.msg = res.msg || '';
+ admin.msg.success(res.msg, function () {
+ if (close) {
- exportFields[col.field] = col.title;
+ admin.api.closeCurrentOpen({
+ refreshTable: refresh,
+ backHref: backHref,
+ onClose: function () {
+ complete();
+ }
+ });
- switch (col.fieldFormat) {
- case 'image':
- imageFields.push(col.field);
- break;
+ }
+ });
+ return false;
+ };
+ }
- case 'select':
- if (Object.keys(col.selectList).length > 0) {
- selectFields[col.field] = col.selectList;
+ admin.request.post({
+ url: url,
+ data: dataField,
+ }, ok, no, ex, complete);
+
+ return false;
+ });
+ });
+ }
+
+ },
+ formSubmitEditor(dataField, form) {
+ return dataField;
+ },
+
+ formSubmitCity(dataField, form) {
+
+ var cityList = $(form).closest('.layui-form').find('[data-toggle="city-picker"]');
+
+ if (cityList.length > 0) {
+ $.each(cityList, function (i, v) {
+
+ var fieldName = $(v).attr('name');
+ var code = $(v).data('citypicker').getCode();
+ var text = $(v).data('citypicker').getVal();
+ var level = $(v).data('level');
+ var formatTargetList = {};
+
+ formatTargetList['name'] = 1;
+ formatTargetList['code'] = 1;
+ formatTargetList['name-province'] = 1;
+ formatTargetList['name-city'] = 1;
+ formatTargetList['name-district'] = 1;
+ formatTargetList['code-province'] = 1;
+ formatTargetList['code-city'] = 1;
+ formatTargetList['code-district'] = 1;
+
+
+ $.each(formatTargetList, function (targetType, value) {
+
+ var valueSet = $(v).data('field-' + targetType);
+
+ if (valueSet == 0) {
+ formatTargetList[targetType] = 0;
+ }
+
+ });
+
+ var codeArr = code.split('/');
+ var textArr = text.split('/');
+
+ if (formatTargetList['name'] == 1) {
+ dataField[fieldName] = text;
+ }
+ if (formatTargetList['code'] == 1) {
+ dataField[fieldName + '_code'] = code;
+ }
+ if (formatTargetList['name-province'] == 1) {
+ dataField[fieldName + '_name_province'] = textArr[0] || '';
+ }
+ if (formatTargetList['name-city'] == 1) {
+ dataField[fieldName + '_name_city'] = textArr[1] || '';
+ }
+ if (formatTargetList['name-district'] == 1) {
+ dataField[fieldName + '_name_district'] = textArr[2] || '';
+ }
+ if (formatTargetList['code-province'] == 1) {
+ dataField[fieldName + '_code_province'] = codeArr[0] || '';
+ }
+ if (formatTargetList['code-city'] == 1) {
+ dataField[fieldName + '_code_city'] = codeArr[1] || '';
+ }
+ if (formatTargetList['code-district'] == 1) {
+ dataField[fieldName + '_code_district'] = codeArr[2] || '';
+ }
+
+ });
+ }
+ return dataField;
+ },
+ upload: function () {
+ var uploadList = document.querySelectorAll("[data-upload]");
+ var uploadSelectList = document.querySelectorAll("[data-upload-select]");
+
+ if (uploadList.length > 0) {
+ $.each(uploadList, function (i, v) {
+ var uploadExts = $(this).attr('data-upload-exts'),
+ uploadName = $(this).attr('data-upload'),
+ uploadNumber = $(this).attr('data-upload-number') || 'one',
+ uploadSign = $(this).attr('data-upload-sign') || '|',
+ uploadAccept = $(this).attr('data-upload-accept') || 'file',
+ uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
+ uploadDisablePreview = $(this).attr('data-upload-disable-preview') || '0',
+ uploadFilenameField = $(this).attr('data-upload-filename-field') || '',
+ elem = "input[name='" + uploadName + "']",
+
+ uploadElem = this;
+ if (uploadFilenameField) {
+ var elemFilenameField = "[name='" + uploadFilenameField + "']";
+ }
+ if (uploadExts == '*') {
+ uploadExts = init.uploadExts;
+ } else if (uploadExts.charAt(0) == '*') {
+ var extGroupName = uploadExts.slice(1);
+ if (extGroup[extGroupName]) {
+ uploadExts = extGroup[extGroupName].join('|');
+ }
+ }
+
+ // 监听上传事件
+ upload.render({
+ elem: this,
+ url: admin.url(init.uploadUrl),
+ exts: uploadExts,
+ accept: uploadAccept,//指定允许上传时校验的文件类型
+ acceptMime: uploadAcceptMime,//规定打开文件选择框时,筛选出的文件类型
+ multiple: uploadNumber !== 'one',//是否多文件上传
+ headers: admin.headers(),
+ done: function (res) {
+ if (res.code === 0) {
+ var url = res.data.url;
+ var filename = res.data.original_name;
+ if (uploadNumber !== 'one') {
+ var oldUrl = $(elem).val();
+ if (oldUrl !== '') {
+ url = oldUrl + uploadSign + url;
+ }
+ if (elemFilenameField) {
+ var oldFilename = $(elemFilenameField).val();
+ if (oldFilename !== '') {
+ filename = oldFilename + uploadSign + filename;
}
- break;
- case 'date':
- dateFields.push(col.field);
- break;
+ }
+ }
+ if (elemFilenameField) {
+ $(elemFilenameField).val(filename);
+ }
+ $(elem).val(url);
+ $(elem).trigger("input");
+ admin.msg.success(res.msg);
+ } else {
+ admin.msg.error(res.msg);
+ }
+ return false;
+ }
+ });
- default:
- break;
+ if (uploadDisablePreview == 0) {
+ // 监听上传input值变化
+ $(elem).bind("input propertychange", function (event) {
+ var urlString = $(this).val(),
+ urlArray = urlString.split(uploadSign),
+ uploadIcon = $(uploadElem).attr('data-upload-icon') || "file";
+ var uploadNameKey = uploadName.replace(/\[/g, "-").replace(/\]/g, "-");
+ $('#bing-' + uploadNameKey).remove();
+ if (urlString.length > 0) {
+ var parant = $(this).parent('div');
+ var liHtml = '';
+ var filenameArray = [];
+ if (uploadFilenameField) {
+ var filenameVal = $(elemFilenameField).val() || '';
+ if (filenameVal) {
+ filenameArray = filenameVal.split(uploadSign);
+ }
}
+ $.each(urlArray, function (i, v) {
+
+ // 获取链接扩展名
+ var ext = v.substr(v.lastIndexOf('.') + 1);
+ var currentFilename = filenameArray[i] || '';
+ currentFilename = currentFilename.replace(/"/g, '"');
+
+ if (extGroup.image.indexOf(ext) != -1) {
+ // 是图片
+ liHtml += '
×\n';
+ } else {
+ // 不是图片
+ // 遍历extGroup数组找到扩展名所在的索引
+
+ uploadIcon = admin.getExtGroupName(ext);
+
+ liHtml += '
×\n';
+
+ }
+
+ });
+ parant.after('');
+
+ var initSortable = function () {
+ var el = document.getElementById('bing-' + uploadNameKey);
+ if (el) {
+ new Sortable(el, {
+ animation: 150,
+ onEnd: function (evt) {
+ var newUrls = [];
+ var newFilenames = [];
+ $(el).find('.uploads-delete-tip').each(function () {
+ newUrls.push($(this).attr('data-upload-url'));
+ newFilenames.push($(this).attr('data-upload-filename'));
+ });
+ $(elem).val(newUrls.join(uploadSign));
+ if (uploadFilenameField) {
+ $(elemFilenameField).val(newFilenames.join(uploadSign));
+ }
+ $(elem).trigger("input");
+ }
+ });
+ }
+ };
+
+ initSortable();
}
+
});
- }
- });
-
- // excel导出
- $('body').on('click', '[data-table-export]', function () {
- var tableId = $(this).attr('data-table-export'),
- url = $(this).attr('data-url');
-
- var searchVals = form.val(tableId + '_filter_form');
-
- var dataField = searchVals;
-
- var formatFilter = {},
- formatOp = {};
- $.each(dataField, function (key, val) {
- if (val !== '') {
- formatFilter[key] = val;
-
- var elemId = admin.table.renderSearchFormItemElementId(key);
-
- var op = $('#c-' + elemId).attr('data-search-op');
- op = op || '%*%';
- formatOp[key] = op;
+ // 非空初始化图片显示
+ if ($(elem).val() !== '') {
+ $(elem).trigger("input");
}
- });
+ }
- var searchQuery = {
- filter: JSON.stringify(formatFilter),
- op: JSON.stringify(formatOp),
- fields: JSON.stringify(exportFields),
- image_fields: JSON.stringify(imageFields),
- select_fields: JSON.stringify(selectFields),
- date_fields: JSON.stringify(dateFields),
- };
+ });
- var query = $.param(searchQuery);
+ // 监听上传文件的删除事件
+ $('body').on('click', '[data-upload-delete]', function () {
+ var uploadName = $(this).attr('data-upload-delete'),
+ deleteUrl = $(this).attr('data-upload-url'),
+ uploadFilenameField = $(this).attr('data-upload-filename-field'),
+ sign = $(this).attr('data-upload-sign');
+ var confirm = admin.msg.confirm('确定删除?', function () {
+ var elem = "input[name='" + uploadName + "']";
+ var elemFilenameField = "[name='" + uploadFilenameField + "']";
+ var currentUrl = $(elem).val();
+ var currentFilename = $(elemFilenameField).val();
- var index = admin.msg.confirm('根据查询进行导出,确定导出?', function () {
+ var currentUrlList = currentUrl.split(sign);
+ var deleteIndex = currentUrlList.indexOf(deleteUrl);
- toUrl = admin.url(url);
- if (toUrl.indexOf('?') < 0) {
- toUrl += '?';
- } else {
- toUrl += '&';
+ currentUrlList.splice(deleteIndex, 1);
+ $(elem).val(currentUrlList.join(sign));
+ $(elem).trigger("input");
+
+ if (currentFilename) {
+
+ var currentFilenameList = currentFilename.split(sign);
+ currentFilenameList.splice(deleteIndex, 1);
+
+ $(elemFilenameField).val(currentFilenameList.join(sign));
}
- toUrl += query;
- window.open(toUrl);
-
- layer.close(index);
+ admin.msg.close(confirm);
});
- });
- },
- renderSearchFormItemElementId(key) {
-
- var elemId = key;
- if (key.indexOf('[') == 0) {
- var keyArr = key.replace('[', '').split(']');
-
- elemId = keyArr[0] + '-' + keyArr[1];
- }
-
- elemId = elemId.replace('.', '-');
-
- return elemId;
- }
- },
- checkMobile: function () {
- return tools.checkMobile();
- },
- open: function (title, url, width, height, isResize, shadeClose = false) {
- isResize = isResize === undefined ? true : isResize;
- var index = layer.open({
- title: title,
- type: 2,
- area: [width, height],
- content: url,
- maxmin: true,
- moveOut: true,
- shadeClose: shadeClose,
- success: function (layero, index) {
- var body = layer.getChildFrame('body', index);
- if (body.length > 0) {
- $.each(body, function (i, v) {
-
- // todo 优化弹出层背景色修改
- $(v).before('');
- });
- }
- },
- end: function () {
- index = null;
- }
- });
- if (admin.checkMobile() || width === undefined || height === undefined) {
- layer.full(index);
- }
- if (isResize) {
- $(window).on("resize", function () {
- index && layer.full(index);
+ return false;
});
}
- },
- listen: function (preposeCallback, ok, no, ex, complete) {
- // 监听表单是否为必填项
- admin.api.formRequired();
+ if (uploadSelectList.length > 0) {
+ $.each(uploadSelectList, function (i, v) {
+ var uploadName = $(this).attr('data-upload-select'),
+ uploadNumber = $(this).attr('data-upload-number') || 'one',
+ uploadSign = $(this).attr('data-upload-sign') || '|',
+ uploadFilenameField = $(this).attr('data-upload-filename-field') || '';
- // 监听表单提交事件
- admin.api.formSubmit(preposeCallback, ok, no, ex, complete);
-
- // 监听按钮操作
- admin.api.button();
-
- // 初始化图片显示以及监听上传事件
- admin.api.upload();
-
- // 监听富文本初始化
- admin.api.editor();
-
- // 监听下拉选择生成
- admin.api.select();
-
- // 监听原生单选框选中
- admin.api.nativeRadio();
- admin.api.nativeSelect();
-
- // 监听时间控件生成
- admin.api.date();
-
- // 监听通用表格数据控件生成
- admin.api.tableData();
- // 监听地图组件
- admin.api.mapLocation();
-
- // 监听标签输入控件生成
- admin.api.tagInput();
- // 监听属性输入控件生成
- admin.api.propertyInput();
-
- // 监听点击复制
- admin.api.copyText();
-
- // 监听点击粘贴
- admin.api.pasteText();
-
- // 监听tab操作
- miniTab.listen();
-
- // 初始化layui表单
- form.render();
-
- // 表格修改
- $("body").on("mouseenter", ".table-edit-tips", function () {
- var openTips = layer.tips('点击行内容可以进行修改', $(this), { tips: [2, '#e74c3c'], time: 4000 });
- });
-
- // 监听弹出层的打开
- $('body').on('click', '[data-open]', function () {
-
- var clienWidth = $(this).attr('data-width'),
- clientHeight = $(this).attr('data-height'),
- dataFull = $(this).attr('data-full'),
- checkbox = $(this).attr('data-checkbox'),
- url = $(this).attr('data-open'),
- external = $(this).attr('data-external') || false,
- tableId = $(this).attr('data-table');
-
- if (checkbox === 'true') {
- tableId = tableId || init.tableRenderId;
- var checkStatus = table.checkStatus(tableId),
- data = checkStatus.data;
- if (data.length <= 0) {
- admin.msg.error('请勾选需要操作的数据');
- return false;
+ if (uploadFilenameField) {
+ var elemFilenameField = "[name='" + uploadFilenameField + "']";
+ var elemFilename = $(elemFilenameField);
}
- var ids = [];
- $.each(data, function (i, v) {
- ids.push(v.id);
- });
- if (url.indexOf("?") === -1) {
- url += '?id=' + ids.join(',');
- } else {
- url += '&id=' + ids.join(',');
- }
- }
- if (clienWidth === undefined || clientHeight === undefined) {
+ var selectCheck = uploadNumber === 'one' ? 'radio' : 'checkbox';
+ var elem = "input[name='" + uploadName + "']";
var width = document.body.clientWidth,
height = document.body.clientHeight;
+
if (width >= 800 && height >= 600) {
clienWidth = '800px';
clientHeight = '600px';
@@ -2058,1201 +2749,521 @@
clienWidth = '100%';
clientHeight = '100%';
}
- }
- if (dataFull === 'true') {
- clienWidth = '100%';
- clientHeight = '100%';
- }
- // 如果是手机版,则直接跳转
- if (admin.checkMobile()) {
- location.href = external ? url : admin.url(url);
- } else {
- admin.open(
- $(this).attr('data-title'),
- external ? url : admin.url(url),
- clienWidth,
- clientHeight
- );
- }
-
- });
-
- // 放大图片
- $('body').on('click', '[data-image]', function () {
- var title = $(this).attr('data-image'),
- src = $(this).attr('src'),
- alt = $(this).attr('alt');
- var photos = {
- "title": title,
- "id": Math.random(),
- "data": [
- {
- "alt": alt,
- "pid": Math.random(),
- "src": src,
- "thumb": src
- }
- ]
- };
- layer.photos({
- photos: photos,
- anim: 5
- });
- return false;
- });
-
- // 放大一组图片
- $('body').on('click', '[data-images]', function () {
- var doms = $(this).closest(".layuimini-upload-show").children("li"), // 从当前元素向上找layuimini-upload-show找到第一个后停止, 再找其所有子元素li
- currentSrc = $(this).attr('src'), // 被点击的图片地址
- start = 0,
- data = [];
- $.each(doms, function (key, value) {
- var img = $(value).find('img'),
- src = img.attr('src'),
- alt = img.attr('alt');
- data.push({
- "alt": alt,
- "pid": Math.random(),
- "src": src,
- "thumb": src
- });
- if (src === currentSrc) {
- start = key;
- }
- });
- var photos = {
- "title": '',
- "start": start,
- "id": Math.random(),
- "data": data,
- };
-
- layer.photos({
- photos: photos,
- anim: 5
- });
- return false;
- });
-
-
- // 监听动态表格刷新
- $('body').on('click', '[data-table-refresh]', function () {
- var tableId = $(this).attr('data-table-refresh');
- if (tableId === undefined || tableId === '' || tableId == null) {
- tableId = init.tableRenderId;
- }
- table.reloadData(tableId);
- });
-
- // 监听搜索表格重置
- $('body').on('click', '[data-table-reset]', function () {
- var tableId = $(this).attr('data-table-reset');
- if (tableId === undefined || tableId === '' || tableId == null) {
- tableId = init.tableRenderId;
- }
-
- setTimeout(() => {
- var searchVals = form.val(tableId + '_filter_form');
- var dataField = searchVals;
- var formatFilter = {},
- formatOp = {};
- $.each(dataField, function (key, val) {
- if (val !== '') {
- formatFilter[key] = val;
-
- var elemId = admin.table.renderSearchFormItemElementId(key);
-
- var op = $('#c-' + elemId).attr('data-search-op');
- op = op || '%*%';
- formatOp[key] = op;
- }
- });
-
- var where = {
- filter: JSON.stringify(formatFilter),
- op: JSON.stringify(formatOp)
- };
- table.reloadData(tableId, {
- page: {
- curr: 1
- }
- , where: where
- }, 'data');
- }, 100);
- });
-
- // 监听请求
- $('body').on('click', '[data-request]', function () {
- var title = $(this).attr('data-title'),
- url = $(this).attr('data-request'),
- tableId = $(this).attr('data-table'),
- checkbox = $(this).attr('data-checkbox'),
- direct = $(this).attr('data-direct'),
- field = $(this).attr('data-field') || 'id',
- endMethod = $(this).attr('data-end-method') || 'reload-table';
-
- title = title || '确定进行该操作?';
-
- if (direct === 'true') {
- admin.msg.confirm(title, function () {
- window.location.href = url;
- });
- return false;
- }
-
- var postData = {};
- if (checkbox === 'true') {
- tableId = tableId || init.tableRenderId;
- var checkStatus = table.checkStatus(tableId),
- data = checkStatus.data;
- if (data.length <= 0) {
- admin.msg.error('请勾选需要操作的数据');
- return false;
- }
- var ids = [];
- $.each(data, function (i, v) {
- ids.push(v[field]);
- });
- postData[field] = ids;
- }
-
- url = admin.url(url);
-
- admin.msg.confirm(title, function () {
- admin.request.post({
- url: url,
- data: postData,
- }, function (res) {
- admin.msg.success(res.msg, function () {
- if (endMethod == 'reload-table') {
- tableId = tableId || init.tableRenderId;
- table.reloadData(tableId);
- } else if (endMethod == 'refresh-page') {
- location.reload();
- }
- });
- });
- });
- return false;
- });
-
-
-
- // 数据表格多删除
- $('body').on('click', '[data-table-delete]', function () {
- var tableId = $(this).attr('data-table-delete'),
- url = $(this).attr('data-url');
- tableId = tableId || init.tableRenderId;
- url = url !== undefined ? admin.url(url) : window.location.href;
- var checkStatus = table.checkStatus(tableId),
- data = checkStatus.data;
- if (data.length <= 0) {
- admin.msg.error('请勾选需要删除的数据');
- return false;
- }
- var ids = [];
- $.each(data, function (i, v) {
- ids.push(v.id);
- });
- admin.msg.confirm('确定删除?', function () {
- admin.request.post({
- url: url,
- data: {
- id: ids
- },
- }, function (res) {
- admin.msg.success(res.msg, function () {
- table.reloadData(tableId);
- });
- });
- });
- return false;
- });
-
- },
- api: {
- button: function () {
- $('button[target="_blank"]').click(function () {
- window.open(admin.url($(this).attr('href')));
- });
- },
-
- closeCurrentOpen: function (option) {
- option = option || {};
- option.backHref = option.backHref || '';
- option.refreshTable = option.refreshTable || false;
- option.refreshFrame = option.refreshFrame || false;
- option.onClose = option.onClose || function () { };
- if (option.refreshTable === true) {
- option.refreshTable = init.tableRenderId;
- }
- var backWindow = window.parent;
- if (option.backHref) {
- // 标签打开页面,需要返回上一个标签刷新的情况
- backWindow = admin.findPageId(option.backHref);
- if (backWindow) {
- backWindow.layui.table.reloadData(option.refreshTable);
- } else {
- admin.findIndexPage(function (w) {
- var menu = w.miniTab.searchMenu(option.backHref);
- var title = option.backHref;
-
- if (menu) {
- title = menu.title;
- }
- w.miniTab.create({
- tabId: option.backHref,
- href: option.backHref,
- title: title,
- });
- });
- }
- admin.findIndexPage(function (w) {
- w.layui.element.tabDelete('layuiminiTab', admin.getCurrentPageId());
- w.layui.element.tabChange('layuiminiTab', option.backHref);
- });
- return;
- }
- // 弹框保存后刷新的情况
- var index = parent.layer.getFrameIndex(window.name);
- backWindow.layer.close(index, option.onClose);
- if (option.refreshTable !== false) {
- backWindow.layui.table.reloadData(option.refreshTable);
- }
- if (option.refreshFrame) {
- backWindow.location.reload();
- }
- return false;
- },
- refreshFrame: function () {
- parent.location.reload();
- return false;
- },
- refreshTable: function (tableName, mode) {
- tableName = tableName || 'currentTableRenderId';
- if (mode == 'table') {
- table.reload(tableName);
- } else {
- table.reloadData(tableName);
- }
- },
- // var options = {
- // url :'system.menu/index?id=1'
- // }
- // ua.api.reloadTable('currentTableRenderId',options)
- reloadTable: function (tableName, options, mode) {
- tableName = tableName || 'currentTableRenderId';
- if (mode == 'table') {
- table.reload(tableName, options);
- } else {
- table.reloadData(tableName, options);
- }
- },
- formRequired: function () {
- var verifyList = document.querySelectorAll("[lay-verify]");
- if (verifyList.length > 0) {
- $.each(verifyList, function (i, v) {
- var verify = $(this).attr('lay-verify');
-
- // todo 必填项处理
- if (verify.includes('required')) {
- var label = $(this).parent().prev();
- if (label.is('label') && !label.hasClass('required')) {
- label.addClass('required');
- }
- if ($(this).attr('lay-reqtext') === undefined && $(this).attr('placeholder') !== undefined) {
- $(this).attr('lay-reqtext', $(this).attr('placeholder'));
- }
- if ($(this).attr('placeholder') === undefined && $(this).attr('lay-reqtext') !== undefined) {
- $(this).attr('placeholder', $(this).attr('lay-reqtext'));
- }
- }
-
- });
- }
- },
- formSubmit: function (preposeCallback, ok, no, ex, complete) {
- var formList = document.querySelectorAll("[lay-submit]");
-
- // 表单提交自动处理
- if (formList.length > 0) {
- $.each(formList, function (i, v) {
- var filter = $(this).attr('lay-filter'),
- type = $(this).attr('data-type'),
- refresh = $(this).attr('data-refresh'),
- close = $(this).attr('data-close'),
- url = $(this).attr('lay-submit');
- // 表格搜索不做自动提交
- if (type === 'tableSearch') {
- return false;
- }
- // 判断是否需要刷新表格
- if (refresh === 'false') {
- refresh = false;
- } else {
- refresh = true;
- }
- if (close === 'false') {
- close = false;
- } else {
- close = true;
- }
- // 自动添加layui事件过滤器
- if (filter === undefined || filter === '') {
- filter = 'save_form_' + (i + 1);
- $(this).attr('lay-filter', filter);
- }
- if (url === undefined || url === '' || url === null) {
- url = window.location.href;
- } else {
- url = admin.url(url);
- }
- form.on('submit(' + filter + ')', function (data) {
-
- var btnElem = data.elem;
-
- var form = $(this).closest('form');
- if ($(form).hasClass('loading')) return false;
- $(form).addClass('loading');
-
- // 判断btn是否具备name和value属性,如果有,则加到表单数据里
- var btnName = $(btnElem).attr('name');
- var btnValue = $(btnElem).attr('value');
- var backHref = $(btnElem).attr('data-back-href');
- if (btnName !== undefined && btnValue !== undefined) {
- data.field[btnName] = btnValue;
- }
- if (!backHref) {
- backHref = admin.getQueryVariable('backTagId');
- }
-
- var dataField = data.field;
- dataField = admin.api.formSubmitEditor(dataField, v);
- dataField = admin.api.formSubmitCity(dataField, v);
-
- if (typeof preposeCallback === 'function') {
- dataField = preposeCallback(dataField);
- }
- complete = complete || function () {
- $(form).removeClass('loading');
- };
-
- if (ok) {
- var originalOk = ok;
- ok = function (res) {
- originalOk(res);
- complete();
- };
- } else {
- ok = function (res) {
- res.msg = res.msg || '';
- admin.msg.success(res.msg, function () {
- if (close) {
-
- admin.api.closeCurrentOpen({
- refreshTable: refresh,
- backHref: backHref,
- onClose: function () {
- complete();
- }
- });
-
- }
- });
- return false;
- };
- }
-
- admin.request.post({
- url: url,
- data: dataField,
- }, ok, no, ex, complete);
-
- return false;
- });
- });
- }
-
- },
- formSubmitEditor(dataField, form) {
- return dataField;
- },
-
- formSubmitCity(dataField, form) {
-
- var cityList = $(form).closest('.layui-form').find('[data-toggle="city-picker"]');
-
- if (cityList.length > 0) {
- $.each(cityList, function (i, v) {
-
- var fieldName = $(v).attr('name');
- var code = $(v).data('citypicker').getCode();
- var text = $(v).data('citypicker').getVal();
- var level = $(v).data('level');
- var formatTargetList = {};
-
- formatTargetList['name'] = 1;
- formatTargetList['code'] = 1;
- formatTargetList['name-province'] = 1;
- formatTargetList['name-city'] = 1;
- formatTargetList['name-district'] = 1;
- formatTargetList['code-province'] = 1;
- formatTargetList['code-city'] = 1;
- formatTargetList['code-district'] = 1;
-
-
- $.each(formatTargetList, function (targetType, value) {
-
- var valueSet = $(v).data('field-' + targetType);
-
- if (valueSet == 0) {
- formatTargetList[targetType] = 0;
- }
-
- });
-
- var codeArr = code.split('/');
- var textArr = text.split('/');
-
- if (formatTargetList['name'] == 1) {
- dataField[fieldName] = text;
- }
- if (formatTargetList['code'] == 1) {
- dataField[fieldName + '_code'] = code;
- }
- if (formatTargetList['name-province'] == 1) {
- dataField[fieldName + '_name_province'] = textArr[0] || '';
- }
- if (formatTargetList['name-city'] == 1) {
- dataField[fieldName + '_name_city'] = textArr[1] || '';
- }
- if (formatTargetList['name-district'] == 1) {
- dataField[fieldName + '_name_district'] = textArr[2] || '';
- }
- if (formatTargetList['code-province'] == 1) {
- dataField[fieldName + '_code_province'] = codeArr[0] || '';
- }
- if (formatTargetList['code-city'] == 1) {
- dataField[fieldName + '_code_city'] = codeArr[1] || '';
- }
- if (formatTargetList['code-district'] == 1) {
- dataField[fieldName + '_code_district'] = codeArr[2] || '';
- }
-
- });
- }
- return dataField;
- },
- upload: function () {
- var uploadList = document.querySelectorAll("[data-upload]");
- var uploadSelectList = document.querySelectorAll("[data-upload-select]");
-
- if (uploadList.length > 0) {
- $.each(uploadList, function (i, v) {
- var uploadExts = $(this).attr('data-upload-exts'),
- uploadName = $(this).attr('data-upload'),
- uploadNumber = $(this).attr('data-upload-number') || 'one',
- uploadSign = $(this).attr('data-upload-sign') || '|',
- uploadAccept = $(this).attr('data-upload-accept') || 'file',
- uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
- uploadDisablePreview = $(this).attr('data-upload-disable-preview') || '0',
- uploadFilenameField = $(this).attr('data-upload-filename-field') || '',
- elem = "input[name='" + uploadName + "']",
-
- uploadElem = this;
- if (uploadFilenameField) {
- var elemFilenameField = "[name='" + uploadFilenameField + "']";
- }
- if (uploadExts == '*') {
- uploadExts = init.uploadExts;
- } else if (uploadExts.charAt(0) == '*') {
- var extGroupName = uploadExts.slice(1);
- if (extGroup[extGroupName]) {
- uploadExts = extGroup[extGroupName].join('|');
- }
- }
-
- // 监听上传事件
- upload.render({
- elem: this,
- url: admin.url(init.uploadUrl),
- exts: uploadExts,
- accept: uploadAccept,//指定允许上传时校验的文件类型
- acceptMime: uploadAcceptMime,//规定打开文件选择框时,筛选出的文件类型
- multiple: uploadNumber !== 'one',//是否多文件上传
- headers: admin.headers(),
- done: function (res) {
- if (res.code === 0) {
- var url = res.data.url;
- var filename = res.data.original_name;
- if (uploadNumber !== 'one') {
- var oldUrl = $(elem).val();
- if (oldUrl !== '') {
- url = oldUrl + uploadSign + url;
- }
- if (elemFilenameField) {
- var oldFilename = $(elemFilenameField).val();
- if (oldFilename !== '') {
- filename = oldFilename + uploadSign + filename;
- }
+ $(v).click(function () {
+ layer.open({
+ title: '选择文件',
+ type: 2,
+ area: [clienWidth, clientHeight],
+ content: admin.url('system.uploadfile/index') + '?select_mode=' + selectCheck,
+ success(layero, index) {
+ window.onTableDataConfirm = function (data) {
+ var currentUrl = $(elem).val();
+ var urlArray = currentUrl.split(uploadSign);
+ if (currentUrl.length == 0 || selectCheck == 'radio') {
+ urlArray = [];
+ }
+ if (uploadFilenameField) {
+ var currentFilename = $(elemFilename).val();
+ var filenameArray = currentFilename.split(uploadSign);
+ if (currentFilename.length == 0 || selectCheck == 'radio') {
+ filenameArray = [];
}
}
- if (elemFilenameField) {
- $(elemFilenameField).val(filename);
+ $.each(data, function (index, val) {
+ if (urlArray.indexOf(val.url) == -1) {
+ urlArray.push(val.url);
+ }
+ if (uploadFilenameField) {
+ if (filenameArray.indexOf(val.original_name) == -1) {
+ filenameArray.push(val.original_name);
+ }
+ }
+
+ });
+ var url = urlArray.join(uploadSign);
+
+ if (uploadFilenameField) {
+ var filename = filenameArray.join(uploadSign);
}
$(elem).val(url);
- $(elem).trigger("input");
- admin.msg.success(res.msg);
- } else {
- admin.msg.error(res.msg);
- }
- return false;
- }
- });
-
- if (uploadDisablePreview == 0) {
- // 监听上传input值变化
- $(elem).bind("input propertychange", function (event) {
- var urlString = $(this).val(),
- urlArray = urlString.split(uploadSign),
- uploadIcon = $(uploadElem).attr('data-upload-icon') || "file";
- var uploadNameKey = uploadName.replace(/\[/g, "-").replace(/\]/g, "-");
- $('#bing-' + uploadNameKey).remove();
- if (urlString.length > 0) {
- var parant = $(this).parent('div');
- var liHtml = '';
- var filenameArray = [];
if (uploadFilenameField) {
- var filenameVal = $(elemFilenameField).val() || '';
- if (filenameVal) {
- filenameArray = filenameVal.split(uploadSign);
- }
+ $(elemFilenameField).val(filename);
}
-
- $.each(urlArray, function (i, v) {
-
- // 获取链接扩展名
- var ext = v.substr(v.lastIndexOf('.') + 1);
- var currentFilename = filenameArray[i] || '';
- currentFilename = currentFilename.replace(/"/g, '"');
-
- if (extGroup.image.indexOf(ext) != -1) {
- // 是图片
- liHtml += '
×\n';
- } else {
- // 不是图片
- // 遍历extGroup数组找到扩展名所在的索引
-
- uploadIcon = admin.getExtGroupName(ext);
-
- liHtml += '
×\n';
-
- }
-
- });
- parant.after('');
-
- var initSortable = function () {
- var el = document.getElementById('bing-' + uploadNameKey);
- if (el) {
- new Sortable(el, {
- animation: 150,
- onEnd: function (evt) {
- var newUrls = [];
- var newFilenames = [];
- $(el).find('.uploads-delete-tip').each(function () {
- newUrls.push($(this).attr('data-upload-url'));
- newFilenames.push($(this).attr('data-upload-filename'));
- });
- $(elem).val(newUrls.join(uploadSign));
- if (uploadFilenameField) {
- $(elemFilenameField).val(newFilenames.join(uploadSign));
- }
- $(elem).trigger("input");
- }
- });
- }
- };
-
- initSortable();
- }
-
- });
-
- // 非空初始化图片显示
- if ($(elem).val() !== '') {
- $(elem).trigger("input");
+ $(elem).trigger("input");
+ layer.close(index);
+ admin.msg.success('选择成功');
+ };
}
- }
-
- });
-
- // 监听上传文件的删除事件
- $('body').on('click', '[data-upload-delete]', function () {
- var uploadName = $(this).attr('data-upload-delete'),
- deleteUrl = $(this).attr('data-upload-url'),
- uploadFilenameField = $(this).attr('data-upload-filename-field'),
- sign = $(this).attr('data-upload-sign');
- var confirm = admin.msg.confirm('确定删除?', function () {
- var elem = "input[name='" + uploadName + "']";
- var elemFilenameField = "[name='" + uploadFilenameField + "']";
- var currentUrl = $(elem).val();
- var currentFilename = $(elemFilenameField).val();
-
- var currentUrlList = currentUrl.split(sign);
- var deleteIndex = currentUrlList.indexOf(deleteUrl);
-
- currentUrlList.splice(deleteIndex, 1);
- $(elem).val(currentUrlList.join(sign));
- $(elem).trigger("input");
-
- if (currentFilename) {
-
- var currentFilenameList = currentFilename.split(sign);
- currentFilenameList.splice(deleteIndex, 1);
-
- $(elemFilenameField).val(currentFilenameList.join(sign));
- }
-
- admin.msg.close(confirm);
- });
- return false;
- });
- }
-
- if (uploadSelectList.length > 0) {
- $.each(uploadSelectList, function (i, v) {
- var uploadName = $(this).attr('data-upload-select'),
- uploadNumber = $(this).attr('data-upload-number') || 'one',
- uploadSign = $(this).attr('data-upload-sign') || '|',
- uploadFilenameField = $(this).attr('data-upload-filename-field') || '';
-
- if (uploadFilenameField) {
- var elemFilenameField = "[name='" + uploadFilenameField + "']";
- var elemFilename = $(elemFilenameField);
- }
-
- var selectCheck = uploadNumber === 'one' ? 'radio' : 'checkbox';
- var elem = "input[name='" + uploadName + "']";
- var width = document.body.clientWidth,
- height = document.body.clientHeight;
-
- if (width >= 800 && height >= 600) {
- clienWidth = '800px';
- clientHeight = '600px';
- } else {
- clienWidth = '100%';
- clientHeight = '100%';
- }
-
- $(v).click(function () {
-
- layer.open({
- title: '选择文件',
- type: 2,
- area: [clienWidth, clientHeight],
- content: admin.url('system.uploadfile/index') + '?select_mode=' + selectCheck,
- success(layero, index) {
- window.onTableDataConfirm = function (data) {
- var currentUrl = $(elem).val();
- var urlArray = currentUrl.split(uploadSign);
- if (currentUrl.length == 0 || selectCheck == 'radio') {
- urlArray = [];
- }
- if (uploadFilenameField) {
- var currentFilename = $(elemFilename).val();
- var filenameArray = currentFilename.split(uploadSign);
- if (currentFilename.length == 0 || selectCheck == 'radio') {
- filenameArray = [];
- }
- }
- $.each(data, function (index, val) {
- if (urlArray.indexOf(val.url) == -1) {
- urlArray.push(val.url);
- }
- if (uploadFilenameField) {
- if (filenameArray.indexOf(val.original_name) == -1) {
- filenameArray.push(val.original_name);
- }
- }
-
- });
- var url = urlArray.join(uploadSign);
-
- if (uploadFilenameField) {
- var filename = filenameArray.join(uploadSign);
- }
- $(elem).val(url);
- if (uploadFilenameField) {
- $(elemFilenameField).val(filename);
- }
- $(elem).trigger("input");
- layer.close(index);
- admin.msg.success('选择成功');
- };
- }
- });
});
});
+ });
- }
- },
- editor: function () {
- var editorList = document.querySelectorAll(".editor");
- if (editorList.length > 0) {
- $.each(editorList, function (i, v) {
- var editorConfig = {
- placeholder: '请输入内容',
- onChange(editor) {
- const html = editor.getHtml();
- $(v).val(html);
+ }
+ },
+ editor: function () {
+ var editorList = document.querySelectorAll(".editor");
+ if (editorList.length > 0) {
+ $.each(editorList, function (i, v) {
+ var editorConfig = {
+ placeholder: '请输入内容',
+ onChange(editor) {
+ const html = editor.getHtml();
+ $(v).val(html);
+ },
+ MENU_CONF: {
+ uploadImage: {
+ server: admin.url('ajax/uploadEditor'),
+ maxFileSize: 10 * 1024 * 1024,
+ fieldName: 'upload',
},
- MENU_CONF: {
- uploadImage: {
- server: admin.url('ajax/uploadEditor'),
- maxFileSize: 10 * 1024 * 1024,
- fieldName: 'upload',
- },
+ }
+ };
+
+ var formName = $(this).attr('name');
+
+ var editorId = 'editor-' + formName.replace(/\[/g, '-').replace(/\]/g, '-');
+ var editorContainer = $('');
+ $(this).after(editorContainer);
+
+ var toolbarId = 'toolbar-' + formName.replace(/\[/g, '-').replace(/\]/g, '-');
+ var toolbarContent = $('');
+ $(this).after(toolbarContent);
+
+ $(this).hide();
+
+ var originalValue = $(this).val();
+ const editor = createEditor({
+ selector: '#' + editorId,
+ html: originalValue,
+ config: editorConfig,
+ mode: 'default',
+ scroll: true
+ });
+ $(v).data('editor', editor);
+
+
+ const toolbarConfig = {
+ excludeKeys: [
+ 'uploadVideo',
+ 'fullScreen',
+ 'todo',
+ ]
+ };
+
+ const toolbar = createToolbar({
+ editor,
+ selector: '#' + toolbarId,
+ config: toolbarConfig,
+ mode: 'default', // or 'simple'
+ });
+
+
+ });
+ }
+ },
+ select: function () {
+
+ var selectList = document.querySelectorAll("[data-select]");
+ $.each(selectList, function (i, v) {
+ var url = $(this).attr('data-select'),
+ selectFields = $(this).attr('data-fields'),
+ value = $(this).attr('data-value'),
+ that = this,
+ html = '';
+
+ var template = $(that).data('template');
+
+ if (typeof template != 'function') {
+ template = function (data, fields) {
+ return data[fields[1]];
+ };
+ }
+
+ var fields = selectFields.replace(/\s/g, "").split(',');
+ if (fields.length < 2) {
+ return admin.msg.error('下拉选择字段有误');
+ }
+ admin.request.get(
+ {
+ url: url,
+ data: {
+ selectFields: selectFields
+ },
+ }, function (res) {
+ var list = res.data;
+
+
+
+ list.forEach(val => {
+ var key = val[fields[0]];
+
+ var valueTitle = template(val, fields);
+
+ if (value !== undefined && key.toString() === value) {
+ html += '';
+ } else {
+ html += '';
}
- };
-
- var formName = $(this).attr('name');
-
- var editorId = 'editor-' + formName.replace(/\[/g, '-').replace(/\]/g, '-');
- var editorContainer = $('');
- $(this).after(editorContainer);
-
- var toolbarId = 'toolbar-' + formName.replace(/\[/g, '-').replace(/\]/g, '-');
- var toolbarContent = $('');
- $(this).after(toolbarContent);
-
- $(this).hide();
-
- var originalValue = $(this).val();
- const editor = createEditor({
- selector: '#' + editorId,
- html: originalValue,
- config: editorConfig,
- mode: 'default',
- scroll: true
});
- $(v).data('editor', editor);
-
-
- const toolbarConfig = {
- excludeKeys: [
- 'uploadVideo',
- 'fullScreen',
- 'todo',
- ]
- };
-
- const toolbar = createToolbar({
- editor,
- selector: '#' + toolbarId,
- config: toolbarConfig,
- mode: 'default', // or 'simple'
- });
-
-
- });
+ $(that).html(html);
+ form.render();
+ }
+ );
+ });
+ },
+ nativeRadio() {
+ $('[value-checked]').each(function (index, elem) {
+ if ($(this).hasClass('checked-rendered')) {
+ return;
}
- },
- select: function () {
-
- var selectList = document.querySelectorAll("[data-select]");
- $.each(selectList, function (i, v) {
- var url = $(this).attr('data-select'),
- selectFields = $(this).attr('data-fields'),
- value = $(this).attr('data-value'),
- that = this,
- html = '';
-
- var template = $(that).data('template');
-
- if (typeof template != 'function') {
- template = function (data, fields) {
- return data[fields[1]];
- };
- }
-
- var fields = selectFields.replace(/\s/g, "").split(',');
- if (fields.length < 2) {
- return admin.msg.error('下拉选择字段有误');
- }
- admin.request.get(
- {
- url: url,
- data: {
- selectFields: selectFields
- },
- }, function (res) {
- var list = res.data;
-
-
-
- list.forEach(val => {
- var key = val[fields[0]];
-
- var valueTitle = template(val, fields);
-
- if (value !== undefined && key.toString() === value) {
- html += '';
- } else {
- html += '';
- }
- });
- $(that).html(html);
- form.render();
- }
- );
- });
- },
- nativeRadio() {
- $('[value-checked]').each(function (index, elem) {
- if ($(this).hasClass('checked-rendered')) {
- return;
- }
- $(this).addClass('checked-rendered');
- if ($(this).attr('value') == $(this).attr('value-checked')) {
- $(this).prop('checked', true);
- }
- });
- },
- nativeSelect() {
- $('[value-selected]').each(function (index, elem) {
- if ($(this).hasClass('selected-rendered')) {
- return;
- }
- $(this).addClass('selected-rendered');
- if ($(this).attr('value') == $(this).attr('value-selected')) {
- $(this).prop('selected', true);
- }
- });
- },
- date: function () {
- var dateList = document.querySelectorAll("[data-date]");
- if (dateList.length > 0) {
- $.each(dateList, function (i, v) {
- var format = $(this).attr('data-date'),
- type = $(this).attr('data-date-type'),
- range = $(this).attr('data-date-range');
- if (type === undefined || type === '' || type === null) {
- type = 'datetime';
- }
- var options = {
- elem: this,
- type: type,
- };
- if (format !== undefined && format !== '' && format !== null) {
- options['format'] = format;
- }
- if (range !== undefined) {
- if (range === null || range === '') {
- range = '-';
- }
- options['range'] = range;
- }
- laydate.render(options);
- });
- }
- },
- tableData() {
- var tableList = document.querySelectorAll('[data-toggle="table-data"]');
- $.each(tableList, function (i, v) {
- var data = $(v).data();
- tableData.render(v, data, admin);
- });
-
- },
- mapLocation() {
- var mapList = document.querySelectorAll('[data-toggle="map-location"]');
-
- $.each(mapList, function (i, v) {
- if ($(v).hasClass('map-rendered')) {
- return;
- }
- $(v).addClass('map-rendered');
- var data = $(v).data();
- mapLocation.render(v, data, admin);
- });
-
- },
- tagInput() {
- var list = document.querySelectorAll('[data-toggle="tag-input"]');
- $.each(list, function (i, v) {
- var data = $(v).data();
- tagInput.render(v, data, admin);
- });
-
- },
- propertyInput() {
- var list = document.querySelectorAll('[data-toggle="property-input"]');
- $.each(list, function (i, v) {
- var data = $(v).data();
-
- data.value = $(v).text();
-
- propertyInput.render(v, data, admin);
- });
-
- },
- copyText(elem) {
- if (elem == undefined) {
- elem = 'body';
- }
- var list = $(elem).find('[data-toggle="copy-text"]');
-
- $.each(list, function (i, v) {
-
- if ($(v).hasClass('copy-rendered')) {
- return;
- }
-
- $(v).addClass('copy-rendered');
- var clipboard = new ClipboardJS(v);
-
- clipboard.on('success', function (e) {
- admin.msg.success('复制成功');
- });
-
- clipboard.on('error', function (e) {
- admin.msg.error('复制失败');
-
- });
- });
- },
- pasteText(elem) {
- if (elem == undefined) {
- elem = 'body';
- }
- var list = $(elem).find('[data-toggle="paste-text"]');
-
- $.each(list, function (i, v) {
-
- if ($(v).hasClass('paste-rendered')) {
- return;
- }
- $(v).addClass('paste-rendered');
-
- var targetElemName = $(v).data('paste-target');
- $(v).on('click', function () {
- if (!navigator.clipboard) {
- admin.msg.error('您的当前不支持粘贴操作');
- return;
- }
- navigator.clipboard.readText()
- .then(text => {
- $(targetElemName).val(text);
- layer.msg('粘贴成功');
- })
- .catch(err => {
- console.error('Failed to read clipboard contents: ', err);
- layer.msg('粘贴失败,请手动粘贴');
- });
- });
- });
- }
- },
- getQueryVariable(variable, defaultValue) {
- if (typeof defaultValue == 'undefined') {
- defaultValue = undefined;
- }
-
- var query = window.location.search.substring(1);
- query = query.replace(/\+/g, ' ');
- var vars = query.split("&");
- for (var i = 0; i < vars.length; i++) {
- var pair = vars[i].split("=");
- if (pair[0] == variable) {
- return decodeURIComponent(pair[1]);
- }
- }
- return defaultValue;
- },
- dataBrage: null,
- getDataBrage(keys, defaultValue) {
- if (this.dataBrage == null) {
- this.dataBrage = JSON.parse($('#data-brage').text());
- }
-
- if (typeof defaultValue == 'undefined') {
- defaultValue = undefined;
- }
-
- return admin.dataGet(this.dataBrage, keys, defaultValue);
- },
- dataGet(data, keys, defaultValue) {
- return (
- (!Array.isArray(keys)
- ? keys.replace(/\[/g, '.').replace(/\]/g, '').split('.')
- : keys
- ).reduce((o, k) => (o || {})[k], data) || defaultValue
- );
- },
- getExtGroupName(ext) {
- var groupName = 'file';
- for (const extGroupName in extGroup) {
- if (Object.hasOwnProperty.call(extGroup, extGroupName)) {
- const extGroupList = extGroup[extGroupName];
- if (extGroupList.indexOf(ext) != -1) {
- groupName = extGroupName;
- break;
- }
- }
- }
-
- return groupName;
- },
- //js版empty,判断变量是否为空
- empty: function (r) {
- var n, t, e, f = [void 0, null, !1, 0, "", "0"];
- for (t = 0, e = f.length; t < e; t++) if (r === f[t]) return !0;
- if ("object" == typeof r) {
- for (n in r) if (r.hasOwnProperty(n)) return !1;
- return !0;
- }
- return !1;
- },
-
- bytes(size) {
- if (size > 0) {
- const kb = 1024;
- const unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- const i = Math.floor(Math.log(size) / Math.log(kb));
- const num = (size / Math.pow(kb, i)).toPrecision(3);
- const u = unit[i];
- return num + u;
- }
- return '0B';
- },
- triggerEventReplaceJs(name, defaultCallback, replaceCallback) {
- var code = $('#event-replace-js-' + name).html();
-
- if (admin.empty(code)) {
- defaultCallback();
- } else {
- replaceCallback(code);
- }
- },
- randdomString(len) {
- len = len || 32;
- var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
- var maxPos = $chars.length;
- var pwd = '';
- for (var i = 0; i < len; i++) {
- pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
- }
- return pwd;
- },
- getPageSetting(key, defaultValue, global = false) {
- if (!global) {
- key = window.CONFIG.PAGE_KEY_NAME + '_' + key;
- }
- return tools.getLocal(key, defaultValue);
- },
- setPageSetting(key, value, global) {
- if (!global) {
- key = window.CONFIG.PAGE_KEY_NAME + '_' + key;
- }
- return tools.setLocal(key, value);
- },
- /**
- * 如果不存在则写入,返回有效的值
- * 如果不存在则返回新的值,否则返回之前设置的值
- *
- * @param {string} key
- * @param {mixed} value
- * @param {boolean} global
- * @returns
- */
- trySetPageSetting(key, value, global) {
- var oldValue = admin.getPageSetting(key, undefined, global);
- if (!oldValue) {
- admin.setPageSetting(key, value, global);
- return value;
- }
-
- return oldValue;
- },
- isCurrentIndex() {
- if (window.pageType && window.pageType == 'index') {
- return true;
- }
- return false;
- },
- isParentIndex(){
- try {
- if (window.parent && window.parent.pageType && window.parent.pageType == 'index') {
- return true;
- }
- } catch (e) {
- return false;
- }
- return false;
- },
- findIndexPage(findCallback, missCallback) {
- if (!findCallback) {
- findCallback = function (w) { return w; };
- }
- if (!missCallback) {
- missCallback = function (w) { return w; };
- }
- if (this.isCurrentIndex()) {
- return findCallback(window);
- }
-
- var parent = window.parent;
- if (parent && parent != window) {
- return parent.ua.findIndexPage(findCallback, missCallback);
- }
-
- return missCallback(null);
- },
- getCurrentPageId() {
- // pageId就是路径加参数
- var path = location.pathname;
- var params = location.search;
- return path + params;
- },
- findPageId(tabId) {
- var iframeWindow;
- this.findIndexPage(function (window) {
- // 查找对应的tab内容区域
- var tabContent = window.layui.$('.layui-tab-content .layui-tab-item[lay-id="' + tabId + '"]');
- if (tabContent.length > 0) {
- var iframe = tabContent.find('iframe')[0];
- if (iframe) {
- iframeWindow = iframe.contentWindow;
- }
+ $(this).addClass('checked-rendered');
+ if ($(this).attr('value') == $(this).attr('value-checked')) {
+ $(this).prop('checked', true);
}
});
- return iframeWindow;
},
- getMenuInfoByTabId(tabId) {
- var menuValue = null;
- this.findIndexPage(function (w) {
- var menu = w.miniTab.searchMenu(tabId);
- if (menu) {
- menuValue = menu;
+ nativeSelect() {
+ $('[value-selected]').each(function (index, elem) {
+ if ($(this).hasClass('selected-rendered')) {
+ return;
+ }
+ $(this).addClass('selected-rendered');
+ if ($(this).attr('value') == $(this).attr('value-selected')) {
+ $(this).prop('selected', true);
}
});
- return menuValue;
},
- getMenuTitleByTabId(tabId, defaultValue) {
- var menuTitle = defaultValue;
- var menu = this.getMenuInfoByTabId(tabId);
-
- if (menu) {
- menuTitle = menu.title;
+ date: function () {
+ var dateList = document.querySelectorAll("[data-date]");
+ if (dateList.length > 0) {
+ $.each(dateList, function (i, v) {
+ var format = $(this).attr('data-date'),
+ type = $(this).attr('data-date-type'),
+ range = $(this).attr('data-date-range');
+ if (type === undefined || type === '' || type === null) {
+ type = 'datetime';
+ }
+ var options = {
+ elem: this,
+ type: type,
+ };
+ if (format !== undefined && format !== '' && format !== null) {
+ options['format'] = format;
+ }
+ if (range !== undefined) {
+ if (range === null || range === '') {
+ range = '-';
+ }
+ options['range'] = range;
+ }
+ laydate.render(options);
+ });
}
- return menuTitle;
+ },
+ tableData() {
+ var tableList = document.querySelectorAll('[data-toggle="table-data"]');
+ $.each(tableList, function (i, v) {
+ var data = $(v).data();
+ tableData.render(v, data, admin);
+ });
+
+ },
+ mapLocation() {
+ var mapList = document.querySelectorAll('[data-toggle="map-location"]');
+
+ $.each(mapList, function (i, v) {
+ if ($(v).hasClass('map-rendered')) {
+ return;
+ }
+ $(v).addClass('map-rendered');
+ var data = $(v).data();
+ mapLocation.render(v, data, admin);
+ });
+
+ },
+ tagInput() {
+ var list = document.querySelectorAll('[data-toggle="tag-input"]');
+ $.each(list, function (i, v) {
+ var data = $(v).data();
+ tagInput.render(v, data, admin);
+ });
+
+ },
+ propertyInput() {
+ var list = document.querySelectorAll('[data-toggle="property-input"]');
+ $.each(list, function (i, v) {
+ var data = $(v).data();
+
+ data.value = $(v).text();
+
+ propertyInput.render(v, data, admin);
+ });
+
+ },
+ copyText(elem) {
+ if (elem == undefined) {
+ elem = 'body';
+ }
+ var list = $(elem).find('[data-toggle="copy-text"]');
+
+ $.each(list, function (i, v) {
+
+ if ($(v).hasClass('copy-rendered')) {
+ return;
+ }
+
+ $(v).addClass('copy-rendered');
+ var clipboard = new ClipboardJS(v);
+
+ clipboard.on('success', function (e) {
+ admin.msg.success('复制成功');
+ });
+
+ clipboard.on('error', function (e) {
+ admin.msg.error('复制失败');
+
+ });
+ });
+ },
+ pasteText(elem) {
+ if (elem == undefined) {
+ elem = 'body';
+ }
+ var list = $(elem).find('[data-toggle="paste-text"]');
+
+ $.each(list, function (i, v) {
+
+ if ($(v).hasClass('paste-rendered')) {
+ return;
+ }
+ $(v).addClass('paste-rendered');
+
+ var targetElemName = $(v).data('paste-target');
+ $(v).on('click', function () {
+ if (!navigator.clipboard) {
+ admin.msg.error('您的当前不支持粘贴操作');
+ return;
+ }
+ navigator.clipboard.readText()
+ .then(text => {
+ $(targetElemName).val(text);
+ layer.msg('粘贴成功');
+ })
+ .catch(err => {
+ console.error('Failed to read clipboard contents: ', err);
+ layer.msg('粘贴失败,请手动粘贴');
+ });
+ });
+ });
}
};
+ window.ulAdmin = window.ua = admin;
+})();
+
+
+(function () {
+
+ var ctx = window.__uaCtx || {};
+ var admin = window.ua || {};
+ var extGroup = ctx.extGroup;
+
+ admin.getQueryVariable = function (variable, defaultValue) {
+ if (typeof defaultValue == 'undefined') {
+ defaultValue = undefined;
+ }
+
+ var query = window.location.search.substring(1);
+ query = query.replace(/\+/g, ' ');
+ var vars = query.split("&");
+ for (var i = 0; i < vars.length; i++) {
+ var pair = vars[i].split("=");
+ if (pair[0] == variable) {
+ return decodeURIComponent(pair[1]);
+ }
+ }
+ return defaultValue;
+ };
+ admin.dataBrage = null;
+ admin.getDataBrage = function (keys, defaultValue) {
+ if (this.dataBrage == null) {
+ this.dataBrage = JSON.parse($('#data-brage').text());
+ }
+
+ if (typeof defaultValue == 'undefined') {
+ defaultValue = undefined;
+ }
+
+ return admin.dataGet(this.dataBrage, keys, defaultValue);
+ };
+ admin.dataGet = function (data, keys, defaultValue) {
+ return (
+ (!Array.isArray(keys)
+ ? keys.replace(/\[/g, '.').replace(/\]/g, '').split('.')
+ : keys
+ ).reduce((o, k) => (o || {})[k], data) || defaultValue
+ );
+ };
+ admin.getExtGroupName = function (ext) {
+ var groupName = 'file';
+ for (const extGroupName in extGroup) {
+ if (Object.hasOwnProperty.call(extGroup, extGroupName)) {
+ const extGroupList = extGroup[extGroupName];
+ if (extGroupList.indexOf(ext) != -1) {
+ groupName = extGroupName;
+ break;
+ }
+ }
+ }
+
+ return groupName;
+ };
+ //js版empty,判断变量是否为空
+ admin.empty = function (r) {
+ var n, t, e, f = [void 0, null, !1, 0, "", "0"];
+ for (t = 0, e = f.length; t < e; t++) if (r === f[t]) return !0;
+ if ("object" == typeof r) {
+ for (n in r) if (r.hasOwnProperty(n)) return !1;
+ return !0;
+ }
+ return !1;
+ };
+
+ admin.bytes = function (size) {
+ if (size > 0) {
+ const kb = 1024;
+ const unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
+ const i = Math.floor(Math.log(size) / Math.log(kb));
+ const num = (size / Math.pow(kb, i)).toPrecision(3);
+ const u = unit[i];
+ return num + u;
+ }
+ return '0B';
+ };
+ admin.triggerEventReplaceJs = function (name, defaultCallback, replaceCallback) {
+ var code = $('#event-replace-js-' + name).html();
+
+ if (admin.empty(code)) {
+ defaultCallback();
+ } else {
+ replaceCallback(code);
+ }
+ };
+ admin.randdomString = function (len) {
+ len = len || 32;
+ var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
+ var maxPos = $chars.length;
+ var pwd = '';
+ for (var i = 0; i < len; i++) {
+ pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
+ }
+ return pwd;
+ };
+ admin.getPageSetting = function (key, defaultValue, global = false) {
+ if (!global) {
+ key = window.CONFIG.PAGE_KEY_NAME + '_' + key;
+ }
+ return tools.getLocal(key, defaultValue);
+ };
+ admin.setPageSetting = function (key, value, global) {
+ if (!global) {
+ key = window.CONFIG.PAGE_KEY_NAME + '_' + key;
+ }
+ return tools.setLocal(key, value);
+ };
+ /**
+ * 如果不存在则写入,返回有效的值
+ * 如果不存在则返回新的值,否则返回之前设置的值
+ *
+ * @param {string} key
+ * @param {mixed} value
+ * @param {boolean} global
+ * @returns
+ */
+ admin.trySetPageSetting = function (key, value, global) {
+ var oldValue = admin.getPageSetting(key, undefined, global);
+ if (!oldValue) {
+ admin.setPageSetting(key, value, global);
+ return value;
+ }
+
+ return oldValue;
+ };
+ admin.isCurrentIndex = function () {
+ if (window.pageType && window.pageType == 'index') {
+ return true;
+ }
+ return false;
+ };
+ admin.isParentIndex = function () {
+ try {
+ if (window.parent && window.parent.pageType && window.parent.pageType == 'index') {
+ return true;
+ }
+ } catch (e) {
+ return false;
+ }
+ return false;
+ };
+ admin.findIndexPage = function (findCallback, missCallback) {
+ if (!findCallback) {
+ findCallback = function (w) { return w; };
+ }
+ if (!missCallback) {
+ missCallback = function (w) { return w; };
+ }
+ if (this.isCurrentIndex()) {
+ return findCallback(window);
+ }
+
+ var parent = window.parent;
+ if (parent && parent != window) {
+ return parent.ua.findIndexPage(findCallback, missCallback);
+ }
+
+ return missCallback(null);
+ };
+ admin.getCurrentPageId = function () {
+ // pageId就是路径加参数
+ var path = location.pathname;
+ var params = location.search;
+ return path + params;
+ };
+ admin.findPageId = function (tabId) {
+ var iframeWindow;
+ this.findIndexPage(function (window) {
+ // 查找对应的tab内容区域
+ var tabContent = window.layui.$('.layui-tab-content .layui-tab-item[lay-id="' + tabId + '"]');
+ if (tabContent.length > 0) {
+ var iframe = tabContent.find('iframe')[0];
+ if (iframe) {
+ iframeWindow = iframe.contentWindow;
+ }
+ }
+ });
+ return iframeWindow;
+ };
+ admin.getMenuInfoByTabId = function (tabId) {
+ var menuValue = null;
+ this.findIndexPage(function (w) {
+ var menu = w.miniTab.searchMenu(tabId);
+ if (menu) {
+ menuValue = menu;
+ }
+ });
+ return menuValue;
+ };
+ admin.getMenuTitleByTabId = function (tabId, defaultValue) {
+ var menuTitle = defaultValue;
+ var menu = this.getMenuInfoByTabId(tabId);
+
+ if (menu) {
+ menuTitle = menu.title;
+ }
+ return menuTitle;
+ };
window.ulAdmin = window.ua = admin;
-})();
\ No newline at end of file
+})();