| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660 |
- import common from '../../utils/util';
- import main from '../../utils/main';
- import animation from '../../utils/animation';
- import commonBehavior from '../behaviors/commonBehavior';
- const Theme=[{
- "Name":"DarkColor",
- "backgroundColor": "#004433",
- "color":"#C1E1C1",
- "frontColor": '#ffffff',
- },{
- "Name":"LightColor",
- "backgroundColor": "#D0ECD3",
- "color":"#151815",
- "frontColor": '#000000',
- }
- ];
- const app = getApp();
- Page({
- behaviors: [commonBehavior],
- data: {
- Words:"",
- IsShowFirstOpen:true,
- IsBuilding:false,
- IsBuildError:false,
- IsShowLightColor:false,
- IsShowKeyword:true,//显示关键词
- IsShowQuestion:false,
- IsShowTranslate:false,
- IsShowSetting:false,
- IsShowWordTranslate:false,
- IsBuildQueue:false,
- TranslateHeight:100,//翻译单词框的高度
- CurrentQuestionIndex:0,
- swiperHeight: "526rpx",
- lastTapTime: 0, // 记录上一次点击的时间,用于检测双击
- CountDown:30,//倒计时秒数
- },
- onLoad: function (options) {
- let that = this;
- let words=app.globalData.SelectedWords.join(",");
- let wordsStr=app.globalData.SelectedWords.join(" ");
-
- const IsShowFirstOpen2=wx.getStorageSync('IsShowFirstOpen2');
- const IsShowGuideContainer=wx.getStorageSync('IsShowGuideContainer');
- if (!IsShowGuideContainer && !IsShowFirstOpen2){
- that.setData({
- IsShowFirstOpen2:1,
- });
- }
- else if (IsShowGuideContainer){
- that.setData({
- IsShowGuideContainer:true,
- IsShowFirstOpen2:false,
- });
- main.showGuideContainer(that,"#btnQAndA",-61,-195,"pic_ha07",240,0);
- }
-
- let IsShowKeyword=wx.getStorageSync('IsShowKeyword');
- if (IsShowKeyword===""){
- IsShowKeyword=true;
- wx.setStorageSync('IsShowKeyword', true);
- }
- let IsShowLightColor=wx.getStorageSync('IsShowLightColor');
- if (!IsShowLightColor){
- IsShowLightColor=false;
- }
-
- that.setData({
- Containnerheight: main.getWindowHeight(),
- Words:words,
- WordsStr:wordsStr,
- Level:options.Level,
- ArticleStyle:options.ArticleStyle,
- AIVersion:options.AIVersion,
- OpenType:options.Type,//打开的类型,可能是新用户引导
- IsShowLightColor:IsShowLightColor,
- IsShowKeyword:IsShowKeyword,
- IsBuildError:false,
- IsBuilding:false,
- IsCollect:false,
- });
- if (options.ID)
- that.getArticleByID(options.ID);
- else
- that.init(options);
- that.setTheme();
- // //测试
- // that.setData({
- // IsBuilding:true,
- // });
- // that.getChoicenessArticle();
- main.checkGenerating();
- this.audioCtx = wx.createAudioContext('myAudio');
- },
- onShow:function(){
- main.getPageInfo();
- },
- getArticleByID:function(id){
- let that=this;
- main.getData('GetYJBDCArticleList?UserID=' + app.globalData.userInfo.UserID+'&ID='+id, function (data) {
- if (data) {
- data=data[0];
- that.setData({
- Words:data.Words,
- Level:data.Level,
- ArticleStyle:data.ArticleStyle,
- CreateTime:data.CreateTime,
- ID:id,
- });
- let content=data.JSONString;
- that.updateData(content);
- that.updateReadCount(that.data.ID);
- }
- });
- },
- init:function(options){
- let that=this;
- let interval=0;
- that.data.CountDown=options.BuildSecond;
- that.setData({
- CountDown:that.data.CountDown,
- });
- interval = setInterval(function(){
- that.setData({
- CountDown:--that.data.CountDown,
- });
- if (that.data.CountDown<=0)
- clearInterval(interval);
- },1200);
- that.setData({
- IsBuilding:true,
- IsNew:true,
- });
- app.globalData.Generating=true;
- let words=app.globalData.SelectedWords.join(",");
- main.postData('QueuedGenerateArticle?UserID='+app.globalData.userInfo.UserID, {
- Words:words,
- Level:that.data.Level,
- ArticleStyle:that.data.ArticleStyle,
- AIVersion:that.data.AIVersion
- }, function (data) {
- app.globalData.Generating=false;
- app.globalData.GeneratingStart=false;
- if (data){
- console.log("请求生成数据:"+JSON.stringify(data));
- if (data=="-1"){
- that.setData({
- IsBuilding:false,
- IsBuildError:true,
- IsBuildQueue:false,
- });
- }
- else if (data=="-2"){
- that.setData({
- IsBuilding:false,
- IsBuildError:false,
- IsBuildQueue:true,
- });
- }
- else{
- console.log("生成1");
- if (that.data.IsNew){
- console.log("生成2");
- that.updateData(data.Content);
- that.updateReadCount(that.data.ID);
- }
- that.setData({
- IsBuilding:false,
- ID:data.ID,
- CreateTime:common.formatDateCHS(common.formatTime(new Date()),true),
- });
-
- }
- clearInterval(interval);
- }
- });
- that.getChoicenessArticle();
- },
- updateReadCount:function(id){
- if (id!="MAX")
- main.getData('UpdateYJBDCArticleReadCount?UserID=' + app.globalData.userInfo.UserID+'&ID='+id, function (data) {});
- },
- //得到精选文章
- getChoicenessArticle:function(){
- let that=this;
- main.getData('GetYJBDCArticleList?IsFine=1', function (data) {
- if (data) {
- that.setData({
- ChoicenessList:data,
- });
- }
- });
- },
- updateData:function(content){
- let that=this;
- //console.log(content);
-
- // 添加检查,确保 content 不是 undefined
- if (!content) {
- console.error('Content is undefined in updateData');
- return;
- }
-
- if (typeof content === 'string') {
- content = JSON.parse(content);
- }
- if (typeof content === 'string') {
- content = JSON.parse(content);
- }
- let hl = that.data.IsShowKeyword ? "highlight" : "nonelight";
-
- // 初始化ArticleEnglishArr数组
- content.ArticleEnglishArr = [];
-
- for(let i=0; i<content.ArticleEnglish.length; i++){
- // 确保每个句子末尾有空格,避免和下一句紧挨着
- let sentence = content.ArticleEnglish[i] + " ";
- // 替换所有单引号为双引号,包括对话中的单引号和句尾的单引号
- sentence = sentence.replace(/(^|[,.;:!?\s])'([^']+)'([,.;:!?]|\s|$)/g, '$1"$2"$3');
-
- // 处理常见的带点缩写,将其中的点替换为特殊标记,以防止被分割
- // 1. 称谓缩写
- sentence = sentence.replace(/\b(Dr|Mr|Mrs|Ms|Prof)\./g, '$1@DOT@');
- // 2. 时间缩写
- sentence = sentence.replace(/\b([ap])\.m\./gi, '$1@DOT@m@DOT@');
- // 3. 学位缩写
- sentence = sentence.replace(/\b(B|M|Ph)\.([A-Z])\./gi, '$1@DOT@$2@DOT@');
- // 4. 公司名称缩写
- sentence = sentence.replace(/\b(Inc|Ltd|Co|Corp)\./g, '$1@DOT@');
- // 5. 拉丁缩写
- sentence = sentence.replace(/\b(e\.g|i\.e|etc|et al|vs)\./g, '$1@DOT@');
- // 6. 军衔缩写
- sentence = sentence.replace(/\b(Lt|Col|Gen|Sgt|Capt)\./g, '$1@DOT@');
- // 7. 地理缩写
- sentence = sentence.replace(/\b(St|Ave|Rd|Blvd)\./g, '$1@DOT@');
- // 8. 其他常见缩写
- sentence = sentence.replace(/\b(U\.S|U\.K|U\.N)\./g, '$1@DOT@');
-
- // 先处理破折号,在破折号前后添加空格,使其成为独立元素
- sentence = sentence.replace(/([^\s])([—\-–—])([^\s])/g, '$1 $2 $3');
-
- // 将句子按空格分割成单词数组
- let words = sentence.trim().split(/\s+/);
- let wordObjects = [];
-
- // 处理每个单词,检查是否需要高亮
- for(let j=0; j<words.length; j++){
- let word = words[j];
- // 检查是否是单独的破折号
- let isDash = /^[—\-–—]$/.test(word);
- let originalWord = word.replace(/[.,!?;:"'()—\-–—_]/g, ''); // 去除标点符号和特殊字符(包括各种破折号)
- let isHighlighted = false;
-
- // 检查单词是否在需要高亮的列表中
- for(let k=0; k<content.FormsOfWords.length; k++){
- if(originalWord.toLowerCase() === content.FormsOfWords[k].toLowerCase()){
- isHighlighted = true;
- break;
- }
- }
-
- // 添加单词对象到数组
- wordObjects.push({
- Sentence: word,
- CSS: isHighlighted ? hl : "",
- OriginalWord: originalWord
- });
- }
-
- // 将单词数组添加到ArticleEnglishArr
- content.ArticleEnglishArr.push(wordObjects);
- }
- for(let i=0;i<content.Question.length;i++){
- //console.log("i:"+i);
- for(let j=0;j<content.Question[i].OptionsEnglish.length;j++){
- content.Question[i].OptionsEnglish[j] = content.Question[i].OptionsEnglish[j].replace(/(^|[,.]\s+)'([^']+)'/g, '$1"$2"');
- if (j<4){//选项不能超过4个
- let str=content.Question[i].OptionsChinese[j];
- content.Question[i].OptionsChinese[j]=str.substr(2);
- }
- }
- let char = content.Question[i].Answer;
- let asciiCode = char.charCodeAt(0);
- content.Question[i].AnswerNumber=asciiCode-65;
- content.Question[i].IsShowAnswer=false;
- }
- // 在设置数据前,确保所有@DOT@都被替换回.
- that.replaceAllDOTMarkers(content);
-
- that.setData({
- Content:content,
- });
-
- },
- setTheme:function(){
- let that=this;
- const css=Theme[that.data.IsShowLightColor?1:0];
- wx.setNavigationBarColor({
- frontColor: css.frontColor,
- backgroundColor: css.backgroundColor,
- });
- wx.setBackgroundColor({
- backgroundColor: css.backgroundColor,
- backgroundColorTop:css.backgroundColor,
- backgroundColorBottom:css.backgroundColor,
- });
- that.setData({
- ThemeCSS:css.Name,
- });
- wx.setStorageSync('IsShowLightColor', that.data.IsShowLightColor);
- },
- selectedAnswer:function(e){
- let that=this;
- const question=e.currentTarget.dataset.question;
- const index=e.currentTarget.dataset.index;
- if (that.data.Content.Question[question].UserAnswer==index)
- that.data.Content.Question[question].UserAnswer=-1;
- else
- that.data.Content.Question[question].UserAnswer=index;
- that.setData({
- Content:that.data.Content,
- });
- },
- showData:function(e){
- let that=this;
- let name=e.currentTarget.dataset.name;
- this.data[name] = !this.data[name];
- this.setData(this.data);
- if (name=="IsShowKeyword"){
- that.setShowKeyword();
- }
- else if (name=="IsShowLightColor"){
- that.setTheme();
- }
- else if (name=="IsShowAnswer"){
- let index=e.currentTarget.dataset.index;
- let content=that.data.Content;
- content.Question[index].IsShowAnswer=!content.Question[index].IsShowAnswer;
- that.setData({
- Content:content,
- });
- }
- else if (name=="IsShowQuestion"){
- main.showGuideContainer(that,"#panelArticle",38,30,"pic_ha08",196,279);
- }
- },
- setShowKeyword:function(){
- let that=this;
- let content=that.data.Content;
- let source="highlight",target="nonelight";
- if (that.data["IsShowKeyword"]){
- source="nonelight";
- target="highlight";
- }
- for(let i=0;i<content.ArticleEnglishArr.length;i++){
- let obj=content.ArticleEnglishArr[i];
- let arr=[];
- for(let j=0;j<obj.length;j++){
- if (obj[j].CSS==source)
- obj[j].CSS=target;
- }
- }
- for(let i=0;i<content.ArticleEnglish.length;i++){
- content.ArticleEnglish[i]=common.ReplaceAllString(content.ArticleEnglish[i],source,target);
- }
- that.setData({
- Content:content,
- });
- wx.setStorageSync('IsShowKeyword', that.data.IsShowKeyword);
- },
- nextQuestion:function(e){
- if (this.data.CurrentQuestionIndex+1<this.data.Content.Question.length){
- this.data.CurrentQuestionIndex=this.data.CurrentQuestionIndex+1;
- this.setData({
- CurrentQuestionIndex:this.data.CurrentQuestionIndex,
- });
- }
- },
- updateQuestionIndex:function(e){
- this.setData({
- CurrentQuestionIndex:e.detail.current,
- });
- console.log(e.detail.current);
- },
- //生成PDF文件
- //访问服务器的GeneratePDF接口,提交this.data.Content数据,获得一个生成好的pdf文件,服务端的代码已经生成好
- generatePDF: function(e) {
- let that = this;
- //debugger;
- that.data.Content.Words=that.data.Words;
- that.data.Content.Level=that.data.Level;
- that.data.Content.ArticleStyle=that.data.ArticleStyle;
- that.data.Content.CreateTime=that.data.CreateTime;
- let url = common.Encrypt("GeneratePDF");
- url =app.globalData.serverUrl + url;
- wx.request({
- url: url,
- method: "POST",
- data: {
- Content: that.data.Content,
- },
- responseType: 'arraybuffer', // 确保响应类型为arraybuffer
- success: function(res) {
- // 将arraybuffer转为临时文件
- const fsm = wx.getFileSystemManager();
- let time=common.formatTime(new Date(),"-");
- time=common.ReplaceAllString(time,"-","");
- time=common.ReplaceAllString(time,":","");
- time=common.ReplaceAllString(time," ","_");
- time=time.substring(2,time.length-2);
- const tempFilePath = `${wx.env.USER_DATA_PATH}/语境背单词_${time}.pdf`;
-
- try {
- fsm.writeFileSync(
- tempFilePath,
- res.data,
- 'binary'
- );
- // 直接使用临时文件路径,不再尝试永久保存
- console.log('文件已生成:', tempFilePath);
-
- // 打开PDF文件预览
- wx.openDocument({
- filePath: tempFilePath,
- fileType: 'pdf',
- showMenu: true, // 显示右上角菜单,可以分享
- success: function() {
- },
- fail: function(error) {
- console.error('打开文档失败:', error);
- wx.showToast({
- title: '打开文件失败',
- icon: 'none'
- });
- }
- });
- } catch (error) {
- console.error('写入文件失败:', error);
- wx.showToast({
- title: '写入文件失败',
- icon: 'none'
- });
- }
- },
- fail: function(err) {
- console.error('请求GeneratePDF接口失败:', err);
- wx.showToast({
- title: '网络错误,请稍候重试',
- icon: 'none'
- });
- }
- });
- },
- // 处理导航栏返回按钮点击事件
- onUnload: function() {
- if ((this.data.IsNew || this.data.OpenType=="Guide") && !this.data.IsBuildError){
- wx.removeStorageSync('IsShowGuideContainer');
- app.globalData.SelectedWords=[];
- wx.navigateBack({
- delta: 1,
- });
- //判断用户是否离开
- this.setData({
- IsNew:false,
- });
- }
- this.setData({
- IsBuildQueue:false,
- });
- },
- onLongPress: function(e) {
- let that = this;
- let strType=e.currentTarget.dataset.strtype;
- let selectedIndex=e.currentTarget.dataset.index;
- let selectedIndex2=e.currentTarget.dataset.index2;
- let engSentence,chnSentence;
- if (strType=="article"){
- //console.log("选中的句子索引:", selectedIndex);
- //console.log("选中的句子:", that.data.Content.ArticleEnglish[selectedIndex]);
- engSentence=that.data.Content.ArticleEnglish[selectedIndex];
- chnSentence=that.data.Content.ArticleChinese[selectedIndex];
- }
- else if (strType=="question"){
- engSentence=that.data.Content.Question[selectedIndex].QuestionEnglish;
- chnSentence=that.data.Content.Question[selectedIndex].QuestionChinese;
- }
- else if (strType=="option"){
- engSentence=that.data.Content.Question[selectedIndex].OptionsEnglish[selectedIndex2];
- chnSentence=that.data.Content.Question[selectedIndex].OptionsChinese[selectedIndex2];
- }
- this.setData({
- EnglishSentence:engSentence,
- ChineseSentence:chnSentence,
- IsShowWordTranslate:true,
- TranslateHeight:240,
- });
- },
- selectWord:function(e){
- let that=this;
- let css=e.currentTarget.dataset.css;
- let word=e.currentTarget.dataset.word;
- let originalWord=e.currentTarget.dataset.originalWord || word;
-
- console.log("点击的单词:", originalWord);
- that.playAudio(originalWord);
-
- let b=false;
- if (css){
- let list=that.data.Content.FormsOfWords;
- for(let i=0;i<list.length;i++){
- if(list[i].toLowerCase() == originalWord.toLowerCase() && that.data.Content.FormsOfWordsChinese && that.data.Content.FormsOfWordsChinese[i]){
- let wordChinese=that.data.Content.FormsOfWordsChinese[i];
- // 直接更新翻译内容,不改变IsShowWordTranslate状态(如果已经是true)
- let updateData = {
- EnglishSentence: originalWord,
- ChineseSentence: wordChinese,
- };
- //debugger;
- // 只有当当前不显示翻译时,才设置IsShowWordTranslate为true
- if (!that.data.IsShowWordTranslate) {
- updateData.IsShowWordTranslate = true;
- }
- updateData.TranslateHeight=100;
- that.setData(updateData);
- b=true;
- break;
- }
- }
- }
- if (!b){
- that.getWordChinese(originalWord,function(wordTarget){
- // 准备更新数据
- let updateData = {};
- updateData.TranslateHeight=100;
- if (wordTarget){
- updateData.EnglishSentence = wordTarget.Word;
- updateData.ChineseSentence = wordTarget.Translate;
- }
- else{
- updateData.EnglishSentence = originalWord;
- updateData.ChineseSentence = "";
- }
- // 只有当当前不显示翻译时,才设置IsShowWordTranslate为true
- if (!that.data.IsShowWordTranslate) {
- updateData.IsShowWordTranslate = true;
- }
- that.setData(updateData);
- });
- }
- that.setData({
- IsCollect:false,
- });
- app.globalData.UserCollect.filter(function (item) {
- if (item.Word==originalWord){
- that.setData({
- IsCollect:true,
- });
- }
- });
- },
- getWordChinese:function(word,callback){
- let that=this;
- main.getData('GetWordChinese?UserID=' + app.globalData.userInfo.UserID+'&Word='+word+'&Level='+that.data.Level, function (data) {
- if (data) {
- callback(data);
- }
- else
- callback();
- });
- },
- saveUserCollect:function(e){
- let that=this;
- let word=e.currentTarget.dataset.word;
- main.getData('AddOrDeleteYJBDCUserCollect?UserID='+app.globalData.userInfo.UserID+'&Word='+word, function (data) {
- that.setData({
- IsCollect:!that.data.IsCollect,
- });
- app.globalData.UserCollect=data;
- });
- },
- playAudio: function (word) {
- var url = app.globalData.audioUrlBaidu;
- url = url.replace("[token]", app.globalData.BaiduToken);
- url = url.replace("[word]", word);
- this.audioCtx.setSrc(url);
- this.audioCtx.play();
- },
- hideWordTranslate: function() {
- console.log("IsShowWordTranslate:false");
- // 点击空白处时隐藏单词翻译
- this.setData({
- IsShowWordTranslate: false
- });
- },
-
- goto: function (e) {
- let that=this;
- var url=e.currentTarget.dataset.url;
- wx.navigateTo({
- url: url,
- });
- },
- // 替换Content对象中所有的@DOT@标记为.
- replaceAllDOTMarkers: function(obj) {
- if (!obj) return;
-
- // 如果是字符串,直接替换
- if (typeof obj === 'string') {
- return obj.replace(/@DOT@/g, '.');
- }
-
- // 如果是数组,递归处理每个元素
- if (Array.isArray(obj)) {
- for (let i = 0; i < obj.length; i++) {
- if (typeof obj[i] === 'string') {
- obj[i] = obj[i].replace(/@DOT@/g, '.');
- } else if (typeof obj[i] === 'object' && obj[i] !== null) {
- this.replaceAllDOTMarkers(obj[i]);
- }
- }
- return;
- }
-
- // 如果是对象,递归处理每个属性
- if (typeof obj === 'object') {
- for (let key in obj) {
- if (obj.hasOwnProperty(key)) {
- if (typeof obj[key] === 'string') {
- obj[key] = obj[key].replace(/@DOT@/g, '.');
- } else if (typeof obj[key] === 'object' && obj[key] !== null) {
- this.replaceAllDOTMarkers(obj[key]);
- }
- }
- }
- }
- },
- catchTouchMove: main.catchTouchMove,
- onShareAppMessage: function () {
- return {
- title: app.globalData.ShareTitle,
- path: app.globalData.SharePath + '?goto=article&ID='+this.data.ID+'&UserID=' + app.globalData.userInfo.UserID,
- }
- },
- })
|