script.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. document.addEventListener('DOMContentLoaded', function () {
  2. // 获取DOM元素 - 计算器模块
  3. const calculateBtn = document.getElementById('calculate-btn');
  4. const solutionsContainer = document.getElementById('solutions');
  5. const statsContainer = document.getElementById('stats');
  6. // 获取DOM元素 - 一星数据模块
  7. const flag1MinInput = document.getElementById('flag1-min');
  8. const flag1SearchBtn = document.getElementById('flag1-search-btn');
  9. const flag1Table = document.getElementById('flag1-table');
  10. // 获取DOM元素 - 二星数据模块
  11. const flag2MinInput = document.getElementById('flag2-min');
  12. const flag2SearchBtn = document.getElementById('flag2-search-btn');
  13. const flag2Table = document.getElementById('flag2-table');
  14. // 获取DOM元素 - 历史记录模块
  15. const historyTypeSelect = document.getElementById('history-type');
  16. const historyStartDateInput = document.getElementById('history-start-date');
  17. const historyEndDateInput = document.getElementById('history-end-date');
  18. const historySearchBtn = document.getElementById('history-search-btn');
  19. const historyContainer = document.getElementById('history-container');
  20. const historyStats = document.getElementById('history-stats');
  21. // 获取DOM元素 - 我的收藏模块
  22. const favoriteContainer = document.getElementById('favorite-container');
  23. const favoriteStats = document.getElementById('favorite-stats');
  24. // 获取DOM元素 - 出题模块
  25. const problemContent = document.getElementById('problem-content');
  26. const problemAnswer = document.getElementById('problem-answer');
  27. const showAnswerBtn = document.getElementById('show-answer-btn');
  28. // 数字输入框
  29. const num1Input = document.getElementById('num1');
  30. const num2Input = document.getElementById('num2');
  31. const num3Input = document.getElementById('num3');
  32. const num4Input = document.getElementById('num4');
  33. // 限制输入范围为1-13
  34. [num1Input, num2Input, num3Input, num4Input].forEach(input => {
  35. input.addEventListener('input', function () {
  36. const value = parseInt(this.value);
  37. if (value < 1) this.value = 1;
  38. if (value > 13) this.value = 13;
  39. });
  40. });
  41. // 定义SVG图标
  42. const svgIcons = {
  43. star: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>`,
  44. starFilled: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>`,
  45. trash: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>`,
  46. eye: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>`,
  47. eyeOff: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>`
  48. };
  49. // 存储当前解法和问题数据
  50. let currentSolutions = [];
  51. let currentProblem = null;
  52. // 获取问题类型选择框和出题按钮
  53. const problemTypeSelect = document.getElementById('problem-type-select');
  54. const generateProblemBtn = document.getElementById('generate-problem-btn');
  55. // 为出题按钮添加点击事件
  56. generateProblemBtn.addEventListener('click', function () {
  57. const selectedType = problemTypeSelect.value;
  58. if (selectedType) {
  59. // 根据选择的类型生成题目
  60. generateProblem(selectedType);
  61. } else {
  62. // 如果没有选择类型,提示用户
  63. problemContent.innerHTML = '<p class="error">请先选择题目类型</p>';
  64. }
  65. });
  66. // 为显示答案按钮添加点击事件
  67. showAnswerBtn.addEventListener('click', function () {
  68. if (currentProblem && currentProblem.answers) {
  69. console.log('currentProblem:', currentProblem.answers)
  70. if (problemAnswer.style.display === 'block') {
  71. problemAnswer.style.display = 'none';
  72. showAnswerBtn.innerHTML = '显示答案';
  73. } else {
  74. problemAnswer.style.display = 'block';
  75. renderProblemAnswers(currentProblem.answers);
  76. showAnswerBtn.innerHTML = '隐藏答案';
  77. }
  78. }
  79. });
  80. // 初始化显示答案按钮图标
  81. if (showAnswerBtn) {
  82. showAnswerBtn.innerHTML = '显示答案';
  83. }
  84. // 为计算按钮添加点击事件
  85. calculateBtn.addEventListener('click', fetchSolutions);
  86. // 为历史记录查询按钮添加点击事件
  87. historySearchBtn.addEventListener('click', () => { fetchHistory(false) });
  88. // 添加滚动监听器,实现自动加载更多
  89. document.querySelector('.history-data-container').addEventListener('scroll', function () {
  90. const module5 = document.querySelector('.module-5');
  91. const module6 = document.querySelector('.module-6');
  92. // 检查历史记录模块是否可见
  93. if (module5.style.display === 'block') {
  94. const historyStatsRect = historyStats.getBoundingClientRect();
  95. if (historyStatsRect.top <= window.innerHeight && !isLoadingHistory && hasMoreHistory) {
  96. fetchHistory(true);
  97. }
  98. }
  99. // 检查收藏模块是否可见
  100. if (module6.style.display === 'block') {
  101. const favoriteStatsRect = favoriteStats.getBoundingClientRect();
  102. if (favoriteStatsRect.top <= window.innerHeight && !isLoadingFavorite && hasMoreFavorite) {
  103. fetchFavorites(true);
  104. }
  105. }
  106. });
  107. // 根据题型生成题目
  108. let answerTimer = null;
  109. let timerInterval = null;
  110. let timerSeconds = 0;
  111. let timerDisplay;
  112. async function generateProblem(type) {
  113. if (answerTimer) clearTimeout(answerTimer);
  114. if (timerInterval) clearInterval(timerInterval);
  115. // 重置问题和答案区域
  116. problemContent.innerHTML = '<p class="placeholder">正在生成题目,请稍候...</p>';
  117. problemAnswer.innerHTML = '';
  118. problemAnswer.style.display = 'none';
  119. showAnswerBtn.style.display = 'none';
  120. currentProblem = null;
  121. // 重置计时器
  122. timerSeconds = 0;
  123. try {
  124. // 调用API获取问题
  125. const response = await fetch(`/api/questions?t=${type}`);
  126. const data = await response.json();
  127. if (response.ok && data.question) {
  128. // 保存当前问题数据
  129. currentProblem = data;
  130. problemContent.dataset.id = currentProblem.record_id;
  131. // 显示问题内容
  132. problemContent.innerHTML = `<div class="problem-text">
  133. <div class="pre-container">
  134. <button type="button" class="icon-btn favorite-btn" title="添加收藏">${svgIcons.star}</button>
  135. <div class="timer-container">
  136. <span id="timer-display" class="timer-display">00:00</span>
  137. </div>
  138. </div>
  139. ${data.question}
  140. </div>`;
  141. // 如果有数字,显示数字
  142. if (data.numbers) {
  143. const numbersHTML = `
  144. <div class="problem-numbers">
  145. ${data.numbers.map(num => `<span class="problem-number">${num === null ? '?' : num}</span>`).join('')}
  146. </div>
  147. `;
  148. problemContent.innerHTML += numbersHTML;
  149. }
  150. timerDisplay = document.getElementById('timer-display');
  151. // 开始计时
  152. startTimer();
  153. // 显示答案按钮
  154. answerTimer = setTimeout(() => {
  155. showAnswerBtn.innerHTML = ' 显示答案';
  156. showAnswerBtn.style.display = 'block';
  157. }, 10 * 1000);
  158. } else {
  159. problemContent.innerHTML = `<p class="error">${data.detail || '获取题目失败'}</p>`;
  160. }
  161. } catch (error) {
  162. console.error('Error:', error);
  163. problemContent.innerHTML = '<p class="error">请求失败,请检查网络连接</p>';
  164. }
  165. // 为收藏按钮添加点击事件
  166. problemContent.querySelectorAll('.favorite-btn').forEach((btn, index) => {
  167. btn.addEventListener('click', async function () {
  168. const card = this.closest('.problem-content'), is_favorite = this.classList.contains('active');
  169. const recordId = card.dataset.id;
  170. try {
  171. const response = await fetch(`/api/history/${recordId}/favorite`, {
  172. method: 'POST'
  173. });
  174. if (response.ok) {
  175. if (is_favorite) {
  176. this.innerHTML = svgIcons.star;
  177. this.classList.remove('active');
  178. alert('取消成功');
  179. } else {
  180. this.innerHTML = svgIcons.starFilled;
  181. this.classList.add('active');
  182. alert('收藏成功');
  183. }
  184. } else {
  185. alert('收藏失败,请重试');
  186. }
  187. } catch (error) {
  188. console.error('收藏操作失败:', error);
  189. alert('收藏失败,请检查网络连接');
  190. }
  191. });
  192. });
  193. // 开始计时器
  194. function startTimer() {
  195. // 清除之前的计时器
  196. if (timerInterval) {
  197. clearInterval(timerInterval);
  198. }
  199. // 重置计时
  200. timerSeconds = 0;
  201. updateTimerDisplay();
  202. // 启动新的计时器
  203. timerInterval = setInterval(() => {
  204. timerSeconds++;
  205. if (timerSeconds > 130) {
  206. clearInterval(timerInterval);
  207. }
  208. updateTimerDisplay();
  209. }, 1000);
  210. }
  211. // 更新计时器显示
  212. function updateTimerDisplay() {
  213. if (timerDisplay) {
  214. if (timerSeconds >= 120) {
  215. timerDisplay.textContent = "时间到";
  216. timerDisplay.classList.add('time-up');
  217. } else {
  218. const minutes = Math.floor(timerSeconds / 60);
  219. const seconds = timerSeconds % 60;
  220. timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  221. timerDisplay.classList.remove('time-up');
  222. }
  223. }
  224. }
  225. }
  226. generateProblem(0)
  227. // 渲染问题答案
  228. function renderProblemAnswers(answers) {
  229. if (!answers || answers.length === 0) {
  230. problemAnswer.innerHTML = '<p class="placeholder">没有找到答案</p>';
  231. return;
  232. }
  233. // 根据答案类型渲染不同的内容
  234. if (Array.isArray(answers)) {
  235. // 如果是数组,渲染为列表
  236. const answersHTML = answers.map(answer => {
  237. if (typeof answer === 'object' && answer.expression) {
  238. // 如果是解法对象
  239. return `
  240. <div class="solution-item flag-${answer.flag || 0}">
  241. <div class="solution-expression">${answer.expression}</div>
  242. <div class="solution-flag flag-${answer.flag || 0}">
  243. ${answer.flag === 1 ? '★' : answer.flag === 2 ? '★★' : ''}
  244. </div>
  245. </div>
  246. `;
  247. } else {
  248. // 如果是普通文本
  249. return `<div class="answer-item">${answer}</div>`;
  250. }
  251. }).join('');
  252. problemAnswer.innerHTML = `
  253. <h3>答案</h3>
  254. <div class="answers-container">
  255. ${answersHTML}
  256. </div>
  257. `;
  258. } else if (typeof answers === 'object') {
  259. // 如果是单个对象
  260. const answerKeys = Object.keys(answers);
  261. const answersHTML = answerKeys.map(key => {
  262. return `
  263. <div class="answer-group">
  264. <div class="answer-key">${key}:</div>
  265. <div class="answer-value">${answers[key]}</div>
  266. </div>
  267. `;
  268. }).join('');
  269. problemAnswer.innerHTML = `
  270. <h3>答案</h3>
  271. <div class="answers-container">
  272. ${answersHTML}
  273. </div>
  274. `;
  275. } else {
  276. // 如果是单个值
  277. problemAnswer.innerHTML = `
  278. <h3>答案</h3>
  279. <div class="answers-container">
  280. <div class="answer-item">${answers}</div>
  281. </div>
  282. `;
  283. }
  284. }
  285. // 获取解法
  286. async function fetchSolutions() {
  287. // 获取输入值
  288. const num1 = parseInt(num1Input.value) || 1;
  289. const num2 = parseInt(num2Input.value) || 1;
  290. const num3 = parseInt(num3Input.value) || 1;
  291. const num4 = parseInt(num4Input.value) || 1;
  292. // 显示加载状态
  293. solutionsContainer.innerHTML = '<p class="placeholder">正在计算解法,请稍候...</p>';
  294. statsContainer.textContent = '';
  295. try {
  296. // 调用API
  297. const response = await fetch(`/api/solutions?num1=${num1}&num2=${num2}&num3=${num3}&num4=${num4}`);
  298. const data = await response.json();
  299. if (response.ok) {
  300. // 保存解法
  301. currentSolutions = data.solutions || [];
  302. // 显示统计信息
  303. if (currentSolutions.length > 0) {
  304. statsContainer.textContent = `共 ${data.count} 种解法(一星: ${data.flag1_count}, 二星: ${data.flag2_count})`;
  305. } else {
  306. statsContainer.textContent = '没有找到任何解法';
  307. }
  308. // 渲染解法
  309. renderSolutions();
  310. } else {
  311. // 显示错误信息
  312. solutionsContainer.innerHTML = `<p class="error">${data.detail || '没有找到解法'}</p>`;
  313. statsContainer.textContent = '';
  314. }
  315. } catch (error) {
  316. console.error('Error:', error);
  317. solutionsContainer.innerHTML = '<p class="error">请求失败,请检查网络连接</p>';
  318. statsContainer.textContent = '';
  319. }
  320. }
  321. // 渲染解法
  322. function renderSolutions() {
  323. // 如果没有解法
  324. if (!currentSolutions || currentSolutions.length === 0) {
  325. solutionsContainer.innerHTML = '<p class="placeholder">没有找到匹配的解法,请尝试其他数字组合</p>';
  326. return;
  327. }
  328. // 直接使用所有解法
  329. const filteredSolutions = currentSolutions;
  330. // 渲染解法列表
  331. const solutionsHTML = filteredSolutions.map(solution => {
  332. return `
  333. <div class="solution-item flag-${solution.flag}">
  334. <div class="solution-expression">${solution.expression}</div>
  335. <div class="solution-flag flag-${solution.flag}">
  336. ${solution.flag === 1 ? '★' : solution.flag === 2 ? '★★' : ''}
  337. </div>
  338. </div>
  339. `;
  340. }).join('');
  341. solutionsContainer.innerHTML = solutionsHTML;
  342. }
  343. // 为一星数据查询按钮添加点击事件
  344. flag1SearchBtn.addEventListener('click', async function () {
  345. const min = flag1MinInput.value || 1;
  346. await fetchFlagData(1, min, flag1Table);
  347. });
  348. // 为二星数据查询按钮添加点击事件
  349. flag2SearchBtn.addEventListener('click', async function () {
  350. const min = flag2MinInput.value || 1;
  351. await fetchFlagData(2, min, flag2Table);
  352. });
  353. // 获取一星/二星数据
  354. async function fetchFlagData(flag, min, tableElement) {
  355. // 显示加载状态
  356. tableElement.querySelector('tbody').innerHTML = '<tr><td colspan="2" class="placeholder">正在加载数据,请稍候...</td></tr>';
  357. try {
  358. // 调用API获取数据
  359. const response = await fetch(`/api/flag?flag=${flag}&min_num=${min}&max_num=`);
  360. const data = await response.json();
  361. if (response.ok && data.length > 0) {
  362. // 处理数据并按数字组合分组
  363. const groupedData = {};
  364. data.forEach(item => {
  365. // 创建数字组合的键
  366. const numbersKey = [item.n1, item.n2, item.n3, item.n4].sort((a, b) => a - b).join(',');
  367. // 如果这个数字组合不存在,创建一个新数组
  368. if (!groupedData[numbersKey]) {
  369. groupedData[numbersKey] = [];
  370. }
  371. // 添加解法到对应的数字组合
  372. item.s.forEach(solution => {
  373. groupedData[numbersKey].push({
  374. expression: solution.c,
  375. flag: solution.f
  376. });
  377. });
  378. });
  379. console.log(groupedData);
  380. // 渲染表格
  381. renderFlagTable(groupedData, tableElement, flag);
  382. } else {
  383. // 显示无数据信息
  384. tableElement.querySelector('tbody').innerHTML = '<tr><td colspan="2" class="placeholder">没有找到匹配的数据</td></tr>';
  385. }
  386. } catch (error) {
  387. console.error('Error:', error);
  388. tableElement.querySelector('tbody').innerHTML = '<tr><td colspan="2" class="error">请求失败,请检查网络连接</td></tr>';
  389. }
  390. }
  391. // 渲染一星/二星数据表格
  392. function renderFlagTable(groupedData, tableElement, currentFlag) {
  393. const tbody = tableElement.querySelector('tbody');
  394. tbody.innerHTML = '';
  395. // 遍历分组数据
  396. Object.entries(groupedData).forEach(([numbersKey, solutions]) => {
  397. const tr = document.createElement('tr');
  398. // 数字单元格
  399. const tdNumbers = document.createElement('td');
  400. tdNumbers.className = 'number-cell';
  401. tdNumbers.textContent = numbersKey;
  402. tr.appendChild(tdNumbers);
  403. // 表达式单元格
  404. const tdExpressions = document.createElement('td');
  405. tdExpressions.className = 'expressions-cell';
  406. const container = document.createElement('div');
  407. container.className = 'expression-container hidden';
  408. // 创建显示按钮
  409. const toggleBtn = document.createElement('button');
  410. toggleBtn.className = 'toggle-btn';
  411. toggleBtn.textContent = '查看答案';
  412. // 添加每个表达式
  413. solutions.forEach(solution => {
  414. // const expressionDiv = document.createElement('div');
  415. // expressionDiv.className = `expression-item flag-${solution.flag}`;
  416. // expressionDiv.textContent = solution.expression;
  417. const expressionDiv = document.createElement('div');
  418. expressionDiv.className = `expression-item flag-${solution.flag} `;
  419. expressionDiv.textContent = solution.expression;
  420. container.appendChild(expressionDiv);
  421. });
  422. tdExpressions.appendChild(container);
  423. // 按钮点击事件
  424. toggleBtn.addEventListener('click', () => {
  425. container.classList.remove('hidden');
  426. toggleBtn.remove();
  427. });
  428. tdExpressions.appendChild(toggleBtn);
  429. tr.appendChild(tdExpressions);
  430. tbody.appendChild(tr);
  431. });
  432. // 如果没有数据
  433. if (tbody.children.length === 0) {
  434. tbody.innerHTML = '<tr><td colspan="2" class="placeholder">没有找到匹配的数据</td></tr>';
  435. }
  436. }
  437. // 添加模块切换事件监听
  438. const moduleSelect = document.getElementById('module-select');
  439. moduleSelect.addEventListener('change', function () {
  440. document.querySelectorAll('.module-container').forEach(module => {
  441. module.style.display = 'none';
  442. });
  443. document.querySelector(`.module-` + this.value).style.display = 'block';
  444. // 切换到计算器模块时重置输入框
  445. if (this.value === '2') {
  446. [num1Input, num2Input, num3Input, num4Input].forEach(input => input.value = 1);
  447. solutionsContainer.innerHTML = '<p class="placeholder">请输入4个数字并点击"计算解法"按钮</p>';
  448. }
  449. // 切换到一星数据模块时加载数据
  450. if (this.value === '3' && flag1Table.querySelector('tbody tr td.placeholder')) {
  451. fetchFlagData(1, flag1MinInput.value, flag1Table);
  452. }
  453. // 切换到二星数据模块时加载数据
  454. if (this.value === '4' && flag2Table.querySelector('tbody tr td.placeholder')) {
  455. fetchFlagData(2, flag2MinInput.value, flag2Table);
  456. }
  457. // 切换到历史记录模块时加载数据
  458. if (this.value === '5' && historyContainer) {
  459. fetchHistory(false);
  460. }
  461. // 切换到我的收藏模块时加载数据
  462. if (this.value === '6' && favoriteContainer) {
  463. fetchFavorites(false);
  464. }
  465. });
  466. // 初始化默认显示模块
  467. document.querySelectorAll('.module-container').forEach(module => {
  468. module.style.display = module.classList.contains('module-1') ? 'block' : 'none';
  469. });
  470. // 历史记录相关变量
  471. let currentHistoryPage = 1;
  472. let isLoadingHistory = false;
  473. let hasMoreHistory = true;
  474. // 收藏记录相关变量
  475. let currentFavoritePage = 1;
  476. let isLoadingFavorite = false;
  477. let hasMoreFavorite = true;
  478. // 获取历史记录数据
  479. async function fetchHistory(loadMore = false) {
  480. if (isLoadingHistory) return;
  481. isLoadingHistory = true;
  482. historyStats.textContent = ''
  483. if (!loadMore) {
  484. currentHistoryPage = 1;
  485. hasMoreHistory = true;
  486. }
  487. try {
  488. // 构建查询参数
  489. const params = new URLSearchParams();
  490. if (historyTypeSelect.value) {
  491. params.append('game_type', historyTypeSelect.value);
  492. }
  493. if (historyStartDateInput.value) {
  494. params.append('start_date', historyStartDateInput.value);
  495. }
  496. if (historyEndDateInput.value) {
  497. params.append('end_date', historyEndDateInput.value);
  498. }
  499. params.append('page', currentHistoryPage.toString());
  500. params.append('page_size', '10');
  501. // 调用API获取历史记录
  502. const response = await fetch(`/api/history?${params.toString()}`);
  503. const data = await response.json();
  504. if (response.ok && data.history) {
  505. // 渲染历史记录
  506. renderHistoryData(data.history, historyContainer, loadMore, false);
  507. // 更新分页状态
  508. hasMoreHistory = currentHistoryPage < data.total_pages;
  509. const historyRecordsStats = document.querySelector('.history-records-stats span');
  510. historyRecordsStats.textContent = data.count
  511. // 如果成功加载,增加页码
  512. currentHistoryPage++;
  513. } else {
  514. throw new Error(data.detail || '获取历史记录失败');
  515. }
  516. } catch (error) {
  517. if (!loadMore) {
  518. historyContainer.innerHTML = `<div class="error">${error.message}</div>`;
  519. historyStats.textContent = '加载失败';
  520. } else {
  521. // 显示加载失败消息
  522. alert('加载更多历史记录失败: ' + error.message);
  523. }
  524. } finally {
  525. isLoadingHistory = false;
  526. }
  527. }
  528. // 获取收藏记录数据
  529. async function fetchFavorites(loadMore = false) {
  530. if (isLoadingFavorite) return;
  531. isLoadingFavorite = true;
  532. favoriteStats.textContent = ''
  533. // 如果不是加载更多,则重置状态
  534. if (!loadMore) {
  535. currentFavoritePage = 1;
  536. hasMoreFavorite = true;
  537. }
  538. try {
  539. // 构建查询参数
  540. const params = new URLSearchParams();
  541. params.append('page', currentFavoritePage);
  542. params.append('page_size', "10");
  543. params.append('only_favorite', "true");
  544. params.append('include_deleted', "false");
  545. // 调用API获取收藏记录
  546. const response = await fetch(`/api/history?${params.toString()}`);
  547. const data = await response.json();
  548. if (response.ok) {
  549. // 渲染历史记录
  550. renderHistoryData(data.history, favoriteContainer, loadMore, true);
  551. // 更新分页状态
  552. hasMoreFavorite = currentFavoritePage < data.total_pages;
  553. const favoriteRecordsStats = document.querySelector('.favorite-records-stats span');
  554. favoriteRecordsStats.textContent = data.count
  555. // 更新分页状态
  556. currentFavoritePage++;
  557. } else {
  558. if (!loadMore) {
  559. favoriteContainer.innerHTML = `<div class="error">${data.detail || '获取收藏记录失败'}</div>`;
  560. favoriteStats.textContent = '加载失败';
  561. }
  562. }
  563. } catch (error) {
  564. console.error('Error:', error);
  565. if (!loadMore) {
  566. favoriteContainer.innerHTML = '<div class="error">请求失败,请检查网络连接</div>';
  567. favoriteStats.textContent = '加载失败';
  568. }
  569. } finally {
  570. isLoadingFavorite = false;
  571. }
  572. }
  573. function renderHistoryData(historyItems, container, append = false, isFavorite = false) {
  574. if (!historyItems || historyItems.length === 0) {
  575. if (!append) {
  576. container.innerHTML = `<div class="placeholder">${isFavorite ? '暂无收藏记录' : '没有找到历史记录'}</div>`;
  577. }
  578. return;
  579. }
  580. // 构建卡片内容
  581. let cardsHTML = ``;
  582. historyItems.forEach(item => {
  583. // 格式化日期时间
  584. const date = new Date(item.created_at);
  585. const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  586. // 获取操作类型的中文名称
  587. const type_names = {
  588. "A": "推理未知数",
  589. "B": "一题多解1",
  590. "C": "一题多解2",
  591. "D": "一星题目",
  592. "E": "二星题目"
  593. };
  594. let typeText = type_names[item.game_type] || item.game_type || '未知类型';
  595. let typeClass = `type-${(item.game_type || '').toLowerCase()}`;
  596. if (!type_names[item.game_type]) {
  597. typeClass = 'type-unknown';
  598. }
  599. // 解析答案数据
  600. let answers = null;
  601. try {
  602. // 尝试解析JSON字符串
  603. if (item.answers && typeof item.answers === 'string') {
  604. const jsonString = item.answers.replace(/'/g, '"');
  605. answers = JSON.parse(jsonString);
  606. } else if (item.answers) {
  607. answers = item.answers;
  608. }
  609. } catch (e) {
  610. // 如果解析失败,直接使用原始字符串
  611. answers = item.answers;
  612. }
  613. // 构建卡片HTML
  614. cardsHTML += `
  615. <div class="history-card ${typeClass}" data-id="${item.id}">
  616. <div class="history-card-header">
  617. <span class="history-card-type">${typeText}</span>
  618. <div class="history-card-actions">
  619. <button type="button" class="icon-btn show-history-answer-btn" title="显示答案">${svgIcons.eye}</button>
  620. ${item.is_favorite ? `<button type="button" class="icon-btn favorite-btn active" title="取消收藏">${svgIcons.starFilled}</button>` : `<button type="button" class="icon-btn favorite-btn" title="添加收藏">${svgIcons.star}</button>`}
  621. ${item.is_deleted ? `<button type="button" class="icon-btn delete-btn active" title="恢复">${svgIcons.trash}</button>` : isFavorite ? '' : `<button class="icon-btn delete-btn" title="删除">${svgIcons.trash}</button>`}
  622. </div>
  623. <span class="history-card-time">${formattedDate}</span>
  624. </div>
  625. <div class="history-card-content">
  626. <div class="problem-text">${item.question || ''}</div>
  627. ${item.numbers ? `<div class="problem-numbers">
  628. ${item.numbers.split(',').map(num => `<span class="problem-number">${num.trim() === 'None' ? "?" : num.trim()}</span>`).join('')}
  629. </div>` : ''}
  630. </div>
  631. <div class="history-card-answers" style="display: none;">
  632. ${renderHistoryAnswers(answers)}
  633. </div>
  634. </div>
  635. `;
  636. });
  637. // 如果是追加模式,则添加到现有内容后面
  638. if (append) {
  639. container.innerHTML += cardsHTML;
  640. } else {
  641. container.innerHTML = cardsHTML;
  642. }
  643. // 为所有显示答案按钮添加点击事件
  644. container.querySelectorAll('.show-history-answer-btn').forEach((btn, index) => {
  645. btn.addEventListener('click', function () {
  646. const card = this.closest('.history-card');
  647. const answersContainer = card.querySelector('.history-card-answers');
  648. if (answersContainer.style.display === 'block') {
  649. // 隐藏答案
  650. answersContainer.style.display = 'none';
  651. this.innerHTML = svgIcons.eye;
  652. this.title = '显示答案';
  653. } else {
  654. // 显示答案
  655. answersContainer.style.display = 'block';
  656. this.innerHTML = svgIcons.eyeOff;
  657. this.title = '隐藏答案';
  658. }
  659. });
  660. });
  661. // 为收藏按钮添加点击事件
  662. container.querySelectorAll('.favorite-btn').forEach((btn, index) => {
  663. btn.addEventListener('click', async function () {
  664. const card = this.closest('.history-card'), is_favorite = this.classList.contains('active');
  665. const recordId = card.dataset.id;
  666. try {
  667. const response = await fetch(`/api/history/${recordId}/favorite`, {
  668. method: 'POST'
  669. });
  670. if (response.ok) {
  671. if (is_favorite) {
  672. this.innerHTML = svgIcons.star;
  673. this.title = '未收藏';
  674. this.classList.remove('active');
  675. if (isFavorite) {
  676. card.remove();
  677. // 如果没有卡片了,显示空提示
  678. if (container.querySelectorAll('.history-card').length === 0) {
  679. container.innerHTML = '<div class="placeholder">暂无记录</div>';
  680. }
  681. }
  682. alert('取消成功');
  683. } else {
  684. this.innerHTML = svgIcons.starFilled;
  685. this.title = '已收藏';
  686. this.classList.add('active');
  687. alert('收藏成功');
  688. }
  689. } else {
  690. alert('收藏失败,请重试');
  691. }
  692. } catch (error) {
  693. console.error('收藏操作失败:', error);
  694. alert('收藏失败,请检查网络连接');
  695. }
  696. });
  697. });
  698. // 为删除收藏按钮添加点击事件
  699. container.querySelectorAll('.delete-btn').forEach((btn, index) => {
  700. btn.addEventListener('click', async function () {
  701. const card = this.closest('.history-card'), is_recover = this.classList.contains('active');
  702. const recordId = card.dataset.id;
  703. if (confirm(`确定要${is_recover ? '恢复' : '删除'}这条记录吗?`)) {
  704. try {
  705. const response = await fetch(`/api/history/${recordId}/delete`, {
  706. method: 'POST'
  707. });
  708. if (response.ok) {
  709. card.remove();
  710. // 如果没有卡片了,显示空提示
  711. if (container.querySelectorAll('.history-card').length === 0) {
  712. container.innerHTML = '<div class="placeholder">暂无记录</div>';
  713. }
  714. if (is_recover) {
  715. alert('恢复成功');
  716. } else {
  717. alert('删除成功');
  718. }
  719. } else {
  720. alert('删除失败,请重试');
  721. }
  722. } catch (error) {
  723. console.error('删除操作失败:', error);
  724. alert('删除失败,请检查网络连接');
  725. }
  726. }
  727. });
  728. });
  729. function renderHistoryAnswers(answers) {
  730. let str = ''
  731. if (!answers || answers.length === 0) {
  732. str = '<p class="placeholder">没有找到答案</p>';
  733. return str;
  734. }
  735. // 根据答案类型渲染不同的内容
  736. if (Array.isArray(answers)) {
  737. // 如果是数组,渲染为列表
  738. const answersHTML = answers.map(answer => {
  739. if (typeof answer === 'object' && answer.expression) {
  740. // 如果是解法对象
  741. return `
  742. <div class="solution-item flag-${answer.flag || 0}">
  743. <div class="solution-expression">${answer.expression}</div>
  744. <div class="solution-flag flag-${answer.flag || 0}">
  745. ${answer.flag === 1 ? '★' : answer.flag === 2 ? '★★' : ''}
  746. </div>
  747. </div>
  748. `;
  749. } else {
  750. // 如果是普通文本
  751. return `<div class="answer-item">${answer}</div>`;
  752. }
  753. }).join('');
  754. str = `
  755. <div class="answers-container">
  756. ${answersHTML}
  757. </div>
  758. `;
  759. } else if (typeof answers === 'object') {
  760. // 如果是单个对象
  761. const answerKeys = Object.keys(answers);
  762. const answersHTML = answerKeys.map(key => {
  763. return `
  764. <div class="answer-group">
  765. <div class="answer-key">${key}:</div>
  766. <div class="answer-value">${answers[key]}</div>
  767. </div>
  768. `;
  769. }).join('');
  770. str = `
  771. <h3>答案</h3>
  772. <div class="answers-container">
  773. ${answersHTML}
  774. </div>
  775. `;
  776. } else {
  777. // 如果是单个值
  778. str = `
  779. <h3>答案</h3>
  780. <div class="answers-container">
  781. <div class="answer-item">${answers}</div>
  782. </div>
  783. `;
  784. }
  785. return str;
  786. }
  787. }
  788. // 设置日期输入框的默认值为当前日期
  789. const today = new Date();
  790. // 计算三天前的日期
  791. const threeDaysAgo = new Date();
  792. threeDaysAgo.setDate(today.getDate() - 3);
  793. // 设置开始日期输入框的值为三天前
  794. historyStartDateInput.value = threeDaysAgo.toISOString().split('T')[0];
  795. historyEndDateInput.value = today.toISOString().split('T')[0];
  796. });