TipitakaController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php
  2. namespace App\Http\Controllers\Library;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Cookie;
  6. use Illuminate\Support\Facades\File;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Models\PaliText;
  9. use App\Models\ProgressChapter;
  10. use App\Services\TermService;
  11. class TipitakaController extends Controller
  12. {
  13. // 封面渐变色池:uid 首字节取余循环,保证同一文集颜色稳定
  14. private array $coverGradients = [
  15. 'linear-gradient(160deg, #2d1020, #ae6b8b)',
  16. 'linear-gradient(160deg, #1a2d10,rgba(75, 114, 36, 0.61))',
  17. 'linear-gradient(160deg, #0d1f3c,rgb(55, 98, 150))',
  18. 'linear-gradient(160deg, #2d1020,rgb(151, 69, 94))',
  19. 'linear-gradient(160deg, #1a1a2d,rgb(76, 68, 146))',
  20. 'linear-gradient(160deg, #1a2820,rgb(55, 124, 99))',
  21. ];
  22. /**
  23. * 构造函数,注入 TermService
  24. *
  25. * @param \App\Services\TermService $termService
  26. */
  27. public function __construct(
  28. protected TermService $termService,
  29. ) {}
  30. // -------------------------------------------------------------------------
  31. // 从 uid / id 字符串中提取一个稳定的整数,用于色池取余
  32. // -------------------------------------------------------------------------
  33. private function colorIndex(string $uid): int
  34. {
  35. return hexdec(substr(str_replace('-', '', $uid), 0, 4)) % 255;
  36. }
  37. protected static int $nextId = 1;
  38. // app/Http/Controllers/Library/CategoryController.php
  39. // category() 方法修改版
  40. // 变更:
  41. // 1. $id 改为可选参数,无参数时显示顶级分类(首页复用)
  42. // 2. 新增 $filters 过滤参数(type / lang / author / sort)
  43. // 3. 新增右边栏数据:$recommended / $activeAuthors
  44. // 4. 新增 $filterOptions(过滤器选项 + 计数)
  45. // 5. 新增 $totalCount
  46. public function index(Request $request, ?int $id = null)
  47. {
  48. $locale = Cookie::get('language') ?? 'en';
  49. $categories = $this->loadCategories();
  50. // ── 当前分类 ──────────────────────────────────────────
  51. if ($id) {
  52. $currentCategory = collect($categories)->firstWhere('id', $id);
  53. if (!$currentCategory) {
  54. abort(404);
  55. }
  56. $breadcrumbs = $this->getBreadcrumbs($currentCategory, $categories);
  57. } else {
  58. // 首页:虚拟顶级分类
  59. $currentCategory = ['id' => null, 'name' => '三藏'];
  60. $breadcrumbs = [];
  61. }
  62. // ── 子分类 ─────────────────────────────────────────────
  63. $subCategories = array_values(array_filter(
  64. $categories,
  65. fn($cat) => $cat['parent_id'] == $id
  66. ));
  67. if (count($subCategories) === 0 && !$request->has('book')) {
  68. $paliBooks = $this->getPaliBooks($categories, $id);
  69. foreach ($paliBooks as $value) {
  70. $subCategories[] = [
  71. 'id' => $id,
  72. 'name' => $value->text,
  73. 'book' => "{$value->book}-{$value->paragraph}"
  74. ];
  75. }
  76. }
  77. $allNames = array_map(fn($item) => $item['name'], $subCategories);
  78. // 去重
  79. $allNames = array_values(array_unique($allNames));
  80. // 查词典
  81. $terms = $this->termService->glossaryByLemma($allNames, $locale);
  82. // 构建映射
  83. $termMap = [];
  84. if ($terms) {
  85. foreach ($terms as $term) {
  86. $termMap[$term->word] = $term->meaning;
  87. }
  88. }
  89. // 回填
  90. foreach ($subCategories as $key => $cat) {
  91. $name = $cat['name'] ?? null;
  92. $subCategories[$key]['name'] = $termMap[$name] ?? $name;
  93. }
  94. // ── 过滤参数 ────────────────────────────────────────────
  95. $selectedType = request('type', 'all');
  96. $selectedLang = request('lang', 'all');
  97. $selectedAuthor = request('author', 'all');
  98. $selectedSort = request('sort', 'new');
  99. $sortList = [
  100. ['key' => 'new', 'label' => '最新',],
  101. ['key' => 'progress', 'label' => '完成度',],
  102. ];
  103. $selected = [
  104. 'type' => $selectedType,
  105. 'lang' => $selectedLang,
  106. 'author' => $selectedAuthor,
  107. 'sort' => $selectedSort,
  108. ];
  109. if ($request->has('book')) {
  110. $selected['book'] = $request->get('book');
  111. }
  112. // ── 书籍列表(过滤+排序,真实实现替换此处) ──────────────
  113. $categoryBooks = $this->getBooks($categories, $id, $selected);
  114. $totalCount = count($categoryBooks);
  115. // ── 过滤器选项(mock,真实实现从书籍数据聚合) ────────────
  116. $filterOptions = [
  117. 'types' => $this->filterTypes(),
  118. 'languages' => $this->filterLanguages(),
  119. 'authors' => $this->getAuthorOptions($categoryBooks),
  120. ];
  121. // ── 右边栏:本周推荐(mock) ────────────────────────────
  122. $recommended = $this->mockRecommended();
  123. // ── 右边栏:活跃译者(mock) ────────────────────────────
  124. $activeAuthors = $this->mockActiveAuthors();
  125. $types = $this->types();
  126. return view('library.tipitaka.category', compact(
  127. 'currentCategory',
  128. 'subCategories',
  129. 'categoryBooks',
  130. 'breadcrumbs',
  131. 'types',
  132. 'selected',
  133. 'filterOptions',
  134. 'totalCount',
  135. 'recommended',
  136. 'activeAuthors',
  137. 'sortList'
  138. ));
  139. }
  140. private function filterLanguages()
  141. {
  142. return [
  143. ['value' => 'all', 'label' => '全部', 'count' => 0],
  144. ['value' => 'zh-Hans', 'label' => '简体中文', 'count' => 0],
  145. ['value' => 'zh-Hant', 'label' => '繁体中文', 'count' => 0],
  146. ['value' => 'pi', 'label' => '巴利语', 'count' => 0],
  147. ['value' => 'en', 'label' => '英语', 'count' => 0],
  148. ];
  149. }
  150. private function filterTypes()
  151. {
  152. return [
  153. ['value' => 'all', 'label' => '全部', 'count' => 0],
  154. ['value' => 'original', 'label' => '原文', 'count' => 0],
  155. ['value' => 'translation', 'label' => '译文', 'count' => 0],
  156. ['value' => 'nissaya', 'label' => 'Nissaya', 'count' => 0],
  157. ];
  158. }
  159. private function mockRecommended()
  160. {
  161. return [
  162. ['id' => 1, 'title' => '相应部·因缘篇', 'category' => '经藏'],
  163. ['id' => 2, 'title' => '法句经', 'category' => '经藏'],
  164. ['id' => 3, 'title' => '清净道论', 'category' => '注释'],
  165. ['id' => 4, 'title' => '律藏·波罗夷', 'category' => '律藏'],
  166. ['id' => 5, 'title' => '长部·梵网经', 'category' => '经藏'],
  167. ];
  168. }
  169. private function mockActiveAuthors()
  170. {
  171. return [
  172. [
  173. 'name' => 'Bhikkhu Bodhi',
  174. 'avatar' => null,
  175. 'color' => '#2d5a8e',
  176. 'initials' => 'BB',
  177. 'count' => 24,
  178. ],
  179. [
  180. 'name' => 'Bhikkhu Sujato',
  181. 'avatar' => null,
  182. 'color' => '#5a2d8e',
  183. 'initials' => 'BS',
  184. 'count' => 18,
  185. ],
  186. [
  187. 'name' => 'Buddhaghosa',
  188. 'avatar' => null,
  189. 'color' => '#8e5a2d',
  190. 'initials' => 'BG',
  191. 'count' => 12,
  192. ],
  193. [
  194. 'name' => 'Bhikkhu Brahmali',
  195. 'avatar' => null,
  196. 'color' => '#2d8e5a',
  197. 'initials' => 'BR',
  198. 'count' => 9,
  199. ],
  200. ];
  201. }
  202. // ── 辅助:从书籍列表聚合作者选项(mock,真实实现替换) ─────────
  203. private function getAuthorOptions(array $books): array
  204. {
  205. // TODO: 从 $books 聚合真实作者列表
  206. return [
  207. ['value' => 'all', 'label' => '全部作者', 'count' => count($books)],
  208. ['value' => 'bhikkhu-bodhi', 'label' => 'Bhikkhu Bodhi', 'count' => 0],
  209. ['value' => 'bhikkhu-sujato', 'label' => 'Bhikkhu Sujato', 'count' => 0],
  210. ['value' => 'buddhaghosa', 'label' => 'Buddhaghosa', 'count' => 0],
  211. ['value' => 'bhikkhu-brahmali', 'label' => 'Bhikkhu Brahmali', 'count' => 0],
  212. ];
  213. }
  214. private function types()
  215. {
  216. return [
  217. ['id' => '1', 'name' => 'sutta'],
  218. ['id' => '48', 'name' => 'vinaya'],
  219. ['id' => '66', 'name' => 'abhidhamma'],
  220. ['id' => '82', 'name' => 'añña']
  221. ];
  222. }
  223. private function subCategories($categories, int $id)
  224. {
  225. return array_filter($categories, function ($cat) use ($id) {
  226. return $cat['parent_id'] == $id;
  227. });
  228. }
  229. private function getBooksIdInCat(array $categories, ?string $id)
  230. {
  231. if ($id) {
  232. $currentCategory = collect($categories)->firstWhere('id', $id);
  233. if (!$currentCategory) {
  234. abort(404);
  235. }
  236. // 标签查章节
  237. $tagNames = $currentCategory['tag'];
  238. $booksChapter = PaliText::withAllTags($tagNames)
  239. ->where('level', 1)->get();
  240. } else {
  241. $booksChapter = PaliText::select(['book', 'paragraph'])
  242. ->where('level', 1)
  243. ->get();
  244. }
  245. $chapters = [];
  246. foreach ($booksChapter as $key => $value) {
  247. $chapters[] = [$value->book, $value->paragraph];
  248. }
  249. return $chapters;
  250. }
  251. private function getPaliBooks(array $categories, string $id)
  252. {
  253. $chapters = $this->getBooksIdInCat($categories, $id);
  254. $books = PaliText::whereIns(['book', 'paragraph'], $chapters)->get();
  255. return $books;
  256. }
  257. private function getBooks(array $categories, ?string $id, array $filters)
  258. {
  259. //根据分类获取书号
  260. if (isset($filters['book'])) {
  261. $chapters = [explode('-', $filters['book'])];
  262. } else {
  263. $chapters = $this->getBooksIdInCat($categories, $id);
  264. }
  265. $table = ProgressChapter::with('channel.owner')
  266. ->whereHas('channel', function ($query) use ($filters) {
  267. $query->where('status', 30);
  268. if ($filters['type'] !== 'all') {
  269. $query->where('type', $filters['type']);
  270. }
  271. if ($filters['lang'] !== 'all') {
  272. $query->where('lang', $filters['lang']);
  273. }
  274. })
  275. ->whereNotNull('last_chapter_completed_at')
  276. ->whereIns(['book', 'para'], $chapters);
  277. if ($filters['sort'] === 'new') {
  278. $table = $table->orderBy('last_chapter_completed_at', 'desc');
  279. } else if ($filters['sort'] === 'progress') {
  280. $table = $table->orderBy('progress', 'desc');
  281. }
  282. $books = $table->take(100)->get();
  283. return $this->getBooksInfo($books);
  284. }
  285. private function getBooksInfo(mixed $books)
  286. {
  287. $pali = PaliText::where('level', 1)->get();
  288. // 获取该分类下的书籍
  289. $categoryBooks = [];
  290. $books->each(function ($book) use (&$categoryBooks, $pali) {
  291. $title = $book->title;
  292. if (empty($title)) {
  293. $title = $pali->firstWhere('book', $book->book)->toc;
  294. }
  295. //Log::debug('getBooksInfo', ['book' => $book->book, 'paragraph' => $book->para]);
  296. $pcd_book_id = $pali->first(function ($item) use ($book) {
  297. return $item->book == $book->book
  298. && $item->paragraph == $book->para;
  299. })?->pcd_book_id;
  300. $coverFile = "/assets/images/cover/zh-hans/1/{$pcd_book_id}.png";
  301. if (File::exists(public_path($coverFile))) {
  302. $coverUrl = $coverFile;
  303. } else {
  304. $coverUrl = null;
  305. }
  306. $colorIdx = $this->colorIndex($book->uid);
  307. $categoryBooks[] = [
  308. "id" => $book->uid,
  309. "title" => $title,
  310. "author" => $book->channel->name,
  311. "publisher" => $book->channel->owner,
  312. 'completed_chapters' => $book->completed_chapters,
  313. "type" => __('labels.' . $book->channel->type),
  314. "cover" => $coverUrl,
  315. 'cover_gradient' => $this->coverGradients[$colorIdx % count($this->coverGradients)],
  316. "description" => $book->summary ?? "比库戒律的详细说明",
  317. "language" => __('language.' . $book->channel->lang),
  318. ];
  319. });
  320. return $categoryBooks;
  321. }
  322. private function loadCategories()
  323. {
  324. $json = file_get_contents(public_path("data/category/default.json"));
  325. $tree = json_decode($json, true);
  326. $flat = self::flattenWithIds($tree);
  327. return $flat;
  328. }
  329. public static function flattenWithIds(array $tree, int $parentId = 0, int $level = 1): array
  330. {
  331. $flat = [];
  332. foreach ($tree as $node) {
  333. $currentId = self::$nextId++;
  334. $item = [
  335. 'id' => $currentId,
  336. 'parent_id' => $parentId,
  337. 'name' => $node['name'] ?? null,
  338. 'tag' => $node['tag'] ?? [],
  339. "description" => "佛教戒律经典",
  340. 'level' => $level,
  341. ];
  342. $flat[] = $item;
  343. if (isset($node['children']) && is_array($node['children'])) {
  344. $childrenLevel = $level + 1;
  345. $flat = array_merge($flat, self::flattenWithIds($node['children'], $currentId, $childrenLevel));
  346. }
  347. }
  348. return $flat;
  349. }
  350. private function getBreadcrumbs($category, $categories)
  351. {
  352. $breadcrumbs = [];
  353. $current = $category;
  354. while ($current) {
  355. array_unshift($breadcrumbs, $current);
  356. $current = collect($categories)->firstWhere('id', $current['parent_id']);
  357. }
  358. return $breadcrumbs;
  359. }
  360. }