SmmPostController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. namespace App\Distributor\Controllers;
  3. use App\Admin\Repositories\BaseProductImage;
  4. use App\Distributor\Repositories\SmmPost;
  5. use App\Distributor\Repositories\SmmPostLog;
  6. use App\Distributor\Repositories\SmmUserAccount;
  7. use App\Services\SmmService;
  8. use Carbon\Carbon;
  9. use Dcat\Admin\Form;
  10. use Dcat\Admin\Grid;
  11. use Dcat\Admin\Grid\Model;
  12. use Dcat\Admin\Show;
  13. use Dcat\Admin\Http\Controllers\AdminController;
  14. use Dcat\Admin\Layout\Content;
  15. use Dcat\Admin\Admin;
  16. use Dcat\Admin\FormStep\Form as StepForm;
  17. use Dcat\Admin\Traits\HasUploadedFile;
  18. use Dcat\Admin\Widgets\Alert;
  19. use App\Console\Commands\TimerSsmPost;
  20. use phpseclib3\Crypt\EC\BaseCurves\Montgomery;
  21. class SmmPostController extends AdminDistController
  22. {
  23. use HasUploadedFile;
  24. /**
  25. * page index
  26. */
  27. public function index(Content $content)
  28. {
  29. return $content
  30. ->header(admin_trans_label('send_post'))
  31. ->body($this->form());
  32. }
  33. protected function form()
  34. {
  35. return Form::make(new SmmPost(), function (Form $form) {
  36. $form->title(admin_trans_label('local_materials'));
  37. $form->action('ssm-post');
  38. $form->disableListButton();
  39. $form->multipleSteps()
  40. ->remember()
  41. ->width('950px')
  42. ->add(admin_trans_label('select_local_media'), function ($step) {
  43. $step->radio('send_type',admin_trans_label('send_type'))
  44. ->when([1], function ($step) {
  45. $step->datetime('send_time', '<span style="color:#bd4147;">*</span> '.admin_trans_label('send_time'))->placeholder(' ');
  46. })
  47. ->options([ 0=>admin_trans_label('immediate'), 1=>admin_trans_label('timing')])->default(0);
  48. $step->radio('post_type',admin_trans_label('media_type'))
  49. ->when([0], function ($step) {
  50. $step->textarea('image_message', '<span style="color:#bd4147;">*</span> '.admin_trans_label('post_message'))->rows(3)->placeholder(' ');
  51. $step->multipleImage('image_url', '<span style="color:#bd4147;">*</span> '.admin_trans_label('images'))
  52. ->retainable()//禁止删OSS图
  53. ->sortable() // 可拖动排序
  54. ->removable() // 可移除图片
  55. ->autoUpload() // 自动上传
  56. ->uniqueName()
  57. ->limit(4)
  58. ->accept('jpg,png')
  59. ->help('jpg,png (Max 3M)')
  60. ->maxSize(3072);
  61. })
  62. ->when([1], function ($step) {
  63. $step->textarea('video_message', '<span style="color:#bd4147;">*</span> '.admin_trans_label('post_message'))->rows(3)->placeholder(' ');
  64. $step->file('video_url','<span style="color:#bd4147;">*</span> '.admin_trans_label('video'))
  65. ->uniqueName()
  66. ->autoUpload()
  67. ->accept(config('admin.upload.oss_video.accept'))
  68. ->maxSize(20480)
  69. ->chunked()
  70. ->help('mp4 (Max 20M)')
  71. ->removable();
  72. //->chunked()
  73. })
  74. ->options([ 0=>admin_trans_label('images'), 1=>admin_trans_label('videos')])->default(0);
  75. $this->stepLeaving($step,0);
  76. })
  77. ->add(admin_trans_label('choose_platforms'), function ($step) {
  78. $rootAccounts = SmmUserAccount::getUserAccounts();
  79. $listBoxOptions = [];
  80. foreach ($rootAccounts as $account) {
  81. if (SmmPostLog::getPostQuota($account->getParent->name) > 0) {
  82. //限额大于0才显示
  83. $listBoxOptions[$account->id] = $account->name . ' ('.$account->getParent->name.')';
  84. }
  85. }
  86. $step->listbox('account_ids', '<span style="color:#bd4147;">*</span> '.admin_trans_label('accountsSelect'))
  87. ->options($listBoxOptions);
  88. $step->select('youtube_category')->setView('distributor.form_custom.select_hide')->options(SmmUserAccount::getYoutubeCategory())->default(22)->required();
  89. $this->stepLeaving($step,1);
  90. });
  91. $this->addJs();
  92. });
  93. }
  94. /*
  95. * 保存数据
  96. */
  97. public function store() {
  98. $post = $_POST;
  99. if (isset($post['_file_del_'])) {
  100. // 删除上传的文件
  101. header('Content-Type: application/json');
  102. echo json_encode(['status' => true, 'data' => []]);
  103. exit;
  104. }
  105. if (isset($post['upload_column']) && ($post['upload_column'] == 'image_url' || $post['upload_column'] == 'video_url')) {
  106. // 上传图片或视频
  107. return $this->upload();
  108. }
  109. if (isset($post['ALL_STEPS']) && $post['ALL_STEPS'] == '1') {
  110. if ($post['account_ids'] == [] || count($post['account_ids']) == 0 || $post['account_ids'] == '' || empty($post['account_ids'][0])) {
  111. return Admin::json()->error('请选择社媒帐号');
  112. }
  113. $post_type = $post['post_type'];
  114. if ($post_type == 0) {
  115. $image_video_url = $post['image_url'];
  116. $post['message'] = $post['image_message'];
  117. } else {
  118. $image_video_url = $post['video_url'];
  119. $post['message'] = $post['video_message'];
  120. }
  121. if ($this->checkStoragePath($image_video_url) === false) {
  122. return Admin::json()->error('请检查上传文件是否存在');
  123. }
  124. if ($post['send_type'] == 0) {
  125. $send_time = Carbon::now();
  126. } else {
  127. // 從北京時間字符串創建 Carbon 對象
  128. $sendTime = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'], 'Asia/Shanghai');
  129. // 轉換為 UTC 時間
  130. $send_time = $sendTime->setTimezone('UTC');
  131. // $send_time = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'])->setTimezone('UTC');
  132. }
  133. //保存数据
  134. SmmPost::create($post,$send_time,$image_video_url);
  135. // 生成发送记录
  136. $timer = new TimerSsmPost();
  137. $timer->createLog();
  138. //最后一步
  139. $data = [
  140. 'title' => admin_trans_label('operation_successful'),
  141. 'description' => admin_trans_label('send_post_description'),
  142. 'continue_publishing' => admin_trans_label('continue_publishing'),
  143. ];
  144. return view('distributor.form_custom.completion-page', $data);
  145. }
  146. }
  147. /**
  148. * 上传图片到本地
  149. */
  150. public function upload() {
  151. try {
  152. //保存到本地
  153. $disk = $this->disk('local');
  154. // 判断是否是删除文件请求
  155. if ($this->isDeleteRequest()) {
  156. // 删除文件并响应
  157. return $this->deleteFileAndResponse($disk);
  158. }
  159. // 获取上传的文件
  160. $file = $this->file();
  161. $dir = 'ssm/'.getDistributorId();
  162. $newName = md5(uniqid() . mt_rand()) .'.'.$file->getClientOriginalExtension();
  163. //保存在本地
  164. $result = $disk->putFileAs($dir, $file, $newName);
  165. //oss 保存
  166. // $disk = $this->disk('oss');
  167. // $result = $disk->putFileAs($dir, $file, $newName);
  168. return $result
  169. ? $this->responseUploaded($result, $disk->url($result))
  170. : $this->responseErrorMessage(admin_trans_label('upload_failed'));
  171. } catch (\Exception $e) {
  172. return $this->responseErrorMessage($e->getMessage());
  173. }
  174. }
  175. /*
  176. * 判断路径是否正确
  177. */
  178. public function checkStoragePath ($filePath) {
  179. $storagePath = 'ssm/'.getDistributorId();
  180. if (strpos($filePath, $storagePath) === 0) {
  181. return true;
  182. }
  183. return false;
  184. }
  185. private function stepLeaving($step,$index=0)
  186. {
  187. $lang = config('app.locale');//当前语言
  188. //JS 验证参数不能为空
  189. if ($index == 0) {
  190. $step->leaving(<<<JS
  191. // 全局缓存对象,存储被移除的YouTube选项 {selectName: jQueryObject}
  192. function toggleYouTube(flag) {
  193. var \$this = \$(this);
  194. // 定义选择器
  195. var youtubeSelector = 'option:contains("(YouTube)")';
  196. var \$helper1 = \$('select[name="account_ids[]_helper1"]');
  197. var \$helper2 = \$('select[name="account_ids[]_helper2"]');
  198. var \$mainSelect = \$('select[name="account_ids[]"]');
  199. // 初始化数据存储
  200. if (!\$this.data('youtubeOptions')) {
  201. \$this.data('youtubeOptions', {
  202. helper1: \$helper1.find(youtubeSelector).clone(true),
  203. helper2: \$helper2.find(youtubeSelector).clone(true),
  204. main: \$mainSelect.find(youtubeSelector).clone(true),
  205. positions: { // 记录原始位置
  206. helper1: \$helper1.find(youtubeSelector).index(),
  207. helper2: \$helper2.find(youtubeSelector).index(),
  208. main: \$mainSelect.find(youtubeSelector).index()
  209. }
  210. });
  211. }
  212. // 通用移除函数
  213. function removeYouTubeOptions(\$container) {
  214. \$container.find(youtubeSelector).each(function() {
  215. \$(this).detach(); // 使用 detach 保留事件和数据的引用
  216. });
  217. }
  218. // 移除所有 YouTube 选项
  219. removeYouTubeOptions(\$helper1);
  220. removeYouTubeOptions(\$helper2);
  221. removeYouTubeOptions(\$mainSelect);
  222. // 还原逻辑
  223. if (flag === false) {
  224. var saved = \$this.data('youtubeOptions');
  225. // 精确还原到原始位置
  226. saved.helper1.insertAfter(
  227. \$helper1.find('option').eq(saved.positions.helper1 - 1)
  228. );
  229. saved.helper2.insertAfter(
  230. \$helper2.find('option').eq(saved.positions.helper2 - 1)
  231. );
  232. saved.main.insertAfter(
  233. \$mainSelect.find('option').eq(saved.positions.main - 1)
  234. );
  235. }
  236. //把选择账号全部向左移
  237. $(".removeall ").click();
  238. //隐藏youtube 分类
  239. $('#select_hide_youtube_category').toggle(false);
  240. }
  241. function validateForm(formArray) {
  242. lang = '{$lang}';
  243. // 仅获取radio类型的post_type值
  244. let postType = formArray.find(item =>
  245. item.name === 'post_type' && item.type === 'radio'
  246. )?.value;
  247. // 仅获取radio类型的send_type值
  248. let sendType = formArray.find(item =>
  249. item.name === 'send_type' && item.type === 'radio'
  250. )?.value;
  251. // 验证post_type相关规则
  252. if (postType === '0') {
  253. const imageMessage = formArray.find(item => item.name === 'image_message')?.value;
  254. const imageUrl = formArray.find(item => item.name === 'image_url')?.value;
  255. if (!imageMessage || !imageUrl) {
  256. if (lang === 'en') {
  257. return 'Post message and images cannot be empty';
  258. } else {
  259. return '帖子留言和图片不能为空';
  260. }
  261. }
  262. //隐藏youtube的帐号
  263. toggleYouTube(true);
  264. } else if (postType === '1') {
  265. const videoMessage = formArray.find(item => item.name === 'video_message')?.value;
  266. const videoUrl = formArray.find(item => item.name === 'video_url')?.value;
  267. if (!videoMessage || !videoUrl) {
  268. if (lang === 'en') {
  269. return 'Post message and video cannot be empty';
  270. } else {
  271. return '帖子留言和视频不能为空';
  272. }
  273. }
  274. toggleYouTube(false);
  275. }
  276. // 验证send_type规则(仅处理radio类型的send_type)
  277. if (sendType === '1') {
  278. const sendTime = formArray.find(item => item.name === 'send_time')?.value;
  279. if (!sendTime) {
  280. if (lang === 'en') {
  281. return 'Send time cannot be empty';
  282. } else {
  283. return '定时发送时间不能为空';
  284. }
  285. }
  286. }
  287. return "";
  288. }
  289. var formArray = args.formArray;
  290. rs = validateForm(formArray);
  291. if (rs != "") {
  292. Dcat.error(rs);
  293. return false;
  294. }
  295. JS);
  296. } else {
  297. $step->leaving(<<<JS
  298. var formArray = args.formArray;
  299. var lang = '{$lang}';
  300. //找account_ids
  301. let accountIds = formArray.find(item => item.name === 'account_ids[]')?.value;
  302. if (!accountIds || accountIds.length === 0) {
  303. if (lang === 'en') {
  304. Dcat.error('Please select accounts');
  305. } else {
  306. Dcat.error('请选择社媒帐号');
  307. }
  308. return false;
  309. }
  310. JS);
  311. }
  312. }
  313. public function addJs()
  314. {
  315. Admin::script(
  316. <<<JS
  317. function checkYouTubeOption(select) {
  318. // 检查是否存在包含"YouTube"的option
  319. var hasYouTube = select.find('option:contains("YouTube")').length > 0;
  320. // 切换目标元素的显示状态
  321. $('#select_hide_youtube_category').toggle(hasYouTube);
  322. }
  323. var select = $('select[name="account_ids\\[\\]_helper2"]');
  324. var select_lenght = select.children().length;
  325. let intervalId = setInterval(() => {
  326. var select = $('select[name="account_ids\\[\\]_helper2"]');
  327. // 处理变化的逻辑
  328. if (select_lenght != select.children().length) {
  329. checkYouTubeOption(select);
  330. }
  331. }, 300);
  332. JS
  333. );
  334. }
  335. }