yjbdcController.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. import moment from 'moment';
  2. import fs from 'fs';
  3. import { promises as fsPromises } from 'fs';
  4. import commonModel from '../../model/commonModel.js';
  5. import config from '../../config/index.js';
  6. import _ from 'lodash';
  7. import axios from 'axios';
  8. import { Encrypt, Decrypt } from '../../util/crypto/index.js';
  9. import { stringUtils } from '../../util/stringClass.js';
  10. import WXBizDataCrypt from '../../util/WXBizDataCrypt.js';
  11. import { globalCache } from '../../util/GlobalCache.js';
  12. import constantClass from '../../util/constant/index.js';
  13. import yjbdc from '../../model/yjbdc.js';
  14. import aiController from './aiController.js';
  15. import PDFDocument from 'pdfkit';
  16. import tencentcloud from 'tencentcloud-sdk-nodejs-ocr';
  17. const OcrClient = tencentcloud.ocr.v20181119.Client;
  18. const ONE_DAY_MAX_BUILD_COUNT=12;//一天最大生成数
  19. //AI生成文章
  20. export async function GenerateArticle(ctx) {
  21. const url='GenerateArticle?UserID='+ctx.query.UserID;
  22. let result = globalCache.get(url);
  23. // 检查是否是队列状态而不是正在处理状态
  24. if (result && result.isQueued) {
  25. // 如果是队列状态,继续处理
  26. result = 0;
  27. }
  28. if (result === 0) {
  29. const params = ctx.request.body;
  30. const words = params.Words;
  31. let articleStyle = params.ArticleStyle;
  32. if (words){
  33. //生成中
  34. result = { errcode: 10000, result: "-2" };
  35. globalCache.set(url, result, config.BufferMemoryTime);
  36. console.log("生成中,暂停生成60秒");
  37. const menuConfig=constantClass.GetYJBDCGenerateConfig();
  38. //console.log("content:"+content);
  39. let level="";
  40. if (!params.Level || params.Level=="" || params.Level==undefined || params.Level>="6"){
  41. params.Level=0;
  42. }
  43. level=menuConfig.Level[Number(params.Level)].Name;
  44. let articleStyleContent="";
  45. for(let i=0;i<menuConfig.ArticleStyle.length;i++){
  46. if (params.ArticleStyle==menuConfig.ArticleStyle[i].Name){
  47. articleStyleContent=menuConfig.ArticleStyle[i].Content;
  48. }
  49. }
  50. //console.log("Level:"+level);
  51. let content={
  52. "instruction": "用单词("+words+")生成"+level+"难度的文章。",
  53. "requirements": [
  54. "200-300词,要求:"+articleStyle+"("+articleStyleContent+")",
  55. "每句分数组提供中英双语,ArticleEnglish必须纯英文不含中文,ArticleChinese必须纯中文不含未翻译的英文单词",
  56. "所有单词至少出现一次(允许变形)",
  57. "生成5道四选一阅读题(含答案)",
  58. "提供用户单词在文中中文翻译",
  59. "所有字段必须完整出现,任何缺失需立即补全并维持原顺序,特别是Question中的所有字段(QuestionEnglish、QuestionChinese、OptionsEnglish、OptionsChinese、Answer)都必须存在"
  60. ],
  61. "output_format": {
  62. "ArticleEnglish": ["句子1", "句子2..."],
  63. "ArticleChinese": ["翻译1", "翻译2..."],
  64. "WordChinese": ["单词1:翻译1", "单词2:翻译2..."],
  65. "Question": [{
  66. "QuestionEnglish": "题干",
  67. "QuestionChinese": "题干翻译",
  68. "OptionsEnglish": ["A.选项", "B.选项", "C.选项", "D.选项"],
  69. "OptionsChinese": ["A.译", "B.译", "C.译", "D.译"],
  70. "Answer": "正确选项字母"
  71. }]
  72. }
  73. };
  74. content=JSON.stringify(content);
  75. // 从请求参数中获取AI提供者,如果没有指定则使用默认值
  76. let aiProvider = '';
  77. for(let i=0;i<menuConfig.AIVersion.length;i++){
  78. if (menuConfig.AIVersion[i].Version==params.AIVersion){
  79. aiProvider=menuConfig.AIVersion[i].Model;
  80. break;
  81. }
  82. }
  83. //给用户一些比较好的体验
  84. if (params.AIVersion=="1.0"){
  85. aiProvider = 'ali-Moonshot-Kimi-K2-Instruct';
  86. }
  87. else if (params.AIVersion=="1.5"){
  88. aiProvider = 'doubao-kimi-k2-250711';
  89. }
  90. try {
  91. //开始时间
  92. let timeStart=new Date().getTime();
  93. // 使用aiController生成文章
  94. let result2 = await aiController.generateArticle(content, aiProvider);
  95. //console.log(result2);
  96. //debugger;
  97. // 校验和修复JSON结构
  98. result2 = aiController.validateAndFixJSON(result2);
  99. //console.log("JSON结构已校验和修复");
  100. result2 =aiController.normalizeArticleFields(result2);
  101. // 解析JSON以增强FormsOfWords
  102. const jsonObj = JSON.parse(result2);
  103. // 增强FormsOfWords,检测文章中单词的变形形式和拼写错误
  104. const enhancedJsonObj = aiController.enhanceFormsOfWords(jsonObj, words);
  105. // 再次确保中文句子被正确分类
  106. if (enhancedJsonObj.ArticleEnglish && Array.isArray(enhancedJsonObj.ArticleEnglish)) {
  107. const englishSentences = [];
  108. const chineseSentences = [];
  109. // 遍历ArticleEnglish数组,分离英文和中文句子
  110. enhancedJsonObj.ArticleEnglish.forEach(sentence => {
  111. // 检查句子是否包含中文字符
  112. if (/[\u4e00-\u9fa5]/.test(sentence)) {
  113. chineseSentences.push(sentence);
  114. } else {
  115. englishSentences.push(sentence);
  116. }
  117. });
  118. // 更新ArticleEnglish数组,只保留英文句子
  119. enhancedJsonObj.ArticleEnglish = englishSentences;
  120. // 如果ArticleChinese不存在或不是数组,则创建它
  121. if (!enhancedJsonObj.ArticleChinese || !Array.isArray(enhancedJsonObj.ArticleChinese)) {
  122. enhancedJsonObj.ArticleChinese = [];
  123. }
  124. // 将中文句子添加到ArticleChinese数组中
  125. chineseSentences.forEach(sentence => {
  126. if (!enhancedJsonObj.ArticleChinese.includes(sentence)) {
  127. enhancedJsonObj.ArticleChinese.push(sentence);
  128. }
  129. });
  130. }
  131. // 将增强后的对象转回JSON字符串
  132. result2 = JSON.stringify(enhancedJsonObj);
  133. //console.log("FormsOfWords已增强,添加了单词变形和拼写错误检测");
  134. // 记录增强后的单词数量
  135. if (enhancedJsonObj.FormsOfWords && Array.isArray(enhancedJsonObj.FormsOfWords)) {
  136. console.log(`增强了${enhancedJsonObj.FormsOfWords.length}个单词的变形形式`);
  137. }
  138. let timeEnd=new Date().getTime();
  139. let param2={};
  140. param2.UserID=ctx.query.UserID;
  141. param2.CreateTime=moment().format('YYYY-MM-DD HH:mm:ss');
  142. param2.Words=words;
  143. param2.Level=params.Level;
  144. param2.articleStyle=articleStyle;
  145. param2.AIProvider=aiProvider;
  146. param2.BuildStr=content;
  147. param2.GenerateTime=Math.round((timeEnd-timeStart)/1000);
  148. console.log("生成时间:"+param2.GenerateTime+"秒");
  149. // 尝试解析JSON以获取ArticleStart
  150. const jsonObj2 = JSON.parse(result2);
  151. param2.ArticleStart = jsonObj2.ArticleEnglish && jsonObj2.ArticleEnglish.length > 0 ? jsonObj2.ArticleEnglish.join("\r\n") : "No content available";
  152. // 去除JSON字符串中的所有换行符(\r\n, \n, \r)
  153. param2.JSONString=JSON.stringify(result2.replace(/[\r\n]+/g, ''));
  154. param2.Flag=0;
  155. let idInsert= await yjbdc.AddArticleInfo(param2);
  156. //result = { errcode: 10000, result: result2 };
  157. let result3={};
  158. result3.ID=idInsert.insertId;
  159. result3.Content=result2;
  160. result3.IsNew=true;
  161. result = { errcode: 10000, result: result3 };
  162. globalCache.delete(url);
  163. console.log("删除缓存,恢复生成");
  164. }
  165. catch(err){
  166. console.error("AI生成错误:"+err);
  167. result = { errcode: 10000, result: "-1" };
  168. }
  169. }
  170. else{
  171. console.log("空单词串");
  172. result = { errcode: 10000, result: "-1" };
  173. }
  174. }
  175. ctx.body = result;
  176. }
  177. //小程序登录
  178. export async function YJBDCLogin(ctx) {
  179. let param = ctx.request.body;
  180. if (param.param) {
  181. const paramStr = Decrypt(param.param, config.urlSecrets.aes_key, config.urlSecrets.aes_iv);
  182. //console.log("paramStr:"+paramStr);
  183. param = JSON.parse(paramStr);
  184. }
  185. const code = param.Code;
  186. //console.log("code:"+code);
  187. const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wx.yjbdc_appid}&secret=${config.wx.yjbdc_appsecret}&js_code=${code}&grant_type=authorization_code`;
  188. let result = await axios.get(url)
  189. .then(res => {
  190. const json = res.data;
  191. //console.log("json:"+json);
  192. if (json && json.openid) {
  193. param.OpenID = json.openid;
  194. param.sessionKey = json.session_key;
  195. if (json.unionid)
  196. param.UnionID = json.unionid;
  197. return {errcode: 10000};
  198. }
  199. else {
  200. return json;
  201. }
  202. })
  203. .catch(err => {
  204. return {errcode: 101, errStr: err};
  205. });
  206. if (result.errcode == 10000) {
  207. delete param.Code;
  208. if (param.sessionKey && param.iv && param.encryptedData){
  209. //console.log("param.sessionKey:"+param.sessionKey);
  210. const pc = new WXBizDataCrypt(config.wx.yjbdc_appid, param.sessionKey);
  211. const dataUnionID = pc.decryptData(param.encryptedData , param.iv);
  212. //console.log(dataUnionID);
  213. param.UnionID = dataUnionID.unionId;
  214. }
  215. delete param.sessionKey;
  216. delete param.iv;
  217. delete param.encryptedData;
  218. //todo
  219. //param.OpenID="o4UHq4gaNlHfdTWxgl3fTgC1mFsI";
  220. let userList = await yjbdc.GetUsersInfo(param);
  221. if (userList.length > 0) {
  222. param.LastLoginTime = new Date();
  223. const time1 = moment(userList[0].ProductServiceTime).format('YYYY-MM-DD HH:mm:ss');
  224. const time3 = moment().format('YYYY-MM-DD HH:mm:ss');
  225. if (time1 < time3)
  226. param.IsMember = 0;
  227. delete param.Introducer;
  228. delete param.UserSource;
  229. delete param.SourceID;
  230. //console.log(param.NickName);
  231. if (param.NickName == "陌生用户") {
  232. delete param.NickName;
  233. delete param.AvatarUrl;
  234. delete param.Language;
  235. delete param.Gender;
  236. delete param.City;
  237. delete param.Province;
  238. delete param.Country;
  239. }
  240. await yjbdc.UpdateUsers(param);
  241. userList = await yjbdc.GetUsersInfo(param);
  242. }
  243. else {
  244. param.NickName = "陌生用户";
  245. param.AvatarUrl = "../images/userface_default.png";
  246. param.CreateTime = new Date();
  247. param.LastLoginTime = param.CreateTime;
  248. param.ProductServiceTime = param.CreateTime;
  249. const inseredID = await yjbdc.AddUsers(param);
  250. userList = await yjbdc.GetUsersInfo(param);
  251. }
  252. delete userList[0].OpenID;
  253. delete userList[0].UnionID;
  254. //产品支付是否显示
  255. if (param.ProgramVersion) {
  256. let param2 = {
  257. ProgramID: 186,
  258. Version: param.ProgramVersion,
  259. };
  260. let result3 = await commonModel.GetProductVersionList(param2);
  261. if (result3) {
  262. if ((param2.Version == result3[0].Version && result3[0].IsShowPay <= 0)
  263. || param2.Version > result3[0].Version) {
  264. userList[0].IsShow = result3[0].IsShowPay;
  265. }
  266. else {
  267. userList[0].IsShow = 1;
  268. }
  269. //针对iphone测试用户,永远是无支付状态
  270. if (userList[0].Brand == 'iPhone' && userList[0].WXLanguage == 'en-US'
  271. && userList[0].UserSource == '1001' && userList[0].IsPay == 0) {
  272. userList[0].IsShow = 0;
  273. }
  274. //针对微信测试用户,永远是无支付状态
  275. if ((userList[0].UserSource=='1001' && userList[0].System=="iOS 10.0.1")
  276. || (!userList[0].UserSource && (!userList[0].LastUserSource || userList[0].LastUserSource>10000))
  277. || userList[0].NickName.indexOf("dgztest")>=0){
  278. userList[0].IsShow=-1;
  279. }
  280. if (userList[0].IsMember===1)
  281. userList[0].IsShow=1;
  282. }
  283. }
  284. result = {errcode: 10000, result: userList[0]};
  285. }
  286. ctx.body = result;
  287. }
  288. //OCR获取单词
  289. export async function OCRImageData(ctx) {
  290. const params = ctx.request.body;
  291. const clientConfig = {
  292. credential: {
  293. secretId: config.tencentcloud.secretId,
  294. secretKey: config.tencentcloud.secretKey,
  295. },
  296. region: "ap-guangzhou",
  297. profile: {
  298. httpProfile: {
  299. endpoint: "ocr.tencentcloudapi.com",
  300. },
  301. },
  302. };
  303. // 实例化要请求产品的client对象,clientProfile是可选的
  304. const client = new OcrClient(clientConfig);
  305. const result = await client.GeneralBasicOCR(params);
  306. let param2={};
  307. param2.UserID=ctx.query.UserID;
  308. param2.CreateTime=moment().format('YYYY-MM-DD HH:mm:ss');
  309. param2.Params=JSON.stringify(params);
  310. param2.JSONString=JSON.stringify(result);
  311. await yjbdc.AddOCRInfo(param2);
  312. ctx.body = {"errcode": 10000, result};
  313. }
  314. export async function GetYJBDCGenerateConfig(ctx) {
  315. const param = {
  316. UserID: ctx.query.UserID || 0,
  317. };
  318. let result=constantClass.GetYJBDCGenerateConfig();
  319. for (let i=0;i<result.Level.length;i++){
  320. delete result.Level[i].English;
  321. }
  322. for(let i=0;i<result.ArticleStyle.length;i++){
  323. delete result.ArticleStyle[i].English;
  324. delete result.ArticleStyle[i].Content;
  325. }
  326. if (param.UserID>3){
  327. result.AIVersion.splice(2,result.AIVersion.length-2);
  328. if (param.UserID==185){
  329. const configArr=constantClass.GetYJBDCGenerateConfig();
  330. result.AIVersion.push(configArr.AIVersion[5]);
  331. }
  332. // if (param.UserID<4){
  333. // const configArr=constantClass.GetYJBDCGenerateConfig();
  334. // result.AIVersion.push(configArr.AIVersion[6]);
  335. // }
  336. }
  337. ctx.body = {"errcode": 10000, result:result};
  338. }
  339. //获得文章列表或具体文章
  340. export async function GetYJBDCArticleList(ctx) {
  341. const param = {
  342. UserID: ctx.query.UserID || 0,
  343. ID:ctx.query.ID || 0,
  344. IsFine:ctx.query.IsFine || 0,//是否是精选文章
  345. IsTodayCount: ctx.query.IsTodayCount || false,
  346. IsNew: ctx.query.IsNew || 0,
  347. PageID: ctx.query.PageID || 999999,
  348. PageCount: ctx.query.PageCount || 10,
  349. };
  350. if (param.IsFine)
  351. param.PageCount=9999;
  352. // 尝试从缓存获取
  353. const url='GetYJBDCArticleList?IsFine='+param.IsFine+'&UserID='+param.UserID+'&ID='+param.ID;
  354. let result = globalCache.get(url);
  355. if (param.IsNew==1)
  356. result=0;
  357. if (result === 0) {
  358. result = await yjbdc.GetYJBDCArticleList(param);
  359. let menuConfig=constantClass.GetYJBDCGenerateConfig();
  360. // 随机选择三个不重复的索引用于今日推荐
  361. let recommendIndices = [];
  362. if(result.length > 3) {
  363. while(recommendIndices.length < 3) {
  364. const randomIndex = Math.floor(Math.random() * result.length);
  365. if(!recommendIndices.includes(randomIndex)) {
  366. recommendIndices.push(randomIndex);
  367. }
  368. }
  369. } else {
  370. // 如果结果少于3个,全部标记为推荐
  371. for(let i = 0; i < result.length; i++) {
  372. recommendIndices.push(i);
  373. }
  374. }
  375. for(let i=0;i<result.length;i++){
  376. let item=result[i];
  377. item.CreateTime=moment(item.CreateTime).format("YYYY年MM月DD日 HH:mm");
  378. //debugger;
  379. item.LevelStr=menuConfig.Level[item.Level].Name;
  380. // 添加今日推荐标记
  381. item.IsRecommend = recommendIndices.includes(i);
  382. }
  383. globalCache.set(url, result, config.BufferMemoryTime);
  384. console.log("缓存"+config.BufferMemoryTime+"秒");
  385. }
  386. //console.log(result.length);
  387. if (param.IsTodayCount && !param.ID){
  388. let count=0,unReadCount=0;
  389. const today=moment().format("YYYY年MM月DD日 00:00");
  390. for(let i=0;i<result.length;i++){
  391. if (result[i].CreateTime>=today)
  392. count++;
  393. if (result[i].Flag==0 && result[i].ReadCount==0)
  394. unReadCount++;
  395. }
  396. let maxcount=ONE_DAY_MAX_BUILD_COUNT;
  397. if (param.UserID<4){
  398. maxcount=100;
  399. }
  400. result={
  401. TodayCount:count,
  402. MaxCount:maxcount,
  403. UnReadCount:unReadCount,
  404. };
  405. }
  406. else if (!param.ID){
  407. let arr=[],count=0,total=0;
  408. for(let i=0;i<result.length;i++){
  409. if (result[i].Flag==0){
  410. if (param.PageID>result[i].ID && count<param.PageCount){
  411. arr.push(result[i]);
  412. count++;
  413. }
  414. total++;
  415. }
  416. }
  417. result=arr;
  418. if (result.length>0)
  419. result[0].RowsCount=total;
  420. }
  421. // console.log(result.length);
  422. // console.log(result.TodayCount);
  423. ctx.body = {"errcode": 10000, result:result};
  424. }
  425. //删除生成的文章
  426. export async function DeleteYJBDCArticleList(ctx) {
  427. const param = {
  428. UserID: ctx.query.UserID || 0,
  429. ID: ctx.query.ID || 0,
  430. Flag:-1,
  431. };
  432. if (param.ID>0){
  433. const url='GetYJBDCArticleList?UserID='+param.UserID+"&ID=0";
  434. globalCache.delete(url);
  435. await yjbdc.UpdateYJBDCArticle(param);
  436. }
  437. ctx.body = {"errcode": 10000};
  438. }
  439. // 更新文章数据(目前仅用于网站)
  440. export async function UpdateYJBDCArticle(ctx) {
  441. const param = ctx.request.body;
  442. if (param.ID>0 && param.UserID<12 && param.Source=="web"){
  443. const url='GetYJBDCArticleList?IsFine=0&UserID='+param.UserID+"&ID=0";
  444. globalCache.delete(url);
  445. const url2='GetYJBDCArticleList?IsFine=0&UserID='+param.UserID+"&ID="+param.ID;
  446. globalCache.delete(url2);
  447. delete param.LevelStr;
  448. delete param.CreateTime;
  449. delete param.IsRecommend;
  450. await yjbdc.UpdateYJBDCArticle(param);
  451. }
  452. ctx.body = {"errcode": 10000};
  453. }
  454. //更新阅读数
  455. export async function UpdateYJBDCArticleReadCount(ctx) {
  456. const param = {
  457. UserID: ctx.query.UserID || 0,
  458. ID: ctx.query.ID || 0,
  459. ReadCount:1,
  460. };
  461. if (param.ID>0){
  462. await yjbdc.UpdateYJBDCArticle(param);
  463. }
  464. ctx.body = {"errcode": 10000};
  465. }
  466. export async function AddOrDeleteYJBDCUserCollect(ctx) {
  467. const param = {
  468. UserID: ctx.query.UserID || 0,
  469. Word: ctx.query.Word || '',
  470. CreateTime:moment().format("YYYY-MM-DD HH:mm:ss"),
  471. };
  472. let list=await yjbdc.GetYJBDCUserCollect(param);
  473. if (list && list.length>0)
  474. await yjbdc.DeleteYJBDCUserCollect(param);
  475. else
  476. await yjbdc.AddYJBDCUserCollect(param);
  477. let param2={}
  478. param2.UserID=param.UserID;
  479. let result=await yjbdc.GetYJBDCUserCollect(param2);
  480. ctx.body = {"errcode": 10000,result:result};
  481. }
  482. export async function DeleteYJBDCUserCollect(ctx) {
  483. const param = {
  484. UserID: ctx.query.UserID || 0,
  485. WordArr:ctx.query.WordArr || "",
  486. };
  487. let arr=param.WordArr.split(",");
  488. for(let i=0;i<arr.length;i++){
  489. let obj={};
  490. obj.UserID=param.UserID;
  491. obj.Word=arr[i];
  492. await yjbdc.DeleteYJBDCUserCollect(obj);
  493. }
  494. let param2={}
  495. param2.UserID=param.UserID;
  496. let result=await yjbdc.GetYJBDCUserCollect(param2);
  497. ctx.body = {"errcode": 10000,result:result};
  498. }
  499. export async function GetYJBDCUserCollect(ctx) {
  500. const param = {
  501. UserID: ctx.query.UserID || 0,
  502. };
  503. let list=await yjbdc.GetYJBDCUserCollect(param);
  504. ctx.body = {"errcode": 10000,result:list};
  505. }
  506. //生成PDF
  507. export async function GeneratePDF(ctx) {
  508. const params = ctx.request.body;
  509. if (!params || !params.Content) {
  510. ctx.status = 400;
  511. ctx.body = { error: 'Invalid request body: Content is required' };
  512. return;
  513. }
  514. const content = params.Content;
  515. const menuConfig=constantClass.GetYJBDCGenerateConfig();
  516. try {
  517. // 创建新的 PDF 文档 - 使用A4尺寸
  518. const doc = new PDFDocument({
  519. size: 'A4', // 使用标准A4尺寸 (595.28 x 841.89 points)
  520. margins: {
  521. top: 0,
  522. bottom: 0,
  523. left: 0,
  524. right: 0
  525. },
  526. autoFirstPage: true
  527. });
  528. // 注册中文字体
  529. doc.registerFont('ChineseFont', './public/fonts/方正黑体简体.TTF');
  530. // 定义字体选择函数
  531. const selectFont = (text, defaultFont = 'Helvetica') => {
  532. if (/[\u4E00-\u9FFF]/.test(text)) {
  533. return 'ChineseFont';
  534. }
  535. return defaultFont;
  536. };
  537. // 收集生成的 PDF 数据
  538. const chunks = [];
  539. doc.on('data', (chunk) => chunks.push(chunk));
  540. // 像素到点(pt)的转换函数
  541. const pixelToPt = (pixel) => pixel * (595.28 / 2100);
  542. // 获取文章内容
  543. let articleText = "";
  544. if (content.ArticleEnglish) {
  545. articleText = Array.isArray(content.ArticleEnglish) ?
  546. content.ArticleEnglish.join(" ") : content.ArticleEnglish;
  547. } else {
  548. articleText = "No content available";
  549. }
  550. articleText = articleText.replace(/<[^>]*>/g, '');
  551. articleText = articleText.replace(/(^|[,.]\s+)'([^']+)'/g, '$1"$2"');
  552. // 获取单词列表
  553. let words = [];
  554. if (content.Words) {
  555. words = typeof content.Words === 'string' ?
  556. content.Words.split(",") :
  557. (Array.isArray(content.Words) ? content.Words : []);
  558. }
  559. // 获取问题列表
  560. let questions = [];
  561. if (content.Question && Array.isArray(content.Question)) {
  562. questions = content.Question;
  563. }
  564. let articleStyleArr=menuConfig.ArticleStyle;
  565. let articleStyle="Story";
  566. for(let i=0;i<articleStyleArr.length;i++){
  567. if (articleStyleArr[i].Name==content.ArticleStyle){
  568. articleStyle=articleStyleArr[i].English;
  569. break;
  570. }
  571. }
  572. // 1. 标题 - 文章类型
  573. doc.font(selectFont(articleStyle))
  574. .fontSize(pixelToPt(48))
  575. .text(articleStyle,
  576. pixelToPt(120), pixelToPt(110));
  577. // 2. 副标题 - 难度级别
  578. doc.font('Helvetica')
  579. .fontSize(pixelToPt(30))
  580. .text(menuConfig.Level[Number(content.Level)].English || "",
  581. pixelToPt(120), pixelToPt(170));
  582. // 3. 时间
  583. const currentDate = moment().format("YYYY年MM月DD日 HH:mm");
  584. if (params.CreateTime)
  585. currentDate=moment(params.CreateTime).format("YYYY年MM月DD日 HH:mm");
  586. doc.font('ChineseFont')
  587. .fontSize(pixelToPt(30))
  588. .text(currentDate,
  589. pixelToPt(120), pixelToPt(212));
  590. // 4. 黑线
  591. doc.rect(pixelToPt(120), pixelToPt(289), pixelToPt(537), pixelToPt(10))
  592. .fill('black');
  593. // 5. 单词列表
  594. doc.font('Helvetica')
  595. .fontSize(pixelToPt(36));
  596. let wordY = pixelToPt(364);
  597. words.slice(0, 10).forEach(word => {
  598. doc.text(word, pixelToPt(122), wordY, {
  599. width: pixelToPt(535),
  600. align: 'left'
  601. });
  602. wordY += pixelToPt(70);
  603. });
  604. // 6. 文章内容
  605. // 先计算文章内容的行数
  606. doc.font('Helvetica');
  607. // 使用48字号计算文本高度
  608. const fontSize48 = pixelToPt(48);
  609. doc.fontSize(fontSize48);
  610. const textHeight48 = doc.heightOfString(articleText, {
  611. width: pixelToPt(1240),
  612. lineGap: pixelToPt(40.5)
  613. });
  614. // 计算行数 (文本高度 / (字体大小 + 行间距))
  615. const lineHeight = fontSize48 + pixelToPt(40.5);
  616. const lineCount = Math.ceil(textHeight48 / lineHeight);
  617. // 如果行数超过18行,则使用42字号
  618. const fontSize = lineCount > 18 ? pixelToPt(42) : pixelToPt(48);
  619. // 渲染文章内容
  620. doc.fontSize(fontSize)
  621. .text(articleText, pixelToPt(740), pixelToPt(105), {
  622. width: pixelToPt(1240),
  623. lineGap: pixelToPt(40.5)
  624. });
  625. // 7. 黑线
  626. const articleEndY = doc.y;
  627. const wordListEndY = doc.y; // 假设单词列表的Y坐标
  628. const maxY = Math.max(articleEndY, wordListEndY);
  629. // 检查内容是否过长,需要分页
  630. const pageHeight = doc.page.height;
  631. const availableHeight = pageHeight - pixelToPt(400); // 预留底部空间
  632. const needsNewPage = articleEndY > availableHeight;
  633. if (doc && typeof doc.line === 'function') {
  634. doc.line(20, maxY, 200, maxY);
  635. }
  636. // 如果内容过长,则创建新页面
  637. if (needsNewPage) {
  638. // 在第一页底部添加提示
  639. doc.font('Helvetica')
  640. .fontSize(pixelToPt(24))
  641. .text("(Continued on next page...)",
  642. pixelToPt(740), pageHeight - pixelToPt(100), {
  643. align: 'center'
  644. });
  645. // 添加新页面
  646. doc.addPage();
  647. // 在新页面顶部添加标题
  648. doc.font(selectFont(articleStyle))
  649. .fontSize(pixelToPt(36))
  650. .text(articleStyle + " (Continued)",
  651. pixelToPt(120), pixelToPt(50));
  652. // 在新页面添加黑线
  653. doc.rect(pixelToPt(120), pixelToPt(100),
  654. pixelToPt(1860), pixelToPt(10))
  655. .fill('black');
  656. } else {
  657. // 如果不需要分页,正常添加黑线
  658. doc.rect(pixelToPt(120), articleEndY + pixelToPt(41),
  659. pixelToPt(1860), pixelToPt(10))
  660. .fill('black');
  661. }
  662. // 8-13. 问题和答案
  663. if (questions.length > 0) {
  664. // 定义问题的X坐标位置
  665. const questionXPositions = [
  666. pixelToPt(120), // 问题1
  667. pixelToPt(120), // 问题2
  668. pixelToPt(740), // 问题3
  669. pixelToPt(740), // 问题4
  670. pixelToPt(1360) // 问题5
  671. ];
  672. // 存储每列最后一个选项的Y坐标位置
  673. let lastOptionYPositions = {
  674. column1: 0, // 用于跟踪第一列(问题1)的最后位置
  675. column2: 0, // 用于跟踪第二列(问题3)的最后位置
  676. };
  677. // 确定问题的起始Y坐标
  678. // 如果内容过长需要分页,则在新页面上从固定位置开始
  679. // 否则在文章内容下方开始
  680. const questionsStartY = needsNewPage ?
  681. pixelToPt(150) : // 新页面上的起始位置
  682. articleEndY + pixelToPt(130); // 原页面上的起始位置
  683. // 首先渲染问题1、3、5(第一行问题)
  684. const firstRowQuestions = [0, 2, 4]; // 问题1、3、5的索引
  685. for (const i of firstRowQuestions) {
  686. if (i < questions.length && questions[i]) {
  687. const currentX = questionXPositions[i];
  688. const currentY = questionsStartY; // 使用计算出的起始Y坐标
  689. questions[i].QuestionEnglish = questions[i].QuestionEnglish.replace(/(^|[,.]\s+)'([^']+)'/g, '$1"$2"');
  690. // 渲染问题文本
  691. doc.font('Helvetica-Bold')
  692. .fontSize(pixelToPt(36))
  693. .text(`${i+1}. ${questions[i].QuestionEnglish || `Question ${i+1}`}`,
  694. currentX, currentY, {
  695. width: pixelToPt(540),
  696. align: 'left'
  697. });
  698. // 获取问题文本渲染后的Y坐标位置
  699. const questionEndY = doc.y;
  700. // 选项起始位置 = 问题结束位置 + 20像素间距
  701. let optionY = questionEndY + pixelToPt(28);
  702. // 渲染选项
  703. const options = questions[i].OptionsEnglish || [];
  704. const optionLabels = ['A', 'B', 'C', 'D'];
  705. // 设置选项标签宽度和选项总宽度
  706. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  707. const totalWidth = pixelToPt(496); // 选项的总宽度
  708. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  709. options.forEach((opt, index) => {
  710. if (index < optionLabels.length) {
  711. // 提取选项内容,移除可能存在的标签前缀
  712. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  713. // 渲染选项标签(A./B./C./D.)
  714. doc.font('Helvetica')
  715. .fontSize(pixelToPt(36))
  716. .text(`${optionLabels[index]}.`, currentX, optionY, {
  717. width: labelWidth,
  718. align: 'left'
  719. });
  720. // 渲染选项内容,确保折行时与内容第一行对齐
  721. doc.font('Helvetica')
  722. .fontSize(pixelToPt(36))
  723. .text(optionContent, currentX + labelWidth, optionY, {
  724. width: contentWidth,
  725. align: 'left'
  726. });
  727. // 更新选项Y坐标,为下一个选项做准备
  728. // 获取当前位置,确保下一个选项在当前选项完全渲染后的位置
  729. optionY = doc.y + pixelToPt(8);
  730. }
  731. });
  732. // 保存该列最后一个选项的Y坐标
  733. if (i === 0) {
  734. lastOptionYPositions.column1 = doc.y;
  735. } else if (i === 2) {
  736. lastOptionYPositions.column2 = doc.y;
  737. }
  738. }
  739. }
  740. // 然后渲染问题2和4(第二行问题)
  741. if (questions.length > 1 && questions[1]) {
  742. // 问题2位于问题1的选项下方60像素处
  743. const question2Y = lastOptionYPositions.column1 + pixelToPt(75);
  744. doc.font('Helvetica-Bold')
  745. .fontSize(pixelToPt(36))
  746. .text(`2. ${questions[1].QuestionEnglish || "Question 2"}`,
  747. questionXPositions[1], question2Y, {
  748. width: pixelToPt(540),
  749. align: 'left'
  750. });
  751. // 获取问题文本渲染后的Y坐标位置
  752. const questionEndY = doc.y;
  753. // 选项起始位置 = 问题结束位置 + 20像素间距
  754. let optionY = questionEndY + pixelToPt(28);
  755. // 渲染选项
  756. const options = questions[1].OptionsEnglish || [];
  757. const optionLabels = ['A', 'B', 'C', 'D'];
  758. // 设置选项标签宽度和选项总宽度
  759. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  760. const totalWidth = pixelToPt(496); // 选项的总宽度
  761. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  762. options.forEach((opt, index) => {
  763. if (index < optionLabels.length) {
  764. // 提取选项内容,移除可能存在的标签前缀
  765. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  766. // 渲染选项标签(A./B./C./D.)
  767. doc.font('Helvetica')
  768. .fontSize(pixelToPt(36))
  769. .text(`${optionLabels[index]}.`, questionXPositions[1], optionY, {
  770. width: labelWidth,
  771. align: 'left'
  772. });
  773. // 渲染选项内容,确保折行时与内容第一行对齐
  774. doc.font('Helvetica')
  775. .fontSize(pixelToPt(36))
  776. .text(optionContent, questionXPositions[1] + labelWidth, optionY, {
  777. width: contentWidth,
  778. align: 'left'
  779. });
  780. // 更新选项Y坐标,为下一个选项做准备
  781. optionY = doc.y + pixelToPt(8);
  782. }
  783. });
  784. }
  785. if (questions.length > 3 && questions[3]) {
  786. // 问题4位于问题3的选项下方60像素处
  787. const question4Y = lastOptionYPositions.column2 + pixelToPt(75);
  788. doc.font('Helvetica-Bold')
  789. .fontSize(pixelToPt(36))
  790. .text(`4. ${questions[3].QuestionEnglish || "Question 4"}`,
  791. questionXPositions[3], question4Y, {
  792. width: pixelToPt(540),
  793. align: 'left'
  794. });
  795. // 获取问题文本渲染后的Y坐标位置
  796. const questionEndY = doc.y;
  797. // 选项起始位置 = 问题结束位置 + 20像素间距
  798. let optionY = questionEndY + pixelToPt(28);
  799. // 渲染选项
  800. const options = questions[3].OptionsEnglish || [];
  801. const optionLabels = ['A', 'B', 'C', 'D'];
  802. // 设置选项标签宽度和选项总宽度
  803. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  804. const totalWidth = pixelToPt(496); // 选项的总宽度
  805. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  806. options.forEach((opt, index) => {
  807. if (index < optionLabels.length) {
  808. // 提取选项内容,移除可能存在的标签前缀
  809. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  810. // 渲染选项标签(A./B./C./D.)
  811. doc.font('Helvetica')
  812. .fontSize(pixelToPt(36))
  813. .text(`${optionLabels[index]}.`, questionXPositions[3], optionY, {
  814. width: labelWidth,
  815. align: 'left'
  816. });
  817. // 渲染选项内容,确保折行时与内容第一行对齐
  818. doc.font('Helvetica')
  819. .fontSize(pixelToPt(36))
  820. .text(optionContent, questionXPositions[3] + labelWidth, optionY, {
  821. width: contentWidth,
  822. align: 'left'
  823. });
  824. // 更新选项Y坐标,为下一个选项做准备
  825. optionY = doc.y + pixelToPt(8);
  826. }
  827. });
  828. }
  829. // 问题5
  830. if (questions.length > 4 && questions[4]) {
  831. const currentX = questionXPositions[4];
  832. // 如果分页,问题5的Y坐标与问题1和3相同
  833. const currentY = questionsStartY;
  834. doc.font('Helvetica-Bold')
  835. .fontSize(pixelToPt(36))
  836. .text(`5. ${questions[4].QuestionEnglish || "Question 5"}`,
  837. currentX, currentY, {
  838. width: pixelToPt(540),
  839. align: 'left'
  840. });
  841. const questionEndY = doc.y;
  842. let optionY = questionEndY + pixelToPt(28);
  843. // 渲染选项
  844. const options = questions[4].OptionsEnglish || [];
  845. const optionLabels = ['A', 'B', 'C', 'D'];
  846. // 设置选项标签宽度和选项总宽度
  847. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  848. const totalWidth = pixelToPt(496); // 选项的总宽度
  849. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  850. options.forEach((opt, index) => {
  851. if (index < optionLabels.length) {
  852. // 提取选项内容,移除可能存在的标签前缀
  853. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  854. // 渲染选项标签(A./B./C./D.)
  855. doc.font('Helvetica')
  856. .fontSize(pixelToPt(36))
  857. .text(`${optionLabels[index]}.`, currentX, optionY, {
  858. width: labelWidth,
  859. align: 'left'
  860. });
  861. // 渲染选项内容,确保折行时与内容第一行对齐
  862. doc.font('Helvetica')
  863. .fontSize(pixelToPt(36))
  864. .text(optionContent, currentX + labelWidth, optionY, {
  865. width: contentWidth,
  866. align: 'left'
  867. });
  868. // 更新选项Y坐标,为下一个选项做准备
  869. optionY = doc.y + pixelToPt(8);
  870. }
  871. });
  872. }
  873. }
  874. // 14. 虚线
  875. // 计算虚线的位置 - 如果是分页,则在新页面上绘制
  876. const lastContentY = needsNewPage ?
  877. doc.page.height - pixelToPt(190) : // 新页面上的位置
  878. doc.page.height - pixelToPt(190); // 原页面上的位置
  879. doc.strokeColor('#D2D2D2')
  880. .dash(pixelToPt(20), { space: pixelToPt(28) }) // 设置虚线样式:宽20像素,间隔20像素
  881. .lineWidth(pixelToPt(10)) // 线高10像素
  882. .moveTo(pixelToPt(120), lastContentY)
  883. .lineTo(pixelToPt(120) + pixelToPt(1630), lastContentY)
  884. .stroke()
  885. .undash(); // 重置虚线样式
  886. // 15-19. 答案和底部信息
  887. doc.font('Helvetica-Bold') // 使用Helvetica-Bold作为Semibold替代
  888. .fontSize(pixelToPt(36))
  889. .fillColor('black'); // 重置颜色为黑色
  890. const answersY = doc.page.height - pixelToPt(144);
  891. // 获取问题答案
  892. const answers = [];
  893. if (questions.length > 0) {
  894. for (let i = 0; i < Math.min(questions.length, 5); i++) {
  895. const answer = questions[i].Answer || "";
  896. answers.push(`${i+1}. ${answer}`);
  897. }
  898. }
  899. // 显示答案(如果存在)
  900. const answerPositions = [120, 262, 411, 561, 711];
  901. for (let i = 0; i < Math.min(answers.length, 5); i++) {
  902. doc.text(answers[i], pixelToPt(answerPositions[i]), answersY+2, {
  903. width: pixelToPt(100),
  904. align: 'left'
  905. });
  906. }
  907. // 20-21. 应用名称
  908. doc.font('ChineseFont')
  909. .fontSize(pixelToPt(36))
  910. .text("语境背单词(微信小程序)", pixelToPt(1338), answersY,{
  911. width: pixelToPt(440),
  912. align: 'right'
  913. });
  914. // 添加二维码图片
  915. try {
  916. // 计算图片位置:距离右边120像素,距离底部100像素
  917. // 由于PDFKit使用左上角坐标系,需要计算左上角坐标
  918. const qrCodeWidth = pixelToPt(200);
  919. const qrCodeHeight = pixelToPt(200);
  920. const qrCodeX = doc.page.width - pixelToPt(120) - qrCodeWidth; // 右边距离转换为左边距离
  921. const qrCodeY = doc.page.height - pixelToPt(100) - qrCodeHeight; // 底部距离转换为顶部距离
  922. // 添加二维码图片
  923. doc.image('./public/images/acode/YJBDC_QRCode.png', qrCodeX, qrCodeY, {
  924. width: qrCodeWidth,
  925. height: qrCodeHeight
  926. });
  927. console.log("QR Code added successfully");
  928. } catch (imgError) {
  929. console.error("Error adding QR Code image:", imgError);
  930. }
  931. // 结束PDF生成
  932. doc.end();
  933. // 等待PDF生成完成
  934. const pdfBuffer = await new Promise((resolve) => {
  935. doc.on('end', () => {
  936. resolve(Buffer.concat(chunks));
  937. });
  938. });
  939. let filename="语境背单词_"+moment().format("YYMMDD_HHmm");
  940. // 设置响应头
  941. ctx.set('Content-Type', 'application/pdf');
  942. // 使用ASCII文件名作为主文件名,确保兼容性
  943. const asciiFilename = 'yjbdc_' + moment().format("YYMMDD_HHmm") + '.pdf';
  944. // 对中文文件名进行URL编码,用于filename*参数
  945. const encodedFilename = encodeURIComponent(filename + '.pdf');
  946. // 设置Content-Disposition头部,使用标准格式
  947. // 首先提供ASCII文件名,然后提供UTF-8编码的文件名
  948. ctx.set('Content-Disposition', `attachment; filename=${asciiFilename}; filename*=UTF-8''${encodedFilename}`);
  949. ctx.body = pdfBuffer;
  950. } catch (error) {
  951. console.error("Error generating PDF:", error);
  952. ctx.status = 500;
  953. ctx.body = { error: "Failed to generate PDF" };
  954. }
  955. }
  956. //生成二维码
  957. export async function BuildYJBDCQRCode(ctx) {
  958. try {
  959. // 获取微信访问令牌
  960. const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${config.wx.yjbdc_appid}&secret=${config.wx.yjbdc_appsecret}&grant_type=client_credential`;
  961. const tokenResponse = await axios.get(tokenUrl);
  962. const tokenData = tokenResponse.data;
  963. if (!tokenData || !tokenData.access_token) {
  964. ctx.status = 400;
  965. ctx.body = { errcode: 101, errStr: '获取微信访问令牌失败' };
  966. return;
  967. }
  968. const accessToken = tokenData.access_token;
  969. // 生成小程序码
  970. const qrCodeUrl = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
  971. const path = './public/images/acode/';
  972. const imageUrl = 'YJBDC_QRCode.png';
  973. const fullPath = path + imageUrl;
  974. // 确保目录存在
  975. if (!fs.existsSync(path)) {
  976. fs.mkdirSync(path, { recursive: true });
  977. }
  978. const postData = {
  979. width: 280,
  980. scene: "SourceID=187"
  981. };
  982. // 使用axios获取二维码并保存到文件
  983. const qrCodeResponse = await axios({
  984. method: 'POST',
  985. url: qrCodeUrl,
  986. data: postData,
  987. responseType: 'stream'
  988. });
  989. // 创建写入流
  990. const writer = fs.createWriteStream(fullPath);
  991. // 将响应数据写入文件
  992. qrCodeResponse.data.pipe(writer);
  993. // 返回成功响应
  994. ctx.body = { errcode: 10000, message: "二维码生成请求已发送" };
  995. // 处理文件写入完成事件
  996. writer.on('finish', () => {
  997. console.log("二维码生成成功:", fullPath);
  998. });
  999. // 处理错误
  1000. writer.on('error', (err) => {
  1001. console.error("二维码文件写入失败:", err);
  1002. });
  1003. } catch (error) {
  1004. console.error("生成二维码失败:", error);
  1005. ctx.status = 500;
  1006. ctx.body = {
  1007. errcode: 500,
  1008. errStr: '生成二维码失败',
  1009. error: error.message
  1010. };
  1011. }
  1012. }
  1013. export async function GetWordChinese(ctx) {
  1014. const param = {
  1015. UserID: ctx.query.UserID || 0,
  1016. Word: ctx.query.Word || '',
  1017. Level: ctx.query.Level || '0'
  1018. };
  1019. if (!param.Word) {
  1020. ctx.body = {"errcode": 10001, "errStr": "单词不能为空"};
  1021. return;
  1022. }
  1023. // 使用单词作为缓存键,为每个单词单独缓存结果
  1024. const cacheKey = `GetWordChinese_${param.Word}_${param.Level}`;
  1025. let result = globalCache.get(cacheKey);
  1026. if (!result) {
  1027. // 缓存未命中,从数据库获取
  1028. result = await yjbdc.GetWordChinese(param);
  1029. // 如果没有找到结果,尝试查找单词的原形
  1030. if (!result || result.length === 0) {
  1031. // 使用stringUtils.getWordBaseForm获取可能的原形
  1032. const possibleBaseWords = stringUtils.getWordBaseForm(param.Word);
  1033. // 尝试每个可能的原形
  1034. for (const baseWord of possibleBaseWords) {
  1035. //console.log(`尝试查找单词 ${param.Word} 的可能原形: ${baseWord}`);
  1036. const baseParam = {...param, Word: baseWord};
  1037. const baseResult = await yjbdc.GetWordChinese(baseParam);
  1038. if (baseResult && baseResult.length > 0) {
  1039. //console.log(`找到单词 ${param.Word} 的原形 ${baseWord}`);
  1040. result = baseResult;
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. // 缓存结果,使用较长的过期时间,因为单词释义很少变化
  1046. if (result && result.length > 0) {
  1047. globalCache.set(cacheKey, result, config.BufferMemoryTimeHighBest);
  1048. //console.log(`缓存单词 ${param.Word} 的释义,7天有效期`);
  1049. }
  1050. }
  1051. // 根据Level筛选合适的单词释义
  1052. let selectedResult = null;
  1053. if (result && result.length > 0) {
  1054. // 将Level转换为数字
  1055. const level = parseInt(param.Level);
  1056. // 根据不同Level筛选结果
  1057. if (level >= 0 && level <= 2) {
  1058. // Level 0-2,返回数组单词第一条
  1059. const filtered = result.filter(item => item.BookID >= 151);
  1060. if (filtered.length > 0) {
  1061. selectedResult = filtered[0];
  1062. } else {
  1063. // 如果没有符合条件的,返回BookID较小的第一条
  1064. selectedResult = result[0];
  1065. }
  1066. } else if (level === 3) {
  1067. // Level 3,优选返回BookID >= 169的
  1068. const filtered = result.filter(item => item.BookID >= 169);
  1069. if (filtered.length > 0) {
  1070. selectedResult = filtered[0];
  1071. } else {
  1072. // 如果没有符合条件的,返回BookID较大的第一条
  1073. result.sort((a, b) => b.BookID - a.BookID);
  1074. selectedResult = result[0];
  1075. }
  1076. } else if (level === 4) {
  1077. // Level 4,优选返回BookID >= 173的
  1078. const filtered = result.filter(item => item.BookID >= 173);
  1079. if (filtered.length > 0) {
  1080. selectedResult = filtered[0];
  1081. } else {
  1082. // 如果没有符合条件的,返回BookID较大的第一条
  1083. result.sort((a, b) => b.BookID - a.BookID);
  1084. selectedResult = result[0];
  1085. }
  1086. } else if (level === 5) {
  1087. // Level 5,优选返回BookID >= 178的
  1088. const filtered = result.filter(item => item.BookID >= 178);
  1089. if (filtered.length > 0) {
  1090. selectedResult = filtered[0];
  1091. } else {
  1092. // 如果没有符合条件的,返回BookID较大的第一条
  1093. result.sort((a, b) => b.BookID - a.BookID);
  1094. selectedResult = result[0];
  1095. }
  1096. }
  1097. // 移除 BookID 字段
  1098. if (selectedResult) {
  1099. delete selectedResult.BookID;
  1100. }
  1101. }
  1102. ctx.body = {"errcode": 10000, result: selectedResult};
  1103. }
  1104. export async function YJBDC_Articles_Admin(ctx) {
  1105. //console.log("yjbdc_articles");
  1106. const data = await fsPromises.readFile("./public/mg/yjbdc_articles.html");
  1107. ctx.body = data.toString();
  1108. };