article_generator.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import common from '../../utils/util';
  2. import main from '../../utils/main';
  3. import constant1 from '../../utils/constant';
  4. Page({
  5. data: {
  6. wordList: [],
  7. selectedWords: [],
  8. difficulty: 0,
  9. difficulties: constant1.arrHardLevel,
  10. articleStyles: constant1.arrArticleStyle,
  11. articleStyle: '',
  12. generatedArticle: '',
  13. articleTranslation: '',
  14. generating: false,
  15. Content:"",
  16. },
  17. onLoad: function(options) {
  18. let that=this;
  19. that.setData({
  20. Containnerheight: main.getWindowHeight(),
  21. IsShowTranslate:false,
  22. });
  23. let words=options.words;
  24. if (!options.words)
  25. words="boy,girl,king,come,go,yellow,dragon,fire";
  26. if (words) {
  27. try {
  28. const wordList = words.split(",");
  29. this.setData({ wordList });
  30. } catch (e) {
  31. wx.showToast({
  32. title: '数据加载失败',
  33. icon: 'none'
  34. });
  35. }
  36. }
  37. },
  38. onDifficultyChange: function(e) {
  39. this.setData({
  40. difficulty: Number(e.detail.value)
  41. });
  42. },
  43. onArticleStyleChange: function(e) {
  44. this.setData({
  45. articleStyle: e.detail.value
  46. });
  47. console.log('选择的文章类型:', e.detail.value);
  48. },
  49. generateArticle: async function() {
  50. let that=this;
  51. if (!this.data.articleStyle) {
  52. wx.showToast({
  53. title: '请选择文章类型',
  54. icon: 'none'
  55. });
  56. return;
  57. }
  58. this.setData({
  59. generating: true,
  60. Content:""
  61. });
  62. try {
  63. let url = common.Encrypt("GenerateArticle");
  64. //url="https://www.kylx365.com/apiData/"+url;
  65. url="http://localhost:3020/api/GenerateArticle";
  66. let words=that.data.wordList;
  67. const cloudRes = await new Promise((resolve, reject) => {
  68. wx.request({
  69. url: url,
  70. method: "POST",
  71. data: {
  72. Words:JSON.stringify(words),
  73. Level:that.data.difficulty,
  74. Style:that.data.articleStyle
  75. },
  76. success: resolve,
  77. fail: reject,
  78. })
  79. });
  80. //console.log(cloudRes);
  81. let result=cloudRes.data.result.choices[0].message.content;
  82. console.log(result);
  83. let content=JSON.parse(result);
  84. //console.log(content);
  85. for(let i=0;i<content.ArticleEnglish.length;i++){
  86. for(let j=0;j<content.FormsOfWords.length;j++){
  87. let word = content.FormsOfWords[j];
  88. let regex = new RegExp(`\\b${word}\\b[.,!?;:]?`, 'gi');
  89. content.ArticleEnglish[i] = content.ArticleEnglish[i].replace(regex, match => {
  90. let punctuation = match.match(/[.,!?;:]$/);
  91. let punc = punctuation ? punctuation[0] : '';
  92. let wordPart = match.replace(/[.,!?;:]$/, '');
  93. return `<span class='highlight'>${wordPart}</span>${punc}`;
  94. });
  95. }
  96. }
  97. content.ArticleEnglishStr=content.ArticleEnglish.join("");
  98. for(let i=0;i<content.Question.length;i++){
  99. for(let j=0;j<content.Question[i].OptionsEnglish.length;j++){
  100. let str=content.Question[i].OptionsChinese[j];
  101. content.Question[i].OptionsChinese[j]=str.substr(2);
  102. }
  103. }
  104. this.setData({
  105. Content:content,
  106. generating: false
  107. });
  108. } catch (error) {
  109. console.error('生成文章失败:', error);
  110. wx.showToast({
  111. title: '生成文章失败',
  112. icon: 'none'
  113. });
  114. this.setData({ generating: false });
  115. }
  116. },
  117. showTranslate:function(e){
  118. this.setData({
  119. IsShowTranslate:!this.data.IsShowTranslate,
  120. })
  121. },
  122. generateTestArticle:function(e){
  123. this.setData({
  124. Content:{
  125. Title: "Sample Reading Article",
  126. ArticleEnglishStr:"This is a <span>sample</span> article for testing the PDF generation functionality.It contains multiple paragraphs and some <span>bold text</span> to test formatting.The PDF should be generated with proper layout and styling.",
  127. ArticleEnglish: [
  128. "This is a <span>sample</span> article for testing the PDF generation functionality.",
  129. "It contains multiple paragraphs and some <span>bold text</span> to test formatting.",
  130. "The PDF should be generated with proper layout and styling."
  131. ],
  132. Question: [
  133. {
  134. QuestionEnglish: "What is the purpose of this article?",
  135. OptionsEnglish: [
  136. "A. To test PDF generation",
  137. "B. To teach English",
  138. "C. To demonstrate formatting",
  139. "D. All of the above"
  140. ]
  141. },
  142. {
  143. QuestionEnglish: "What special formatting is used in this article?",
  144. OptionsEnglish: [
  145. "A. Italics",
  146. "B. Bold text",
  147. "C. Underline",
  148. "D. Strikethrough"
  149. ]
  150. }
  151. ]
  152. },
  153. })
  154. },
  155. //生成PDF文件
  156. //访问服务器的GeneratePDF接口,提交this.data.Content数据,获得一个生成好的pdf文件,服务端的代码已经生成好
  157. generatePDF: function(e) {
  158. let that = this;
  159. this.setData({
  160. generatingPDF: true,
  161. });
  162. let url = common.Encrypt("GeneratePDF");
  163. url = "https://www.kylx365.com/apiData/" + url;
  164. //url="http://localhost:3020/api/GeneratePDF";
  165. wx.request({
  166. url: url,
  167. method: "POST",
  168. data: {
  169. Content: that.data.Content
  170. },
  171. responseType: 'arraybuffer', // 确保响应类型为arraybuffer
  172. success: function(res) {
  173. // 将arraybuffer转为临时文件
  174. const fsm = wx.getFileSystemManager();
  175. const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.pdf`;
  176. try {
  177. fsm.writeFileSync(
  178. tempFilePath,
  179. res.data,
  180. 'binary'
  181. );
  182. // 直接使用临时文件路径,不再尝试永久保存
  183. console.log('文件已生成:', tempFilePath);
  184. // 打开PDF文件预览
  185. wx.openDocument({
  186. filePath: tempFilePath,
  187. fileType: 'pdf',
  188. showMenu: true, // 显示右上角菜单,可以分享
  189. success: function() {
  190. console.log('打开文档成功');
  191. wx.showToast({
  192. title: 'PDF生成成功',
  193. icon: 'success'
  194. });
  195. },
  196. fail: function(error) {
  197. console.error('打开文档失败:', error);
  198. wx.showToast({
  199. title: '打开文件失败',
  200. icon: 'none'
  201. });
  202. }
  203. });
  204. } catch (error) {
  205. console.error('写入文件失败:', error);
  206. wx.showToast({
  207. title: '写入文件失败',
  208. icon: 'none'
  209. });
  210. }
  211. },
  212. fail: function(err) {
  213. console.error('请求GeneratePDF接口失败:', err);
  214. wx.showToast({
  215. title: '网络错误,请稍候重试',
  216. icon: 'none'
  217. });
  218. },
  219. complete: function() {
  220. that.setData({ generatingPDF: false });
  221. }
  222. });
  223. },
  224. });