TipitakaController.php 16 KB

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