SmmPostController.php 13 KB

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