SiteAlbumController.php 23 KB

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