SiteAlbumController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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('enabled')->using(admin_trans_array(config('dictionary.enabled'))) ->label([
  137. 0 => 'danger',
  138. 1 => 'success',
  139. ]);
  140. $grid->column('status')->display(function ($status) {
  141. $updated_at = $this->updated_at->format('Y-m-d H:i:s');
  142. //三个月前显示待更新
  143. if (time() - strtotime($updated_at) > 90 * 24 * 3600) {
  144. return '<span class="label label-warning" style="background:#dda451">待更新</span>';
  145. } else {
  146. return '<span class="label label-success" style="background:#21b978">正常</span>';
  147. }
  148. });
  149. $grid->column('missing_content')->display(function ($missing_content) {
  150. $missing_content = [];
  151. if ($this->cover == '[]') {$missing_content[] = '主图';}
  152. if ($this->text_detail == '') {$missing_content[] = '文字介绍';}
  153. if ($this->en_detail == '[]') {$missing_content[] = '英文详情页';}
  154. if ($this->cn_detail == '[]') {$missing_content[] = '中文详情页';}
  155. if ($this->video == '[]') {$missing_content[] = '视频';}
  156. if ($this->poster == '[]') {$missing_content[] = '海报';}
  157. if ($this->cert == '[]') {$missing_content[] = '证书';}
  158. if ($this->pdf == '[]') {$missing_content[] = 'PDF';}
  159. return implode(' / ', $missing_content);
  160. });
  161. // 筛选
  162. $grid->filter(function (Grid\Filter $filter) {
  163. $selectOptions = SiteAlbumFolderModel::selectOptions();
  164. unset($selectOptions[0]);
  165. $filter->panel();
  166. $filter->expand();
  167. $filter->like('model')->width(2);
  168. $filter->equal('folder_id',admin_trans_label('folder'))->select($selectOptions)->width(3);
  169. $filter->where('status', function ($query) {
  170. $status = $this->input;
  171. // 自定义查询逻辑
  172. if ($status == 1) {
  173. // 三个月内的
  174. $query->where('updated_at', '>=', date('Y-m-d H:i:s', strtotime('-3 month')));
  175. } else {
  176. // 三个月前的
  177. $query->where('updated_at', '<', date('Y-m-d H:i:s', strtotime('-3 month')));
  178. }
  179. })->select(admin_trans_array(config('dictionary.album_status')))->width(3);
  180. });
  181. $grid->disableViewButton();
  182. $grid->disablePerPages();
  183. $grid->disableRefreshButton();
  184. $grid->model()->orderBy('order', 'asc')->orderBy('id', 'desc');
  185. //弹窗大小
  186. $grid->setDialogFormDimensions('830px','670px');
  187. });
  188. }
  189. protected function form()
  190. {
  191. $thisObj = $this;
  192. return Form::make(new SiteAlbum(), function (Form $form) use ($thisObj) {
  193. if ($form->isEditing()) {
  194. $form->title("编辑 | " . $form->model()->title);
  195. }
  196. $form->width(9, 1);
  197. $form->disableViewButton();
  198. $form->disableViewCheck();
  199. $form->saving(function (Form $form) use ($thisObj) {
  200. //处理video
  201. $videos = $form->input('video');
  202. if ($videos) {
  203. foreach ($videos as $key => $value) {
  204. if (empty($value['cover']) && $value['_remove_'] != 1) {
  205. //自动生成封面
  206. $result = $thisObj->autoGenerateCover($value['video_src']);
  207. if ($result['status']) {
  208. $videos[$key]['cover'] = $result['path'];
  209. } else {
  210. return $form->response()->error($result['msg']);
  211. }
  212. }
  213. }
  214. } else {
  215. $videos = [];
  216. }
  217. $form->input('video', $videos);
  218. //处理pdf
  219. $pdfs = $form->input('pdf');
  220. $pdfs = empty($pdfs) ? [] : $pdfs;
  221. $form->input('pdf', $pdfs);
  222. //记录日志
  223. if (!$form->isCreating()) {
  224. $id = $form->getKey();
  225. $cacheKey = 'album_log_'.$id;
  226. Cache::add($cacheKey, json_encode($form->model()->toArray()), 3600);
  227. }
  228. });
  229. $form->saved(function (Form $form) {
  230. if (empty($form->input('model')) == false) {
  231. $id = $form->getKey();
  232. $action = $form->isCreating() ? 'add' : 'edit';
  233. if ($action == 'add') {
  234. $oldData = "[]";
  235. } else {
  236. $oldData = Cache::get('album_log_'. $id);
  237. Cache::forget('album_log_'. $id);
  238. }
  239. SiteAlbumLog::log($action, $id,$form->input('model'),$oldData);
  240. }
  241. });
  242. $form->tab(admin_trans_label('basic_info'), function (Form $form) {
  243. $selectOptions = SiteAlbumFolder::selectOptions();
  244. unset($selectOptions[0]);
  245. $folderId = getTempValue('folderId');
  246. if ($folderId == 0) {
  247. $folderId = array_key_first($selectOptions);
  248. }
  249. $form->select('folder_id')->options($selectOptions)->default($folderId)->required();
  250. $form->text('title',admin_trans_label('product_name'))->required();
  251. $form->text('title_en',admin_trans_label('product_name_en'))->required();
  252. $form->text('model')->required();
  253. $form->table('parameters',admin_trans_label('attribute_name'), function (Form\NestedForm $table) {
  254. $table->text('key')->required();
  255. $table->text('value')->required();
  256. })->setView('admin.form_custom.hasmanytable')
  257. ->saving(function ($input) {
  258. return json_encode($input);
  259. });
  260. $form->switch('enabled')->default(1);
  261. })->tab(admin_trans_label('cover'), function (Form $form) {
  262. $form->multipleImage('cover')
  263. ->retainable()//禁止删OSS图
  264. ->sortable() // 可拖动排序
  265. ->removable() // 可移除图片
  266. ->autoUpload() // 自动上传
  267. ->uniqueName()
  268. ->limit(config('admin.upload.oss_image.limit'))
  269. ->accept(config('admin.upload.oss_image.accept'))
  270. ->maxSize(config('admin.upload.oss_image.max_size'))
  271. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  272. ->saving(function ($images) use ($form) {
  273. return json_encode($images);
  274. });
  275. })->tab(admin_trans_label('text_detail'), function (Form $form) {
  276. $form->editor('text_detail',admin_trans_label('text_detail'));
  277. })->tab(admin_trans_label('en_detail'), function (Form $form) {
  278. $form->multipleImage('en_detail')
  279. ->retainable()//禁止删OSS图
  280. ->sortable() // 可拖动排序
  281. ->removable() // 可移除图片
  282. ->autoUpload() // 自动上传
  283. ->uniqueName()
  284. ->limit(config('admin.upload.oss_image.limit'))
  285. ->accept(config('admin.upload.oss_image.accept'))
  286. ->maxSize(config('admin.upload.oss_image.max_size'))
  287. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  288. ->saving(function ($images) use ($form) {
  289. return json_encode($images);
  290. });
  291. })->tab(admin_trans_label('cn_detail'), function (Form $form) {
  292. $form->multipleImage('cn_detail')
  293. ->retainable()//禁止删OSS图
  294. ->sortable() // 可拖动排序
  295. ->removable() // 可移除图片
  296. ->autoUpload() // 自动上传
  297. ->uniqueName()
  298. ->limit(config('admin.upload.oss_image.limit'))
  299. ->accept(config('admin.upload.oss_image.accept'))
  300. ->maxSize(config('admin.upload.oss_image.max_size'))
  301. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  302. ->saving(function ($images) use ($form) {
  303. return json_encode($images);
  304. });
  305. })->tab(admin_trans_label('video'), function (Form $form) {
  306. $count = 0;
  307. $form->hasMany('video', function (Form\NestedForm $form) use (&$count) {
  308. $videos = $form->model()->video;
  309. $imgArray = "";
  310. if ($videos) {
  311. $videos = json_decode($videos,true);
  312. foreach ($videos as $key => $value) {
  313. if ($value['cover'] && $key == $count-1) {
  314. $imgArray = [$value['cover']];
  315. }
  316. }
  317. }
  318. $imgHtml = CommonHelper::displayImage($imgArray);
  319. $form->html($imgHtml,admin_trans_label('image_preview'));
  320. $count++;
  321. $form->text('video_title',admin_trans_label('video_title'))->required();
  322. $form->text('video_en_title',admin_trans_label('video_en_title'))->required();
  323. $form->hidden('cover',admin_trans_label('video_cover'))->placeholder('自动生成')->readOnly();
  324. $form->tradFile('video_src')
  325. ->retainable()//禁止删OSS图
  326. ->removable() // 可移除图片
  327. ->autoUpload() // 自动上传
  328. ->uniqueName()//
  329. ->downloadable()
  330. ->accept(config('admin.upload.oss_video.accept'))
  331. ->maxSize(config('admin.upload.oss_video.max_size'))
  332. ->dir(config("admin.upload.directory.video").'/uploads/'.date("Ym"))
  333. ->chunkSize(1024)
  334. ->required();
  335. })->useTable()
  336. ->customFormat(function ($data) {return json_decode($data,true);})
  337. ->setView('admin.form_custom.hasmanytable')
  338. ->saving(function ($input) {
  339. $data = [];
  340. foreach ($input as $value) {
  341. if ($value['_remove_'] != 1){
  342. $data[] = ['cover'=>$value['cover'],'video_title'=>$value['video_title'],'video_en_title' => $value['video_en_title'],'video_src'=>$value['video_src']];
  343. }
  344. }
  345. return json_encode($data);
  346. });
  347. })->tab(admin_trans_label('poster'), function (Form $form) {
  348. $form->multipleImage('poster')
  349. ->retainable()//禁止删OSS图
  350. ->sortable() // 可拖动排序
  351. ->removable() // 可移除图片
  352. ->autoUpload() // 自动上传
  353. ->uniqueName()
  354. ->limit(config('admin.upload.oss_image.limit'))
  355. ->accept(config('admin.upload.oss_image.accept'))
  356. ->maxSize(config('admin.upload.oss_image.max_size'))
  357. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  358. ->saving(function ($images) use ($form) {
  359. return json_encode($images);
  360. });
  361. })->tab(admin_trans_label('cert'), function (Form $form) {
  362. $form->multipleImage('cert')
  363. ->retainable()//禁止删OSS图
  364. ->sortable() // 可拖动排序
  365. ->removable() // 可移除图片
  366. ->autoUpload() // 自动上传
  367. ->uniqueName()
  368. ->limit(config('admin.upload.oss_image.limit'))
  369. ->accept(config('admin.upload.oss_image.accept'))
  370. ->maxSize(config('admin.upload.oss_image.max_size'))
  371. ->dir(config("admin.upload.directory.image").'/uploads/'.date("Ym"))
  372. ->saving(function ($images) use ($form) {
  373. return json_encode($images);
  374. });
  375. })->tab(admin_trans_label('pdf'), function (Form $form) {
  376. $form->hasMany('pdf', function ($form) {
  377. $form->text('pdf_title')->required();
  378. $form->text('pdf_title_en')->required();
  379. $form->tradFile('pdf_src')
  380. ->retainable()//禁止删OSS图
  381. ->removable() // 可移除图片
  382. ->autoUpload() // 自动上传
  383. ->uniqueName()
  384. ->downloadable()
  385. ->accept(config('admin.upload.oss_pdf.accept'))
  386. ->maxSize(config('admin.upload.oss_pdf.max_size'))
  387. ->dir(config("admin.upload.directory.pdf").'/uploads/'.date("Ym"))
  388. ->chunkSize(1024)
  389. ->required();
  390. })->useTable()
  391. ->customFormat(function ($data) {
  392. return json_decode($data,true);
  393. })
  394. ->setView('admin.form_custom.hasmanytable')
  395. ->saving(function ($input) {
  396. $data = [];
  397. foreach ($input as $value) {
  398. if ($value['_remove_'] != 1){
  399. $data[] = ['pdf_title'=>$value['pdf_title'],'pdf_title_en' => $value['pdf_title_en'],'pdf_src'=>$value['pdf_src']];
  400. }
  401. }
  402. return json_encode($data);
  403. });
  404. });
  405. //以下JS代码用于点击列表时,带上folder_id参数,还有隐藏的tab切换功能
  406. $thisObj->formAddJS();
  407. });
  408. }
  409. /*
  410. * 自动生成视频封面,并上传到OSS
  411. */
  412. private function autoGenerateCover($videoSrc)
  413. {
  414. try {
  415. $cover = $videoSrc.'?x-oss-process=video/snapshot,t_2000,f_jpg,h_500,m_fast';
  416. $cover = CommonHelper::ossUrl($cover);
  417. $path = $this->upload($cover,'.jpg');
  418. } catch (\Exception $e) {
  419. $path = ['status'=>true,'path'=>'/static/common/images/no-image.jpg'];
  420. }
  421. return $path;
  422. }
  423. private function upload($file,$imgType='.jpg')
  424. {
  425. $disk = $this->disk('oss');
  426. $newName = uniqueCode("video_cover_").$imgType;
  427. $dir = config("admin.upload.directory.image").'/uploads/'.date("Ym").'/'.$newName;
  428. $contents = file_get_contents($file);
  429. if (!$contents) {
  430. return ['status'=>false,'msg'=>'图片上传失败,请检查PHP配置'];
  431. }
  432. $disk->put($dir, $contents);
  433. return ['status'=>true,'path'=>$dir];
  434. }
  435. private function formAddJS() {
  436. $folderTabs = SiteAlbumFolder::getAllFolderTabs();
  437. $album_tabs = config('dictionary.album_tabs');
  438. foreach ($folderTabs as $key => $value) {
  439. foreach ($value as $k => $v) {
  440. $folderTabs[$key][$k] = admin_trans_label($album_tabs[$v]);
  441. }
  442. }
  443. $folderTabs = json_encode($folderTabs);
  444. //以下JS作用:1.点击列表时,把folder_id参数传递给表单 2.切换文件夹时,显示隐藏相应的tab
  445. Admin::script(
  446. <<<JS
  447. const featherIcon = document.querySelector('i.feather.icon-list');
  448. if (featherIcon) {
  449. // 找到 <i> 的上级 <a> 元素
  450. const parentLink = featherIcon.closest('a');
  451. if (parentLink) {
  452. // 绑定 onclick 事件
  453. parentLink.onclick = function(event) {
  454. // 阻止默认行为(如跳转)
  455. event.preventDefault();
  456. // 获取 folder_id 的值
  457. let folderIdValue = $('select[name="folder_id"]').val();
  458. // 在 href 后追加 ?folder_id=xxx
  459. if (parentLink.href) {
  460. const newHref = parentLink.href + '?folder_id=' + folderIdValue;
  461. window.location.href = newHref; // 跳转到新的 URL
  462. }
  463. };
  464. }
  465. }
  466. // 监听 <select name="folder_id"> 的变化事件
  467. $('select[name="folder_id"]').change(function() {
  468. showHideTabs($(this).val());
  469. });
  470. folderIdValue = $('select[name="folder_id"]').val();
  471. showHideTabs(folderIdValue);
  472. function showHideTabs(fid) {
  473. // 获取当前选中的值
  474. let folderTabs = {$folderTabs};
  475. const folderIdValue = fid;
  476. // 获取当前 folderIdValue 对应的标签索引
  477. const tabIndexes = folderTabs[folderIdValue];
  478. console.log(tabIndexes);
  479. if (tabIndexes) {
  480. // 处理上方的 <li>,限定在 .nav-tabs 内
  481. $('.nav-tabs .nav-item').each(function(index) {
  482. if (index > 0) { // 跳过第一个固定元素
  483. $(this).hide();
  484. }
  485. });
  486. $('.nav-tabs .nav-item').each(function() {
  487. const navItem = $(this);
  488. const navLink = navItem.find('.nav-link');
  489. // 获取清理后的导航文本(包含处理空格和特殊字符)
  490. const tabText = navLink.clone().children().remove().end().text().trim();
  491. // 逻辑判断与显示控制
  492. if (tabIndexes.includes(tabText)) {
  493. navItem.show(); // 显式设置显示
  494. }
  495. });
  496. }
  497. }
  498. JS
  499. );
  500. }
  501. }