script.js 38 KB

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