SmmPostController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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('本地素材发布');
  37. $form->action('ssm-post');
  38. $form->disableListButton();
  39. $form->multipleSteps()
  40. ->remember()
  41. ->width('950px')
  42. ->add('选择本地媒体', 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,不大于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(120400)
  69. ->chunked()
  70. ->removable();
  71. //->chunked()
  72. })
  73. ->options([ 0=>admin_trans_label('images'), 1=>admin_trans_label('videos')])->default(0);
  74. $this->stepLeaving($step,0);
  75. })
  76. ->add('选择传单社媒平台', function ($step) {
  77. $rootAccounts = SmmUserAccount::getUserAccounts();
  78. $listBoxOptions = [];
  79. foreach ($rootAccounts as $account) {
  80. if (SmmPostLog::getPostQuota($account->getParent->name) > 0) {
  81. //限额大于0才显示
  82. $listBoxOptions[$account->id] = $account->name . ' ('.$account->getParent->name.')';
  83. }
  84. }
  85. $step->listbox('account_ids', '<span style="color:#bd4147;">*</span> '.admin_trans_label('accountsSelect'))
  86. ->options($listBoxOptions);
  87. $step->select('youtube_category')->setView('distributor.form_custom.select_hide')->options(SmmUserAccount::getYoutubeCategory())->default(22)->required();
  88. $this->stepLeaving($step,1);
  89. });
  90. $this->addJs();
  91. });
  92. }
  93. /*
  94. * 保存数据
  95. */
  96. public function store() {
  97. $post = $_POST;
  98. if (isset($post['_file_del_'])) {
  99. // 删除上传的文件
  100. header('Content-Type: application/json');
  101. echo json_encode(['status' => true, 'data' => []]);
  102. exit;
  103. }
  104. if (isset($post['upload_column']) && ($post['upload_column'] == 'image_url' || $post['upload_column'] == 'video_url')) {
  105. // 上传图片或视频
  106. return $this->upload();
  107. }
  108. if (isset($post['ALL_STEPS']) && $post['ALL_STEPS'] == '1') {
  109. if ($post['account_ids'] == [] || count($post['account_ids']) == 0 || $post['account_ids'] == '' || empty($post['account_ids'][0])) {
  110. return Admin::json()->error('请选择社媒帐号');
  111. }
  112. $post_type = $post['post_type'];
  113. if ($post_type == 0) {
  114. $image_video_url = $post['image_url'];
  115. $post['message'] = $post['image_message'];
  116. } else {
  117. $image_video_url = $post['video_url'];
  118. $post['message'] = $post['video_message'];
  119. }
  120. if ($this->checkStoragePath($image_video_url) === false) {
  121. return Admin::json()->error('请检查上传文件是否存在');
  122. }
  123. if ($post['send_type'] == 0) {
  124. $send_time = Carbon::now();
  125. } else {
  126. // 從北京時間字符串創建 Carbon 對象
  127. $sendTime = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'], 'Asia/Shanghai');
  128. // 轉換為 UTC 時間
  129. $send_time = $sendTime->setTimezone('UTC');
  130. // $send_time = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'])->setTimezone('UTC');
  131. }
  132. //保存数据
  133. SmmPost::create($post,$send_time,$image_video_url);
  134. // 生成发送记录
  135. $timer = new TimerSsmPost();
  136. $timer->createLog();
  137. //最后一步
  138. $data = [
  139. 'title' => '操作成功',
  140. 'description' => '系统已生成发送队列,详情请查看日志。 ',
  141. ];
  142. return view('distributor.form_custom.completion-page', $data);
  143. }
  144. }
  145. /**
  146. * 上传图片到本地
  147. */
  148. public function upload() {
  149. try {
  150. //保存到本地
  151. $disk = $this->disk('local');
  152. // 判断是否是删除文件请求
  153. if ($this->isDeleteRequest()) {
  154. // 删除文件并响应
  155. return $this->deleteFileAndResponse($disk);
  156. }
  157. // 获取上传的文件
  158. $file = $this->file();
  159. $dir = 'ssm/'.getDistributorId();
  160. $newName = md5(uniqid() . mt_rand()) .'.'.$file->getClientOriginalExtension();
  161. //保存在本地
  162. $result = $disk->putFileAs($dir, $file, $newName);
  163. //oss 保存
  164. // $disk = $this->disk('oss');
  165. // $result = $disk->putFileAs($dir, $file, $newName);
  166. return $result
  167. ? $this->responseUploaded($result, $disk->url($result))
  168. : $this->responseErrorMessage(admin_trans_label('upload_failed'));
  169. } catch (\Exception $e) {
  170. return $this->responseErrorMessage($e->getMessage());
  171. }
  172. }
  173. /*
  174. * 判断路径是否正确
  175. */
  176. public function checkStoragePath ($filePath) {
  177. $storagePath = 'ssm/'.getDistributorId();
  178. if (strpos($filePath, $storagePath) === 0) {
  179. return true;
  180. }
  181. return false;
  182. }
  183. private function stepLeaving($step,$index=0)
  184. {
  185. $lang = config('app.locale');//当前语言
  186. //JS 验证参数不能为空
  187. if ($index == 0) {
  188. $step->leaving(<<<JS
  189. // 全局缓存对象,存储被移除的YouTube选项 {selectName: jQueryObject}
  190. function toggleYouTube(flag) {
  191. var \$this = \$(this);
  192. // 定义选择器
  193. var youtubeSelector = 'option:contains("(YouTube)")';
  194. var \$helper1 = \$('select[name="account_ids[]_helper1"]');
  195. var \$helper2 = \$('select[name="account_ids[]_helper2"]');
  196. var \$mainSelect = \$('select[name="account_ids[]"]');
  197. // 初始化数据存储
  198. if (!\$this.data('youtubeOptions')) {
  199. \$this.data('youtubeOptions', {
  200. helper1: \$helper1.find(youtubeSelector).clone(true),
  201. helper2: \$helper2.find(youtubeSelector).clone(true),
  202. main: \$mainSelect.find(youtubeSelector).clone(true),
  203. positions: { // 记录原始位置
  204. helper1: \$helper1.find(youtubeSelector).index(),
  205. helper2: \$helper2.find(youtubeSelector).index(),
  206. main: \$mainSelect.find(youtubeSelector).index()
  207. }
  208. });
  209. }
  210. // 通用移除函数
  211. function removeYouTubeOptions(\$container) {
  212. \$container.find(youtubeSelector).each(function() {
  213. \$(this).detach(); // 使用 detach 保留事件和数据的引用
  214. });
  215. }
  216. // 移除所有 YouTube 选项
  217. removeYouTubeOptions(\$helper1);
  218. removeYouTubeOptions(\$helper2);
  219. removeYouTubeOptions(\$mainSelect);
  220. // 还原逻辑
  221. if (flag === false) {
  222. var saved = \$this.data('youtubeOptions');
  223. // 精确还原到原始位置
  224. saved.helper1.insertAfter(
  225. \$helper1.find('option').eq(saved.positions.helper1 - 1)
  226. );
  227. saved.helper2.insertAfter(
  228. \$helper2.find('option').eq(saved.positions.helper2 - 1)
  229. );
  230. saved.main.insertAfter(
  231. \$mainSelect.find('option').eq(saved.positions.main - 1)
  232. );
  233. }
  234. //把选择账号全部向左移
  235. $(".removeall ").click();
  236. //隐藏youtube 分类
  237. $('#select_hide_youtube_category').toggle(false);
  238. }
  239. function validateForm(formArray) {
  240. lang = '{$lang}';
  241. // 仅获取radio类型的post_type值
  242. let postType = formArray.find(item =>
  243. item.name === 'post_type' && item.type === 'radio'
  244. )?.value;
  245. // 仅获取radio类型的send_type值
  246. let sendType = formArray.find(item =>
  247. item.name === 'send_type' && item.type === 'radio'
  248. )?.value;
  249. // 验证post_type相关规则
  250. if (postType === '0') {
  251. const imageMessage = formArray.find(item => item.name === 'image_message')?.value;
  252. const imageUrl = formArray.find(item => item.name === 'image_url')?.value;
  253. if (!imageMessage || !imageUrl) {
  254. if (lang === 'en') {
  255. return 'Post message and images cannot be empty';
  256. } else {
  257. return '帖子留言和图片不能为空';
  258. }
  259. }
  260. //隐藏youtube的帐号
  261. toggleYouTube(true);
  262. } else if (postType === '1') {
  263. const videoMessage = formArray.find(item => item.name === 'video_message')?.value;
  264. const videoUrl = formArray.find(item => item.name === 'video_url')?.value;
  265. if (!videoMessage || !videoUrl) {
  266. if (lang === 'en') {
  267. return 'Post message and video cannot be empty';
  268. } else {
  269. return '帖子留言和视频不能为空';
  270. }
  271. }
  272. toggleYouTube(false);
  273. }
  274. // 验证send_type规则(仅处理radio类型的send_type)
  275. if (sendType === '1') {
  276. const sendTime = formArray.find(item => item.name === 'send_time')?.value;
  277. if (!sendTime) {
  278. if (lang === 'en') {
  279. return 'Send time cannot be empty';
  280. } else {
  281. return '定时发送时间不能为空';
  282. }
  283. }
  284. }
  285. return "";
  286. }
  287. var formArray = args.formArray;
  288. rs = validateForm(formArray);
  289. if (rs != "") {
  290. Dcat.error(rs);
  291. return false;
  292. }
  293. JS);
  294. } else {
  295. $step->leaving(<<<JS
  296. var formArray = args.formArray;
  297. var lang = '{$lang}';
  298. //找account_ids
  299. let accountIds = formArray.find(item => item.name === 'account_ids[]')?.value;
  300. if (!accountIds || accountIds.length === 0) {
  301. if (lang === 'en') {
  302. Dcat.error('Please select accounts');
  303. } else {
  304. Dcat.error('请选择社媒帐号');
  305. }
  306. return false;
  307. }
  308. JS);
  309. }
  310. }
  311. public function addJs()
  312. {
  313. Admin::script(
  314. <<<JS
  315. function checkYouTubeOption(select) {
  316. // 检查是否存在包含"YouTube"的option
  317. var hasYouTube = select.find('option:contains("YouTube")').length > 0;
  318. // 切换目标元素的显示状态
  319. $('#select_hide_youtube_category').toggle(hasYouTube);
  320. }
  321. var select = $('select[name="account_ids\\[\\]_helper2"]');
  322. var select_lenght = select.children().length;
  323. let intervalId = setInterval(() => {
  324. var select = $('select[name="account_ids\\[\\]_helper2"]');
  325. // 处理变化的逻辑
  326. if (select_lenght != select.children().length) {
  327. checkYouTubeOption(select);
  328. }
  329. }, 300);
  330. JS
  331. );
  332. }
  333. }