SmmPostController.php 13 KB

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