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,
    IsShowRemind:false,
    remindAnimation: "", // 翻译弹窗动画类
    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,
    });

    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);
      }
    });
  },
  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('GenerateArticle?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){
        if (data=="-1"){
          that.setData({
            IsBuildError:true,
            CreateTime:common.formatDateCHS(common.formatTime(new Date()),true),
          });
        }
        else{
          that.updateData(data.Content);
          that.setData({
            IsBuilding:false,
            ID:data.ID,
            IsNew:data.IsNew,
          });
        }
        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+)'([^']+)'/g, '$1"$2"');
      
      // 将句子按空格分割成单词数组
      let words = sentence.trim().split(/\s+/);
      let wordObjects = [];
      
      // 处理每个单词，检查是否需要高亮
      for(let j=0; j<words.length; j++){
        let word = words[j];
        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;
    }
    that.setData({
      Content:content,
    });
    setTimeout(function(){
      that.updateReadCount(that.data.ID);
    },3000);
  },
  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);
  },

  onContainerTap: function() {
    const currentTime = new Date().getTime();
    const lastTapTime = this.data.lastTapTime;
    const timeDiff = currentTime - lastTapTime;
    
    // 如果两次点击的时间间隔小于300毫秒，则认为是双击
    if (timeDiff < 300 && timeDiff > 0) {
      console.log('双击事件触发');
      // 在这里添加双击事件的处理逻辑
      // 例如：切换翻译显示状态
      this.showData({currentTarget:{dataset:{name:"IsShowTranslate"}}});
    }
    
    // 更新上一次点击的时间
    this.setData({
      lastTapTime: currentTime
    });
  },
    //生成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"){
      wx.removeStorageSync('IsShowGuideContainer');
      app.globalData.SelectedWords=[];
      wx.navigateBack({
        delta: 1,
      });
    } 
  },
  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,
    });
    // 使用动画工具函数显示弹窗，并指定显示动画
    animation.toggleRemindWithAnimation(this, {
      showAnimation: 'remind-slide-up'
    });
  },
  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);
    
    if (css){
      let list=that.data.Content.FormsOfWords;
      for(let i=0;i<list.length;i++){
        if(list[i].toLowerCase() == originalWord.toLowerCase()){
          console.log(that.data.Content.FormsOfWordsChinese[i]);
        }
      }
    }
  },
  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();
  },
  showRemind:function(e){
    animation.toggleRemindWithAnimation(this, {
      showAnimation: 'remind-slide-down'
    });
  },
  goto: function (e) {
    let that=this;
    var url=e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    });
  },
  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,
    }
  },
})