TipitakaController.php 13 KB

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