KnowledgePointTreeController.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. public function index(Request $request): JsonResponse
  18. {
  19. try {
  20. // 使用缓存避免重复查询
  21. $cacheKey = 'knowledge-point-tree-' . md5($request->getQueryString() ?? '');
  22. $treeData = Cache::remember($cacheKey, 3600, function () {
  23. return $this->buildTreeFromDatabase();
  24. });
  25. return response()->json([
  26. 'success' => true,
  27. 'data' => $treeData,
  28. ]);
  29. } catch (\Exception $e) {
  30. Log::error('获取知识点树形结构失败', [
  31. 'error' => $e->getMessage(),
  32. 'trace' => $e->getTraceAsString(),
  33. ]);
  34. return response()->json([
  35. 'success' => false,
  36. 'message' => '获取知识点数据失败:' . $e->getMessage(),
  37. 'data' => [],
  38. ], 500);
  39. }
  40. }
  41. /**
  42. * 从数据库构建树形结构
  43. *
  44. * @return array
  45. */
  46. private function buildTreeFromDatabase(): array
  47. {
  48. // 从数据库获取所有知识点
  49. $knowledgePoints = KnowledgePoint::query()
  50. ->orderBy('kp_code')
  51. ->get()
  52. ->toArray();
  53. if (empty($knowledgePoints)) {
  54. Log::warning('数据库中没有找到知识点数据');
  55. return [];
  56. }
  57. // 构建节点映射(以 kp_code 为键)
  58. $nodesMap = [];
  59. foreach ($knowledgePoints as $point) {
  60. $kpCode = $point['kp_code'];
  61. $nodesMap[$kpCode] = [
  62. 'id' => $kpCode,
  63. 'label' => $point['name'] ?? $kpCode,
  64. 'children' => [],
  65. // 可选字段:如果数据库中有相关数据则添加
  66. 'skills' => $this->extractSkills($point),
  67. 'direct_score' => $this->extractDirectScore($point),
  68. 'related_score' => $this->extractRelatedScore($point),
  69. // 保留原始数据用于调试
  70. '_raw' => $point,
  71. ];
  72. }
  73. // 构建树形结构
  74. $rootNodes = [];
  75. foreach ($nodesMap as $kpCode => &$node) {
  76. $parentKpCode = $this->getParentKpCode($node['_raw']);
  77. // 如果没有父节点,则为根节点
  78. if (empty($parentKpCode) || !isset($nodesMap[$parentKpCode])) {
  79. $rootNodes[] = &$node;
  80. } else {
  81. // 添加到父节点的 children 中
  82. $nodesMap[$parentKpCode]['children'][] = &$node;
  83. }
  84. }
  85. // 清理临时数据
  86. foreach ($nodesMap as &$node) {
  87. unset($node['_raw']);
  88. }
  89. Log::info('成功构建知识点树形结构', [
  90. 'total_nodes' => count($knowledgePoints),
  91. 'root_nodes' => count($rootNodes),
  92. ]);
  93. return $rootNodes;
  94. }
  95. /**
  96. * 提取技能点信息
  97. *
  98. * @param array $point
  99. * @return array
  100. */
  101. private function extractSkills(array $point): array
  102. {
  103. // 如果数据库中有 skills 字段,直接返回
  104. if (isset($point['skills']) && is_array($point['skills'])) {
  105. return $point['skills'];
  106. }
  107. // 否则返回空数组
  108. return [];
  109. }
  110. /**
  111. * 提取直接得分范围
  112. *
  113. * @param array $point
  114. * @return array
  115. */
  116. private function extractDirectScore(array $point): array
  117. {
  118. // 如果数据库中有 direct_score 字段,直接返回
  119. if (isset($point['direct_score']) && is_array($point['direct_score'])) {
  120. return $point['direct_score'];
  121. }
  122. // 从 stats 字段提取(如果存在)
  123. if (isset($point['stats']) && is_array($point['stats'])) {
  124. if (isset($point['stats']['direct_score'])) {
  125. return (array) $point['stats']['direct_score'];
  126. }
  127. }
  128. // 默认值
  129. return [1, 3];
  130. }
  131. /**
  132. * 提取相关得分范围
  133. *
  134. * @param array $point
  135. * @return array
  136. */
  137. private function extractRelatedScore(array $point): array
  138. {
  139. // 如果数据库中有 related_score 字段,直接返回
  140. if (isset($point['related_score']) && is_array($point['related_score'])) {
  141. return $point['related_score'];
  142. }
  143. // 从 stats 字段提取(如果存在)
  144. if (isset($point['stats']) && is_array($point['stats'])) {
  145. if (isset($point['stats']['related_score'])) {
  146. return (array) $point['stats']['related_score'];
  147. }
  148. }
  149. // 默认值
  150. return [2, 5];
  151. }
  152. /**
  153. * 获取父知识点代码
  154. *
  155. * @param array $point
  156. * @return string|null
  157. */
  158. private function getParentKpCode(array $point): ?string
  159. {
  160. // 直接从 parent_kp_code 字段获取
  161. if (!empty($point['parent_kp_code'])) {
  162. return $point['parent_kp_code'];
  163. }
  164. // 如果没有 parent_kp_code,尝试从 kp_code 推断
  165. // 例如:R01 的父节点可能是 S01,M01 的父节点可能是 M00
  166. $kpCode = $point['kp_code'] ?? '';
  167. if (empty($kpCode)) {
  168. return null;
  169. }
  170. // 尝试从编码规则推断父节点
  171. // M01 -> M00, S01 -> M01, R01 -> S01 等
  172. if (preg_match('/^([A-Z]+)\d+$/', $kpCode, $matches)) {
  173. $prefix = $matches[1];
  174. $number = (int) substr($kpCode, strlen($prefix));
  175. if ($number > 0) {
  176. // 降级:R01 -> S01 (去掉一位数字)
  177. $parentNumber = (int) (substr($kpCode, strlen($prefix), -1));
  178. if ($parentNumber > 0) {
  179. return $prefix . str_pad($parentNumber, strlen($kpCode) - strlen($prefix), '0', STR_PAD_LEFT);
  180. }
  181. }
  182. }
  183. return null;
  184. }
  185. }