TipitakaController.php 13 KB

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