KnowledgePointTreeController.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Models\KnowledgePoint;
  4. use Illuminate\Http\JsonResponse;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Log;
  7. use Illuminate\Support\Facades\Cache;
  8. class KnowledgePointTreeController
  9. {
  10. /**
  11. * 获取知识点树形结构
  12. * 从 MySQL 数据库读取数据,构建层级结构
  13. *
  14. * @param Request $request
  15. * @return JsonResponse
  16. *
  17. * 支持参数:
  18. * - stage: 学段筛选(primary=小学1-6, junior=初中7-9, senior=高中10-12)
  19. */
  20. public function index(Request $request): JsonResponse
  21. {
  22. try {
  23. // 获取学段参数
  24. $stage = $request->input('stage');
  25. // 验证学段参数
  26. if ($stage && !in_array($stage, ['primary', 'junior', 'senior'])) {
  27. return response()->json([
  28. 'success' => false,
  29. 'message' => '无效的学段参数,可选值:primary(小学)、junior(初中)、senior(高中)',
  30. 'data' => [],
  31. ], 400);
  32. }
  33. // 使用缓存避免重复查询(缓存 key 包含 stage 参数)
  34. $cacheKey = 'knowledge-point-tree-' . ($stage ?? 'all') . '-' . md5($request->getQueryString() ?? '');
  35. $treeData = Cache::remember($cacheKey, 3600, function () use ($stage) {
  36. return $this->buildTreeFromDatabase($stage);
  37. });
  38. return response()->json([
  39. 'success' => true,
  40. 'data' => $treeData,
  41. 'meta' => [
  42. 'stage' => $stage,
  43. 'stage_label' => $this->getStageLabel($stage),
  44. ],
  45. ]);
  46. } catch (\Exception $e) {
  47. Log::error('获取知识点树形结构失败', [
  48. 'error' => $e->getMessage(),
  49. 'trace' => $e->getTraceAsString(),
  50. ]);
  51. return response()->json([
  52. 'success' => false,
  53. 'message' => '获取知识点数据失败:' . $e->getMessage(),
  54. 'data' => [],
  55. ], 500);
  56. }
  57. }
  58. /**
  59. * 获取学段中文标签
  60. */
  61. private function getStageLabel(?string $stage): ?string
  62. {
  63. return match ($stage) {
  64. 'primary' => '小学',
  65. 'junior' => '初中',
  66. 'senior' => '高中',
  67. default => null,
  68. };
  69. }
  70. /**
  71. * 从数据库构建树形结构
  72. *
  73. * @param string|null $stage 学段筛选:primary(小学)、junior(初中)、senior(高中)
  74. * @return array
  75. */
  76. private function buildTreeFromDatabase(?string $stage = null): array
  77. {
  78. // 从数据库获取知识点
  79. $query = KnowledgePoint::query();
  80. // 根据学段筛选(grade 字段存储的是中文,如 "初中,高中,小学")
  81. if ($stage) {
  82. $stageLabel = match ($stage) {
  83. 'primary' => '小学',
  84. 'junior' => '初中',
  85. 'senior' => '高中',
  86. default => null,
  87. };
  88. if ($stageLabel) {
  89. $query->where('grade', 'like', '%' . $stageLabel . '%');
  90. Log::info('知识点按学段筛选', [
  91. 'stage' => $stage,
  92. 'stage_label' => $stageLabel,
  93. ]);
  94. }
  95. }
  96. $knowledgePoints = $query->orderBy('kp_code')
  97. ->get()
  98. ->toArray();
  99. if (empty($knowledgePoints)) {
  100. Log::warning('数据库中没有找到知识点数据');
  101. return [];
  102. }
  103. // 构建节点映射(以 kp_code 为键)
  104. $nodesMap = [];
  105. foreach ($knowledgePoints as $point) {
  106. $kpCode = $point['kp_code'];
  107. $nodesMap[$kpCode] = [
  108. 'id' => $kpCode,
  109. 'label' => $point['name'] ?? $kpCode,
  110. 'children' => [],
  111. // 可选字段:如果数据库中有相关数据则添加
  112. 'skills' => $this->extractSkills($point),
  113. 'direct_score' => $this->extractDirectScore($point),
  114. 'related_score' => $this->extractRelatedScore($point),
  115. // 保留原始数据用于调试
  116. '_raw' => $point,
  117. ];
  118. }
  119. // 构建树形结构
  120. $rootNodes = [];
  121. foreach ($nodesMap as $kpCode => &$node) {
  122. $parentKpCode = $this->getParentKpCode($node['_raw']);
  123. // 如果没有父节点,则为根节点
  124. if (empty($parentKpCode) || !isset($nodesMap[$parentKpCode])) {
  125. $rootNodes[] = &$node;
  126. } else {
  127. // 添加到父节点的 children 中
  128. $nodesMap[$parentKpCode]['children'][] = &$node;
  129. }
  130. }
  131. // 清理临时数据
  132. foreach ($nodesMap as &$node) {
  133. unset($node['_raw']);
  134. }
  135. Log::info('成功构建知识点树形结构', [
  136. 'total_nodes' => count($knowledgePoints),
  137. 'root_nodes' => count($rootNodes),
  138. ]);
  139. return $rootNodes;
  140. }
  141. /**
  142. * 提取技能点信息
  143. *
  144. * @param array $point
  145. * @return array
  146. */
  147. private function extractSkills(array $point): array
  148. {
  149. // 如果数据库中有 skills 字段,直接返回
  150. if (isset($point['skills']) && is_array($point['skills'])) {
  151. return $point['skills'];
  152. }
  153. // 否则返回空数组
  154. return [];
  155. }
  156. /**
  157. * 提取直接得分范围
  158. *
  159. * @param array $point
  160. * @return array
  161. */
  162. private function extractDirectScore(array $point): array
  163. {
  164. // 如果数据库中有 direct_score 字段,直接返回
  165. if (isset($point['direct_score']) && is_array($point['direct_score'])) {
  166. return $point['direct_score'];
  167. }
  168. // 从 stats 字段提取(如果存在)
  169. if (isset($point['stats']) && is_array($point['stats'])) {
  170. if (isset($point['stats']['direct_score'])) {
  171. return (array) $point['stats']['direct_score'];
  172. }
  173. }
  174. // 默认值
  175. return [1, 3];
  176. }
  177. /**
  178. * 提取相关得分范围
  179. *
  180. * @param array $point
  181. * @return array
  182. */
  183. private function extractRelatedScore(array $point): array
  184. {
  185. // 如果数据库中有 related_score 字段,直接返回
  186. if (isset($point['related_score']) && is_array($point['related_score'])) {
  187. return $point['related_score'];
  188. }
  189. // 从 stats 字段提取(如果存在)
  190. if (isset($point['stats']) && is_array($point['stats'])) {
  191. if (isset($point['stats']['related_score'])) {
  192. return (array) $point['stats']['related_score'];
  193. }
  194. }
  195. // 默认值
  196. return [2, 5];
  197. }
  198. /**
  199. * 获取父知识点代码
  200. *
  201. * @param array $point
  202. * @return string|null
  203. */
  204. private function getParentKpCode(array $point): ?string
  205. {
  206. // 直接从 parent_kp_code 字段获取
  207. if (!empty($point['parent_kp_code'])) {
  208. return $point['parent_kp_code'];
  209. }
  210. // 如果没有 parent_kp_code,尝试从 kp_code 推断
  211. // 例如:R01 的父节点可能是 S01,M01 的父节点可能是 M00
  212. $kpCode = $point['kp_code'] ?? '';
  213. if (empty($kpCode)) {
  214. return null;
  215. }
  216. // 尝试从编码规则推断父节点
  217. // M01 -> M00, S01 -> M01, R01 -> S01 等
  218. if (preg_match('/^([A-Z]+)\d+$/', $kpCode, $matches)) {
  219. $prefix = $matches[1];
  220. $number = (int) substr($kpCode, strlen($prefix));
  221. if ($number > 0) {
  222. // 降级:R01 -> S01 (去掉一位数字)
  223. $parentNumber = (int) (substr($kpCode, strlen($prefix), -1));
  224. if ($parentNumber > 0) {
  225. return $prefix . str_pad($parentNumber, strlen($kpCode) - strlen($prefix), '0', STR_PAD_LEFT);
  226. }
  227. }
  228. }
  229. return null;
  230. }
  231. }