TipitakaController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. $allNames = array_map(fn($item) => $item['name'], $subCategories);
  68. // 去重
  69. $allNames = array_values(array_unique($allNames));
  70. // 查词典
  71. $terms = $this->termService->glossaryByLemma($allNames, $locale);
  72. // 构建映射
  73. $termMap = [];
  74. if ($terms) {
  75. foreach ($terms as $term) {
  76. $termMap[$term->word] = $term->meaning;
  77. }
  78. }
  79. // 回填
  80. foreach ($subCategories as $key => $cat) {
  81. $name = $cat['name'] ?? null;
  82. $subCategories[$key]['name'] = $termMap[$name] ?? $name;
  83. }
  84. // ── 过滤参数 ────────────────────────────────────────────
  85. $selectedType = request('type', 'all');
  86. $selectedLang = request('lang', 'all');
  87. $selectedAuthor = request('author', 'all');
  88. $selectedSort = request('sort', 'new');
  89. $sortList = [
  90. ['key' => 'new', 'label' => '最新',],
  91. ['key' => 'progress', 'label' => '完成度',],
  92. ];
  93. $selected = [
  94. 'type' => $selectedType,
  95. 'lang' => $selectedLang,
  96. 'author' => $selectedAuthor,
  97. 'sort' => $selectedSort,
  98. ];
  99. // ── 书籍列表(过滤+排序,真实实现替换此处) ──────────────
  100. $categoryBooks = $this->getBooks($categories, $id, $selected);
  101. $totalCount = count($categoryBooks);
  102. // ── 过滤器选项(mock,真实实现从书籍数据聚合) ────────────
  103. $filterOptions = [
  104. 'types' => $this->filterTypes(),
  105. 'languages' => $this->filterLanguages(),
  106. 'authors' => $this->getAuthorOptions($categoryBooks),
  107. ];
  108. // ── 右边栏:本周推荐(mock) ────────────────────────────
  109. $recommended = $this->mockRecommended();
  110. // ── 右边栏:活跃译者(mock) ────────────────────────────
  111. $activeAuthors = $this->mockActiveAuthors();
  112. $types = $this->types();
  113. return view('library.tipitaka.category', compact(
  114. 'currentCategory',
  115. 'subCategories',
  116. 'categoryBooks',
  117. 'breadcrumbs',
  118. 'types',
  119. 'selected',
  120. 'filterOptions',
  121. 'totalCount',
  122. 'recommended',
  123. 'activeAuthors',
  124. 'sortList'
  125. ));
  126. }
  127. private function filterLanguages()
  128. {
  129. return [
  130. ['value' => 'all', 'label' => '全部', 'count' => 0],
  131. ['value' => 'zh-Hans', 'label' => '简体中文', 'count' => 0],
  132. ['value' => 'zh-Hant', 'label' => '繁体中文', 'count' => 0],
  133. ['value' => 'pi', 'label' => '巴利语', 'count' => 0],
  134. ['value' => 'en', 'label' => '英语', 'count' => 0],
  135. ];
  136. }
  137. private function filterTypes()
  138. {
  139. return [
  140. ['value' => 'all', 'label' => '全部', 'count' => 0],
  141. ['value' => 'original', 'label' => '原文', 'count' => 0],
  142. ['value' => 'translation', 'label' => '译文', 'count' => 0],
  143. ['value' => 'nissaya', 'label' => 'Nissaya', 'count' => 0],
  144. ];
  145. }
  146. private function mockRecommended()
  147. {
  148. return [
  149. ['id' => 1, 'title' => '相应部·因缘篇', 'category' => '经藏'],
  150. ['id' => 2, 'title' => '法句经', 'category' => '经藏'],
  151. ['id' => 3, 'title' => '清净道论', 'category' => '注释'],
  152. ['id' => 4, 'title' => '律藏·波罗夷', 'category' => '律藏'],
  153. ['id' => 5, 'title' => '长部·梵网经', 'category' => '经藏'],
  154. ];
  155. }
  156. private function mockActiveAuthors()
  157. {
  158. return [
  159. [
  160. 'name' => 'Bhikkhu Bodhi',
  161. 'avatar' => null,
  162. 'color' => '#2d5a8e',
  163. 'initials' => 'BB',
  164. 'count' => 24,
  165. ],
  166. [
  167. 'name' => 'Bhikkhu Sujato',
  168. 'avatar' => null,
  169. 'color' => '#5a2d8e',
  170. 'initials' => 'BS',
  171. 'count' => 18,
  172. ],
  173. [
  174. 'name' => 'Buddhaghosa',
  175. 'avatar' => null,
  176. 'color' => '#8e5a2d',
  177. 'initials' => 'BG',
  178. 'count' => 12,
  179. ],
  180. [
  181. 'name' => 'Bhikkhu Brahmali',
  182. 'avatar' => null,
  183. 'color' => '#2d8e5a',
  184. 'initials' => 'BR',
  185. 'count' => 9,
  186. ],
  187. ];
  188. }
  189. // ── 辅助:从书籍列表聚合作者选项(mock,真实实现替换) ─────────
  190. private function getAuthorOptions(array $books): array
  191. {
  192. // TODO: 从 $books 聚合真实作者列表
  193. return [
  194. ['value' => 'all', 'label' => '全部作者', 'count' => count($books)],
  195. ['value' => 'bhikkhu-bodhi', 'label' => 'Bhikkhu Bodhi', 'count' => 0],
  196. ['value' => 'bhikkhu-sujato', 'label' => 'Bhikkhu Sujato', 'count' => 0],
  197. ['value' => 'buddhaghosa', 'label' => 'Buddhaghosa', 'count' => 0],
  198. ['value' => 'bhikkhu-brahmali', 'label' => 'Bhikkhu Brahmali', 'count' => 0],
  199. ];
  200. }
  201. private function types()
  202. {
  203. return [
  204. ['id' => '1', 'name' => 'sutta'],
  205. ['id' => '48', 'name' => 'vinaya'],
  206. ['id' => '66', 'name' => 'abhidhamma'],
  207. ['id' => '82', 'name' => 'añña']
  208. ];
  209. }
  210. private function subCategories($categories, int $id)
  211. {
  212. return array_filter($categories, function ($cat) use ($id) {
  213. return $cat['parent_id'] == $id;
  214. });
  215. }
  216. private function getBooksIdInCat(array $categories, ?string $id)
  217. {
  218. if ($id) {
  219. $currentCategory = collect($categories)->firstWhere('id', $id);
  220. if (!$currentCategory) {
  221. abort(404);
  222. }
  223. // 标签查章节
  224. $tagNames = $currentCategory['tag'];
  225. $booksChapter = PaliText::withAllTags($tagNames)
  226. ->where('level', 1)->get();
  227. } else {
  228. $booksChapter = PaliText::select(['book', 'paragraph'])
  229. ->where('level', 1)
  230. ->get();
  231. }
  232. $chapters = [];
  233. foreach ($booksChapter as $key => $value) {
  234. $chapters[] = [$value->book, $value->paragraph];
  235. }
  236. return $chapters;
  237. }
  238. private function getBooks(array $categories, ?string $id, array $filters)
  239. {
  240. //根据分类获取书号
  241. $chapters = $this->getBooksIdInCat($categories, $id);
  242. $table = ProgressChapter::with('channel.owner')
  243. ->whereHas('channel', function ($query) use ($filters) {
  244. $query->where('status', 30);
  245. if ($filters['type'] !== 'all') {
  246. $query->where('type', $filters['type']);
  247. }
  248. if ($filters['lang'] !== 'all') {
  249. $query->where('lang', $filters['lang']);
  250. }
  251. })
  252. ->whereNotNull('last_chapter_completed_at')
  253. ->whereIns(['book', 'para'], $chapters);
  254. if ($filters['sort'] === 'new') {
  255. $table = $table->orderBy('last_chapter_completed_at', 'desc');
  256. } else if ($filters['sort'] === 'progress') {
  257. $table = $table->orderBy('progress', 'desc');
  258. }
  259. $books = $table->take(100)->get();
  260. return $this->getBooksInfo($books);
  261. }
  262. private function getBooksInfo(mixed $books)
  263. {
  264. $pali = PaliText::where('level', 1)->get();
  265. // 获取该分类下的书籍
  266. $categoryBooks = [];
  267. $books->each(function ($book) use (&$categoryBooks, $pali) {
  268. $title = $book->title;
  269. if (empty($title)) {
  270. $title = $pali->firstWhere('book', $book->book)->toc;
  271. }
  272. //Log::debug('getBooksInfo', ['book' => $book->book, 'paragraph' => $book->para]);
  273. $pcd_book_id = $pali->first(function ($item) use ($book) {
  274. return $item->book == $book->book
  275. && $item->paragraph == $book->para;
  276. })?->pcd_book_id;
  277. $coverFile = "/assets/images/cover/zh-hans/1/{$pcd_book_id}.png";
  278. if (File::exists(public_path($coverFile))) {
  279. $coverUrl = $coverFile;
  280. } else {
  281. $coverUrl = null;
  282. }
  283. $colorIdx = $this->colorIndex($book->uid);
  284. $categoryBooks[] = [
  285. "id" => $book->uid,
  286. "title" => $title,
  287. "author" => $book->channel->name,
  288. "publisher" => $book->channel->owner,
  289. 'completed_chapters' => $book->completed_chapters,
  290. "type" => __('labels.' . $book->channel->type),
  291. "cover" => $coverUrl,
  292. 'cover_gradient' => $this->coverGradients[$colorIdx % count($this->coverGradients)],
  293. "description" => $book->summary ?? "比库戒律的详细说明",
  294. "language" => __('language.' . $book->channel->lang),
  295. ];
  296. });
  297. return $categoryBooks;
  298. }
  299. private function loadCategories()
  300. {
  301. $json = file_get_contents(public_path("data/category/default.json"));
  302. $tree = json_decode($json, true);
  303. $flat = self::flattenWithIds($tree);
  304. return $flat;
  305. }
  306. public static function flattenWithIds(array $tree, int $parentId = 0, int $level = 1): array
  307. {
  308. $flat = [];
  309. foreach ($tree as $node) {
  310. $currentId = self::$nextId++;
  311. $item = [
  312. 'id' => $currentId,
  313. 'parent_id' => $parentId,
  314. 'name' => $node['name'] ?? null,
  315. 'tag' => $node['tag'] ?? [],
  316. "description" => "佛教戒律经典",
  317. 'level' => $level,
  318. ];
  319. $flat[] = $item;
  320. if (isset($node['children']) && is_array($node['children'])) {
  321. $childrenLevel = $level + 1;
  322. $flat = array_merge($flat, self::flattenWithIds($node['children'], $currentId, $childrenLevel));
  323. }
  324. }
  325. return $flat;
  326. }
  327. private function getBreadcrumbs($category, $categories)
  328. {
  329. $breadcrumbs = [];
  330. $current = $category;
  331. while ($current) {
  332. array_unshift($breadcrumbs, $current);
  333. $current = collect($categories)->firstWhere('id', $current['parent_id']);
  334. }
  335. return $breadcrumbs;
  336. }
  337. }