SiteAlbumController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <?php
  2. namespace App\Admin\Controllers;
  3. use App\Admin\Repositories\SiteAlbum;
  4. use App\Admin\Repositories\SiteAlbumFolder;
  5. use App\Admin\Repositories\SiteAlbumLog;
  6. use App\Libraries\CommonHelper;
  7. use App\Models\SiteAlbumFolder as SiteAlbumFolderModel;
  8. use Dcat\Admin\Form;
  9. use Dcat\Admin\Grid;
  10. use Dcat\Admin\Show;
  11. use Dcat\Admin\Http\Controllers\AdminController;
  12. use Dcat\Admin\Layout\Content;
  13. use Dcat\Admin\Admin;
  14. use App\Admin\Repositories\NullRepository;
  15. use Dcat\Admin\Traits\HasUploadedFile;
  16. use Illuminate\Support\Facades\Cache;
  17. use function Symfony\Component\Translation\t;
  18. class SiteAlbumController extends AdminController
  19. {
  20. use HasUploadedFile;
  21. public function title()
  22. {
  23. return admin_trans( 'admin.album');
  24. }
  25. /**
  26. * page index
  27. */
  28. public function index(Content $content)
  29. {
  30. //记录folder_id
  31. $folderId = isset($_GET['folder_id']) ? intval($_GET['folder_id']) : 0;
  32. //保存临时变量
  33. setTempValue('folderId', $folderId);
  34. $html = $content
  35. ->header(admin_trans( 'admin.album'))
  36. ->body($this->indexForm());
  37. $html = $html->render();
  38. //删除第一个formID对应的JS代码
  39. preg_match('/<form[^>]*id="([^"]*)"[^>]*>/', $html, $matches);
  40. if (isset($matches[1])) {
  41. $formId = $matches[1]; // 获取 id 的值
  42. // echo "找到的 form id: " . $formId . "\n";
  43. // 2. 根据 id 值,删除对应的 JavaScript 代码
  44. $pattern = '/\$\(\'#' . preg_quote($formId, '/') . '\'\)\.form\(\{.*?\}\);/s';
  45. $html = preg_replace($pattern, '', $html);
  46. }
  47. //把第一个form标签替换成div标签
  48. $html = preg_replace('/<form([^>]*)>(.*?)<\/form>/s', '<div$1>$2</div>', $html, 1);
  49. return $html;
  50. }
  51. protected function indexForm()
  52. {
  53. return Form::make(new NullRepository(), function (Form $form) {
  54. $form->action('/site-album');
  55. $folderModel = new SiteAlbumFolderModel();
  56. $folderTree = $folderModel->allNodes();
  57. $form->block(2, function (Form\BlockForm $form) use ($folderTree) {
  58. $type = [
  59. 'default' => [
  60. 'icon' => true,
  61. ],
  62. ];
  63. $plugins = ['types'];
  64. $form->tree()
  65. ->setTitleColumn('title')
  66. ->nodes($folderTree)
  67. ->type($type)
  68. ->plugins($plugins)
  69. ->width(12,0);
  70. });
  71. $form->block(10, function (Form\BlockForm $form) {
  72. $form->html($this->grid())->width(12);
  73. });
  74. //以下JS代码用于点击文件夹时,自动跳转到相应页面
  75. Admin::script(
  76. <<<JS
  77. // 使用定时器检测容器是否存在
  78. const interval = setInterval(() => {
  79. const containerUl = document.querySelector('.jstree-container-ul');
  80. if (containerUl) {
  81. clearInterval(interval); // 找到容器后停止检测
  82. // 以下是原有逻辑(已优化)
  83. const folderId = $('select[name="folder_id"]').data('value'); // 提取 folderId 到外层,避免重复查询[1](@ref)
  84. const anchors = document.querySelectorAll('a.jstree-anchor');
  85. anchors.forEach(anchor => {
  86. const id = anchor.id.split('_')[0];
  87. const href = `/prime-control/site-album?folder_id=`+id;
  88. // 绑定点击事件(阻止默认行为)
  89. anchor.addEventListener('click', event => {
  90. event.preventDefault();
  91. window.location.href = href;
  92. });
  93. // 高亮当前节点
  94. if (folderId == id) {
  95. anchor.classList.add('jstree-clicked');
  96. }
  97. });
  98. }
  99. }, 100); // 每100ms检测一次
  100. const firstCheckbox = document.querySelector('.vs-checkbox-primary');
  101. // 如果找到元素,则隐藏它
  102. if (firstCheckbox) {
  103. firstCheckbox.style.display = 'none';
  104. }
  105. //清空_previous_
  106. const input = document.querySelector('input[name="_previous_"]');
  107. if (input) {
  108. // 清空其值
  109. input.value = '';
  110. }
  111. JS
  112. );
  113. });
  114. }
  115. protected function grid()
  116. {
  117. return Grid::make(new SiteAlbum(), function (Grid $grid) {
  118. //默认分页条数
  119. $grid->paginate(config('admin.per_page'));
  120. $grid->column('id')->sortable();
  121. $grid->column('cover')->display(function ($images) {
  122. $images = json_decode($images);
  123. // 限制最多显示2个缩略图
  124. $dataImages = array_slice($images, 0, 1);
  125. return CommonHelper::displayImage($dataImages,80);
  126. });
  127. $grid->column('title',admin_trans_label('product_name'));
  128. //$grid->column('title_en');
  129. $grid->column('model');
  130. $grid->column('folder_id',admin_trans_label('folder'))
  131. ->display(function ($folder_id) {
  132. $folderModel = new SiteAlbumFolderModel();
  133. $folderName = $folderModel->find($folder_id)->title;
  134. return $folderName;
  135. });
  136. $grid->column('order');
  137. $grid->column('enabled')->using(admin_trans_array(config('dictionary.enabled'))) ->label([
  138. 0 => 'danger',
  139. 1 => 'success',
  140. ]);
  141. $grid->column('status')->display(function ($status) {
  142. $updated_at = $this->updated_at->format('Y-m-d H:i:s');
  143. //三个月前显示待更新
  144. if (time() - strtotime($updated_at) > 90 * 24 * 3600) {
  145. return '<span class="label label-warning" style="background:#dda451">待更新</span>';
  146. } else {
  147. return '<span class="label label-success" style="background:#21b978">正常</span>';
  148. }
  149. });
  150. $grid->column('missing_content')->display(function ($missing_content) {
  151. $missing_content = [];
  152. if ($this->cover == '[]') {$missing_content[] = '主图';}
  153. if ($this->text_detail == '') {$missing_content[] = '文字介绍';}
  154. if ($this->en_detail == '[]') {$missing_content[] = '英文详情页';}
  155. if ($this->cn_detail == '[]') {$missing_content[] = '中文详情页';}
  156. if ($this->video == '[]') {$missing_content[] = '视频';}
  157. if ($this->poster == '[]') {$missing_content[] = '海报';}
  158. if ($this->cert == '[]') {$missing_content[] = '证书';}
  159. if ($this->pdf == '[]') {$missing_content[] = 'PDF';}
  160. return implode(' / ', $missing_content);
  161. });
  162. // 筛选
  163. $grid->filter(function (Grid\Filter $filter) {
  164. $selectOptions = SiteAlbumFolderModel::selectOptions();
  165. unset($selectOptions[0]);
  166. $filter->panel();
  167. $filter->expand();
  168. $filter->like('model')->width(2);
  169. $filter->equal('folder_id',admin_trans_label('folder'))->select($selectOptions)->width(3);
  170. $filter->where('status', function ($query) {
  171. $status = $this->input;
  172. // 自定义查询逻辑
  173. if ($status == 1) {
  174. // 三个月内的
  175. $query->where('updated_at', '>=', date('Y-m-d H:i:s', strtotime('-3 month')));
  176. } else {
  177. // 三个月前的
  178. $query->where('updated_at', '<', date('Y-m-d H:i:s', strtotime('-3 month')));
  179. }
  180. })->select(admin_trans_array(config('dictionary.album_status')))->width(3);
  181. });
  182. $grid->disableViewButton();
  183. $grid->disablePerPages();
  184. $grid->disableRefreshButton();
  185. $grid->model()->orderBy('order', 'desc')->orderBy('id', 'desc');
  186. //弹窗大小
  187. $grid->setDialogFormDimensions('830px','670px');
  188. });
  189. }
  190. protected function form()
  191. {
  192. $thisObj = $this;
  193. return Form::make(new SiteAlbum(), function (Form $form) use ($thisObj) {
  194. if ($form->isEditing()) {
  195. $form->title("编辑 | " . $form->model()->title);
  196. }
  197. $form->width(9, 1);
  198. $form->disableViewButton();
  199. $form->disableViewCheck();
  200. $form->saving(function (Form $form) use ($thisObj) {
  201. //处理video
  202. $videos = $form->input('video');
  203. if ($videos) {
  204. foreach ($videos as $key => $value) {
  205. if (empty($value['cover']) && $value['_remove_'] != 1) {
  206. //自动生成封面
  207. $result = $thisObj->autoGenerateCover($value['video_src']);
  208. if ($result['status']) {
  209. $videos[$key]['cover'] = $result['path'];
  210. } else {
  211. return $form->response()->error($result['msg']);
  212. }
  213. }
  214. }
  215. } else {
  216. $videos = [];
  217. }
  218. $form->input('video', $videos);
  219. //处理pdf
  220. $pdfs = $form->input('pdf');
  221. $pdfs = empty($pdfs) ? [] : $pdfs;
  222. $form->input('pdf', $pdfs);
  223. //记录日志
  224. if (!$form->isCreating()) {
  225. $id = $form->getKey();
  226. $cacheKey = 'album_log_'.$id;
  227. Cache::add($cacheKey, json_encode($form->model()->toArray()), 3600);
  228. }
  229. });
  230. $form->saved(function (Form $form) {
  231. if (empty($form->input('model')) == false) {
  232. $id = $form->getKey();
  233. $action = $form->isCreating() ? 'add' : 'edit';
  234. if ($action == 'add') {
  235. $oldData = "[]";
  236. } else {
  237. $oldData = Cache::get('album_log_'. $id);
  238. Cache::forget('album_log_'. $id);
  239. }
  240. SiteAlbumLog::log($action, $id,$form->input('model'),$oldData);
  241. }
  242. });
  243. $form->tab(admin_trans_label('basic_info'), function (Form $form) {
  244. $selectOptions = SiteAlbumFolder::selectOptions();
  245. unset($selectOptions[0]);
  246. $folderId = getTempValue('folderId');
  247. if ($folderId == 0) {
  248. $folderId = array_key_first($selectOptions);
  249. }
  250. $form->select('folder_id')->options($selectOptions)->default($folderId)->required();
  251. $form->text('title',admin_trans_label('product_name'))->required();
  252. $form->text('title_en',admin_trans_label('product_name_en'))->required();
  253. $form->text('model')->required();
  254. $form->table('parameters',admin_trans_label('attribute_name'), function (Form\NestedForm $table) {
  255. $table->text('key')->required();
  256. $table->text('value')->required();
  257. })->setView('admin.form_custom.hasmanytable')
  258. ->saving(function ($input) {
  259. return json_encode($input);
  260. });
  261. $form->number('order')
  262. ->default(0)
  263. ->rules('numeric');
  264. $form->switch('enabled')->default(1);
  265. })->tab(admin_trans_label('cover'), function (Form $form) {
  266. $form->multipleImage('cover')
  267. ->retainable()//禁止删OSS图
  268. ->sortable() // 可拖动排序
  269. ->removable() // 可移除图片
  270. ->autoUpload() // 自动上传
  271. ->uniqueName()
  272. ->limit(config('admin.upload.oss_image.limit'))
  273. ->accept(config('admin.upload.oss_image.accept'))
  274. ->maxSize(config('admin.upload.oss_image.max_size'))
  275. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  276. ->saving(function ($images) use ($form) {
  277. return json_encode($images);
  278. });
  279. })->tab(admin_trans_label('text_detail'), function (Form $form) {
  280. $form->editor('text_detail',admin_trans_label('text_detail'));
  281. })->tab(admin_trans_label('en_detail'), function (Form $form) {
  282. $form->multipleImage('en_detail')
  283. ->retainable()//禁止删OSS图
  284. ->sortable() // 可拖动排序
  285. ->removable() // 可移除图片
  286. ->autoUpload() // 自动上传
  287. ->uniqueName()
  288. ->limit(config('admin.upload.oss_image.limit'))
  289. ->accept(config('admin.upload.oss_image.accept'))
  290. ->maxSize(config('admin.upload.oss_image.max_size'))
  291. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  292. ->saving(function ($images) use ($form) {
  293. return json_encode($images);
  294. });
  295. })->tab(admin_trans_label('cn_detail'), function (Form $form) {
  296. $form->multipleImage('cn_detail')
  297. ->retainable()//禁止删OSS图
  298. ->sortable() // 可拖动排序
  299. ->removable() // 可移除图片
  300. ->autoUpload() // 自动上传
  301. ->uniqueName()
  302. ->limit(config('admin.upload.oss_image.limit'))
  303. ->accept(config('admin.upload.oss_image.accept'))
  304. ->maxSize(config('admin.upload.oss_image.max_size'))
  305. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  306. ->saving(function ($images) use ($form) {
  307. return json_encode($images);
  308. });
  309. })->tab(admin_trans_label('video'), function (Form $form) {
  310. $count = 0;
  311. $form->hasMany('video', function (Form\NestedForm $form) use (&$count) {
  312. $videos = $form->model()->video;
  313. $imgArray = "";
  314. if ($videos) {
  315. $videos = json_decode($videos,true);
  316. foreach ($videos as $key => $value) {
  317. if ($value['cover'] && $key == $count-1) {
  318. $imgArray = [$value['cover']];
  319. }
  320. }
  321. }
  322. $imgHtml = CommonHelper::displayImage($imgArray);
  323. $form->html($imgHtml,admin_trans_label('image_preview'));
  324. $count++;
  325. $form->text('video_title',admin_trans_label('video_title'))->required();
  326. $form->text('video_en_title',admin_trans_label('video_en_title'))->required();
  327. $form->hidden('cover',admin_trans_label('video_cover'))->placeholder('自动生成')->readOnly();
  328. $form->tradFile('video_src')
  329. ->retainable()//禁止删OSS图
  330. ->removable() // 可移除图片
  331. ->autoUpload() // 自动上传
  332. ->uniqueName()//
  333. ->downloadable()
  334. ->accept(config('admin.upload.oss_video.accept'))
  335. ->maxSize(config('admin.upload.oss_video.max_size'))
  336. ->dir(config("admin.upload.directory.video").'/uploads/'.date("Ym"))
  337. ->chunkSize(1024)
  338. ->required();
  339. })->useTable()
  340. ->customFormat(function ($data) {return json_decode($data,true);})
  341. ->setView('admin.form_custom.hasmanytable')
  342. ->saving(function ($input) {
  343. $data = [];
  344. foreach ($input as $value) {
  345. if ($value['_remove_'] != 1){
  346. $data[] = ['cover'=>$value['cover'],'video_title'=>$value['video_title'],'video_en_title' => $value['video_en_title'],'video_src'=>$value['video_src']];
  347. }
  348. }
  349. return json_encode($data);
  350. });
  351. })->tab(admin_trans_label('poster'), function (Form $form) {
  352. $form->multipleImage('poster')
  353. ->retainable()//禁止删OSS图
  354. ->sortable() // 可拖动排序
  355. ->removable() // 可移除图片
  356. ->autoUpload() // 自动上传
  357. ->uniqueName()
  358. ->limit(config('admin.upload.oss_image.limit'))
  359. ->accept(config('admin.upload.oss_image.accept'))
  360. ->maxSize(config('admin.upload.oss_image.max_size'))
  361. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  362. ->saving(function ($images) use ($form) {
  363. return json_encode($images);
  364. });
  365. })->tab(admin_trans_label('cert'), function (Form $form) {
  366. $form->multipleImage('cert')
  367. ->retainable()//禁止删OSS图
  368. ->sortable() // 可拖动排序
  369. ->removable() // 可移除图片
  370. ->autoUpload() // 自动上传
  371. ->uniqueName()
  372. ->limit(config('admin.upload.oss_image.limit'))
  373. ->accept(config('admin.upload.oss_image.accept'))
  374. ->maxSize(config('admin.upload.oss_image.max_size'))
  375. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  376. ->saving(function ($images) use ($form) {
  377. return json_encode($images);
  378. });
  379. })->tab(admin_trans_label('pdf'), function (Form $form) {
  380. $form->hasMany('pdf', function ($form) {
  381. $form->text('pdf_title')->required();
  382. $form->text('pdf_title_en')->required();
  383. $form->tradFile('pdf_src')
  384. ->retainable()//禁止删OSS图
  385. ->removable() // 可移除图片
  386. ->autoUpload() // 自动上传
  387. ->uniqueName()
  388. ->downloadable()
  389. ->accept(config('admin.upload.oss_pdf.accept'))
  390. ->maxSize(config('admin.upload.oss_pdf.max_size'))
  391. ->dir(config("admin.upload.directory.pdf").'/uploads/'.date("Ym"))
  392. ->chunkSize(1024)
  393. ->required();
  394. })->useTable()
  395. ->customFormat(function ($data) {
  396. return json_decode($data,true);
  397. })
  398. ->setView('admin.form_custom.hasmanytable')
  399. ->saving(function ($input) {
  400. $data = [];
  401. foreach ($input as $value) {
  402. if ($value['_remove_'] != 1){
  403. $data[] = ['pdf_title'=>$value['pdf_title'],'pdf_title_en' => $value['pdf_title_en'],'pdf_src'=>$value['pdf_src']];
  404. }
  405. }
  406. return json_encode($data);
  407. });
  408. });
  409. //以下JS代码用于点击列表时,带上folder_id参数,还有隐藏的tab切换功能
  410. $thisObj->formAddJS();
  411. });
  412. }
  413. /*
  414. * 自动生成视频封面,并上传到OSS
  415. */
  416. private function autoGenerateCover($videoSrc)
  417. {
  418. try {
  419. $cover = $videoSrc.'?x-oss-process=video/snapshot,t_2000,f_jpg,h_500,m_fast';
  420. $cover = CommonHelper::ossUrl($cover);
  421. $path = $this->upload($cover,'.jpg');
  422. } catch (\Exception $e) {
  423. $path = ['status'=>true,'path'=>'/static/common/images/no-image.jpg'];
  424. }
  425. return $path;
  426. }
  427. private function upload($file,$imgType='.jpg')
  428. {
  429. $disk = $this->disk('oss');
  430. $newName = uniqueCode("video_cover_").$imgType;
  431. $dir = config("admin.upload.directory.image").'/uploads/'.date("Ym").'/'.$newName;
  432. $contents = file_get_contents($file);
  433. if (!$contents) {
  434. return ['status'=>false,'msg'=>'图片上传失败,请检查PHP配置'];
  435. }
  436. $disk->put($dir, $contents);
  437. return ['status'=>true,'path'=>$dir];
  438. }
  439. private function formAddJS() {
  440. $folderTabs = SiteAlbumFolder::getAllFolderTabs();
  441. $album_tabs = config('dictionary.album_tabs');
  442. foreach ($folderTabs as $key => $value) {
  443. foreach ($value as $k => $v) {
  444. $folderTabs[$key][$k] = admin_trans_label($album_tabs[$v]);
  445. }
  446. }
  447. $folderTabs = json_encode($folderTabs);
  448. //以下JS作用:1.点击列表时,把folder_id参数传递给表单 2.切换文件夹时,显示隐藏相应的tab
  449. Admin::script(
  450. <<<JS
  451. const featherIcon = document.querySelector('i.feather.icon-list');
  452. if (featherIcon) {
  453. // 找到 <i> 的上级 <a> 元素
  454. const parentLink = featherIcon.closest('a');
  455. if (parentLink) {
  456. // 绑定 onclick 事件
  457. parentLink.onclick = function(event) {
  458. // 阻止默认行为(如跳转)
  459. event.preventDefault();
  460. // 获取 folder_id 的值
  461. let folderIdValue = $('select[name="folder_id"]').val();
  462. // 在 href 后追加 ?folder_id=xxx
  463. if (parentLink.href) {
  464. const newHref = parentLink.href + '?folder_id=' + folderIdValue;
  465. window.location.href = newHref; // 跳转到新的 URL
  466. }
  467. };
  468. }
  469. }
  470. // 监听 <select name="folder_id"> 的变化事件
  471. $('select[name="folder_id"]').change(function() {
  472. showHideTabs($(this).val());
  473. });
  474. folderIdValue = $('select[name="folder_id"]').val();
  475. showHideTabs(folderIdValue);
  476. function showHideTabs(fid) {
  477. // 获取当前选中的值
  478. let folderTabs = {$folderTabs};
  479. const folderIdValue = fid;
  480. // 获取当前 folderIdValue 对应的标签索引
  481. const tabIndexes = folderTabs[folderIdValue];
  482. console.log(tabIndexes);
  483. if (tabIndexes) {
  484. // 处理上方的 <li>,限定在 .nav-tabs 内
  485. $('.nav-tabs .nav-item').each(function(index) {
  486. if (index > 0) { // 跳过第一个固定元素
  487. $(this).hide();
  488. }
  489. });
  490. $('.nav-tabs .nav-item').each(function() {
  491. const navItem = $(this);
  492. const navLink = navItem.find('.nav-link');
  493. // 获取清理后的导航文本(包含处理空格和特殊字符)
  494. const tabText = navLink.clone().children().remove().end().text().trim();
  495. // 逻辑判断与显示控制
  496. if (tabIndexes.includes(tabText)) {
  497. navItem.show(); // 显式设置显示
  498. }
  499. });
  500. }
  501. }
  502. JS
  503. );
  504. }
  505. }