HandlesEsgParagraphs.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. // app/Traits/HandlesParagraphs.php
  3. namespace App\Traits;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Str;
  6. trait HandlesEsgParagraphs
  7. {
  8. /**
  9. * 格式化 paragraphs 資料以符合表單結構(載入時使用)
  10. */
  11. protected function formatParagraphsForForm(array $paragraphs): array
  12. {
  13. $formattedParagraphs = [];
  14. foreach ($paragraphs as $paragraph) {
  15. \Log::info("格式化段落:", $paragraph);
  16. $formatted = [
  17. 'id' => $paragraph['id'],
  18. 'type' => $paragraph['type'],
  19. 'order' => $paragraph['order'],
  20. 'content' => $paragraph['content'] ?? [],
  21. ];
  22. // 根據類型進行特殊格式化
  23. switch ($paragraph['type']) {
  24. case 1: // 純文字
  25. $formatted = $this->formatTextParagraphForForm($formatted);
  26. break;
  27. case 2: // 區塊文字
  28. $formatted = $this->formatBlockParagraphForForm($formatted);
  29. break;
  30. case 3: // 表格
  31. $formatted = $this->formatTableParagraphForForm($formatted);
  32. break;
  33. case 4: // 圖片
  34. $formatted = $this->formatImageParagraphForForm($formatted);
  35. break;
  36. }
  37. // 確保有 item_key
  38. if (!isset($formatted['item_key'])) {
  39. $formatted['item_key'] = Str::random();
  40. }
  41. $formattedParagraphs[] = $formatted;
  42. \Log::info("格式化完成:", $formatted);
  43. }
  44. return $formattedParagraphs;
  45. }
  46. /**
  47. * 格式化純文字段落(載入時)
  48. */
  49. protected function formatTextParagraphForForm(array $paragraph): array
  50. {
  51. // 確保 text_content 結構正確
  52. if (!isset($paragraph['content']['text_content'])) {
  53. $paragraph['content']['text_content'] = ['zh_TW' => '', 'en' => ''];
  54. }
  55. return $paragraph;
  56. }
  57. /**
  58. * 格式化區塊文字段落(載入時)
  59. */
  60. protected function formatBlockParagraphForForm(array $paragraph): array
  61. {
  62. // 確保 text_blocks 結構正確
  63. if (!isset($paragraph['content']['text_blocks'])) {
  64. $paragraph['content']['text_blocks'] = [];
  65. }
  66. // 為每個 text_block 添加必要的欄位
  67. foreach ($paragraph['content']['text_blocks'] as $index => &$block) {
  68. if (!isset($block['block_item_key'])) {
  69. $block['block_item_key'] = Str::random();
  70. }
  71. if (!isset($block['order'])) {
  72. $block['order'] = $index + 1;
  73. }
  74. }
  75. return $paragraph;
  76. }
  77. /**
  78. * 格式化表格段落(載入時)
  79. */
  80. protected function formatTableParagraphForForm(array $paragraph): array
  81. {
  82. $content = $paragraph['content'];
  83. if (!isset($content['column_count'])) {
  84. $content['column_count'] = 2;
  85. }
  86. if (!isset($content['table_title'])) {
  87. $content['table_title'] = ['zh_TW' => '', 'en' => ''];
  88. }
  89. if (!isset($content['table_description'])) {
  90. $content['table_description'] = ['zh_TW' => '', 'en' => ''];
  91. }
  92. if (!isset($content['simple_table_rows'])) {
  93. $content['simple_table_rows'] = [];
  94. }
  95. // 確保表頭資料結構
  96. $columnCount = $content['column_count'];
  97. for ($i = 1; $i <= $columnCount; $i++) {
  98. if (!isset($content["head{$i}"])) {
  99. $content["head{$i}"] = ['zh_TW' => '', 'en' => ''];
  100. }
  101. }
  102. $paragraph['content'] = $content;
  103. return $paragraph;
  104. }
  105. /**
  106. * 格式化圖片段落(載入時)
  107. */
  108. protected function formatImageParagraphForForm(array $paragraph): array
  109. {
  110. // 確保 multiple_images 結構正確
  111. if (!isset($paragraph['content']['multiple_images'])) {
  112. $paragraph['content']['multiple_images'] = [];
  113. }
  114. // 為每個圖片添加必要的欄位
  115. foreach ($paragraph['content']['multiple_images'] as $index => &$image) {
  116. if (!isset($image['para_img_item_key'])) {
  117. $image['para_img_item_key'] = Str::random();
  118. }
  119. if (!isset($image['order'])) {
  120. $image['order'] = $index + 1;
  121. }
  122. }
  123. return $paragraph;
  124. }
  125. /**
  126. * 預處理 paragraphs 資料(儲存前使用)
  127. */
  128. protected function preprocessParagraphs(array $paragraphs): array
  129. {
  130. \Log::info("=== 開始預處理 Paragraphs ===");
  131. foreach ($paragraphs as $index => &$paragraph) {
  132. \Log::info("處理段落 {$index}:", $paragraph);
  133. // 確保基本欄位存在
  134. $paragraph['content'] = $paragraph['content'] ?? [];
  135. $paragraph['order'] = $paragraph['order'] ?? ($index + 1);
  136. // 根據類型進行特殊處理
  137. switch ($paragraph['type']) {
  138. case 1: // 純文字
  139. $paragraph = $this->preprocessTextParagraph($paragraph);
  140. break;
  141. case 2: // 區塊文字
  142. $paragraph = $this->preprocessBlockParagraph($paragraph);
  143. break;
  144. case 3: // 表格
  145. $paragraph = $this->preprocessTableParagraph($paragraph);
  146. break;
  147. case 4: // 圖片
  148. $paragraph = $this->preprocessImageParagraph($paragraph);
  149. break;
  150. }
  151. // 添加處理時間戳
  152. $paragraph['content']['processed_at'] = now()->toISOString();
  153. \Log::info("段落 {$index} 處理完成:", $paragraph);
  154. }
  155. return $paragraphs;
  156. }
  157. /**
  158. * 處理純文字段落(儲存前)
  159. */
  160. protected function preprocessTextParagraph(array $paragraph): array
  161. {
  162. \Log::info("處理純文字段落");
  163. // 確保文字內容結構正確
  164. if (!isset($paragraph['content']['text_content'])) {
  165. $paragraph['content']['text_content'] = ['zh_TW' => '', 'en' => ''];
  166. }
  167. // 清理 HTML 標籤(如果需要)
  168. foreach ($paragraph['content']['text_content'] as $locale => $content) {
  169. $paragraph['content']['text_content'][$locale] = $this->cleanHtml($content);
  170. }
  171. return $paragraph;
  172. }
  173. /**
  174. * 處理區塊文字段落(儲存前)
  175. */
  176. protected function preprocessBlockParagraph(array $paragraph): array
  177. {
  178. \Log::info("處理區塊文字段落");
  179. // 確保有 text_blocks
  180. if (!isset($paragraph['content']['text_blocks'])) {
  181. $paragraph['content']['text_blocks'] = [];
  182. }
  183. // 處理每個文字區塊
  184. foreach ($paragraph['content']['text_blocks'] as $index => &$block) {
  185. // 確保區塊有必要的欄位
  186. $block['block_item_key'] = $block['block_item_key'] ?? Str::random();
  187. $block['order'] = $block['order'] ?? ($index + 1);
  188. // 清理區塊內容
  189. if (isset($block['block_content'])) {
  190. foreach ($block['block_content'] as $locale => $content) {
  191. $block['block_content'][$locale] = $this->cleanHtml($content);
  192. }
  193. }
  194. }
  195. return $paragraph;
  196. }
  197. /**
  198. * 處理表格段落(儲存前)
  199. */
  200. protected function preprocessTableParagraph(array $paragraph): array
  201. {
  202. \Log::info("處理表格段落");
  203. // 確保欄數設定
  204. $columnCount = $paragraph['content']['column_count'] ?? 2;
  205. // 確保表頭存在
  206. if (!isset($paragraph['content']['headers'])) {
  207. $paragraph['content']['headers'] = ['zh_TW' => [], 'en' => []];
  208. }
  209. // 確保表格資料存在
  210. if (!isset($paragraph['content']['simple_table_rows'])) {
  211. $paragraph['content']['simple_table_rows'] = [];
  212. }
  213. // 處理表格資料,確保欄數一致
  214. foreach ($paragraph['content']['simple_table_rows'] as $rowIndex => &$row) {
  215. foreach (['zh_TW', 'en'] as $locale) {
  216. if (!isset($row[$locale])) {
  217. $row[$locale] = [];
  218. }
  219. // 確保每行都有正確的欄數
  220. for ($i = 1; $i <= $columnCount; $i++) {
  221. if (!isset($row[$locale]["col{$i}"])) {
  222. $row[$locale]["col{$i}"] = '';
  223. }
  224. }
  225. // 移除多餘的欄位
  226. for ($i = $columnCount + 1; $i <= 4; $i++) {
  227. unset($row[$locale]["col{$i}"]);
  228. }
  229. }
  230. }
  231. return $paragraph;
  232. }
  233. /**
  234. * 處理圖片段落(儲存前)
  235. */
  236. protected function preprocessImageParagraph(array $paragraph): array
  237. {
  238. \Log::info("處理圖片段落");
  239. // 確保圖片陣列存在
  240. if (!isset($paragraph['content']['multiple_images'])) {
  241. $paragraph['content']['multiple_images'] = [];
  242. }
  243. // 處理每個圖片
  244. foreach ($paragraph['content']['multiple_images'] as $index => &$image) {
  245. $image['para_img_item_key'] = $image['para_img_item_key'] ?? Str::random();
  246. $image['order'] = $image['order'] ?? ($index + 1);
  247. // 驗證圖片檔案是否存在
  248. if (isset($image['image_url'])) {
  249. // 這裡可以添加圖片驗證邏輯
  250. }
  251. }
  252. return $paragraph;
  253. }
  254. /**
  255. * 更新 paragraphs 關聯(編輯時使用)
  256. */
  257. protected function updateParagraphs(Model $record, array $paragraphs): void
  258. {
  259. \Log::info("=== 開始更新 Paragraphs 關聯 ===");
  260. // 獲取現有的段落 IDs
  261. $existingIds = collect($paragraphs)
  262. ->pluck('id')
  263. ->filter()
  264. ->values()
  265. ->toArray();
  266. // 刪除不在列表中的段落
  267. $record->paragraphs()
  268. ->whereNotIn('id', $existingIds)
  269. ->delete();
  270. \Log::info("已刪除不存在的段落");
  271. // 更新或建立段落
  272. foreach ($paragraphs as $paragraphData) {
  273. if (isset($paragraphData['id'])) {
  274. // 更新現有段落
  275. $paragraph = $record->paragraphs()->find($paragraphData['id']);
  276. if ($paragraph) {
  277. $paragraph->update([
  278. 'type' => $paragraphData['type'],
  279. 'order' => $paragraphData['order'],
  280. 'content' => $paragraphData['content'],
  281. ]);
  282. \Log::info("更新段落 ID: {$paragraphData['id']}");
  283. }
  284. } else {
  285. // 建立新段落
  286. $newParagraph = $record->paragraphs()->create([
  287. 'type' => $paragraphData['type'],
  288. 'order' => $paragraphData['order'],
  289. 'content' => $paragraphData['content'],
  290. ]);
  291. \Log::info("建立新段落 ID: {$newParagraph->id}");
  292. }
  293. }
  294. \Log::info("=== Paragraphs 關聯更新完成 ===");
  295. }
  296. /**
  297. * 建立 paragraphs 關聯(新增時使用)
  298. */
  299. protected function createParagraphs(Model $record, array $paragraphs): void
  300. {
  301. \Log::info("=== 開始建立 Paragraphs 關聯 ===");
  302. foreach ($paragraphs as $paragraphData) {
  303. $newParagraph = $record->paragraphs()->create([
  304. 'type' => $paragraphData['type'],
  305. 'order' => $paragraphData['order'],
  306. 'content' => $paragraphData['content'],
  307. ]);
  308. \Log::info("建立新段落 ID: {$newParagraph->id}");
  309. }
  310. \Log::info("=== Paragraphs 關聯建立完成 ===");
  311. }
  312. /**
  313. * 清理 HTML 內容
  314. */
  315. protected function cleanHtml(string $html): string
  316. {
  317. // 這裡可以根據需求自定義清理邏輯
  318. // 例如:移除危險標籤、清理空白等
  319. return trim($html);
  320. }
  321. /**
  322. * 後處理 paragraphs(儲存後使用)
  323. */
  324. protected function postProcessParagraphs($paragraphs): void
  325. {
  326. foreach ($paragraphs as $paragraph) {
  327. \Log::info("後處理段落:", [
  328. 'id' => $paragraph->id,
  329. 'type' => $paragraph->type,
  330. 'content_keys' => array_keys($paragraph->content ?? [])
  331. ]);
  332. // 這裡可以進行:
  333. // - 快取更新
  334. // - 搜尋索引更新
  335. // - 通知發送
  336. // 等後續處理
  337. }
  338. }
  339. /**
  340. * 獲取並格式化關聯資料(載入時的輔助方法)
  341. */
  342. protected function loadAndFormatParagraphs(Model $record): array
  343. {
  344. $paragraphs = $record->paragraphs()
  345. ->orderBy('order')
  346. ->get()
  347. ->toArray();
  348. return $this->formatParagraphsForForm($paragraphs);
  349. }
  350. /**
  351. * 處理表單狀態中的 paragraphs(儲存時的輔助方法)
  352. */
  353. protected function processFormParagraphs(): ?array
  354. {
  355. $formState = $this->form->getState();
  356. if (!isset($formState['paragraphs'])) {
  357. return null;
  358. }
  359. return $this->preprocessParagraphs($formState['paragraphs']);
  360. }
  361. }