TipitakaController.php 15 KB

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