import common from '../../utils/util';
import main from '../../utils/main';
import constant from '../../utils/constant';

const app = getApp();

const arrStudyPlan = ["日常","紧急"];

var innerAudioContext1;

var listTaskFinished = []; //完成的任务
var timeStart; //计算时长
var timeHistory = 0; //已经过去的时间
var TaskList = [];
var arrImage = [],
  arrImage2 = [];
var intervalSound = 0,
  intervalRefresh = 0;
var isCollecting = false;
var isExit = true;

var isPlaying = false;

var timeoutPlayAudio;
var tempPlayUrl = "";
var tempPlayUrlLocal = "";
var timeoutEveryCard = 0;
var timeoutHide = 0;

var cardTypeName="";

Page({
  data: {
    ImagePath: app.globalData.uploadImageUrl,
    NumberNew: 10,
    NumberReview: 0,
    NumberHistory: 30,
    IsShowNumberInfo: false,
    IsMore: false,
    FontSizeArray: constant.arrFontSize,
    StudyPlanArray: arrStudyPlan,
    TaskInfo: {},
    Color: {ID: 1},
  },
  onReady: function () {
    var that = this;
    innerAudioContext1 = wx.createInnerAudioContext();
    innerAudioContext1.onPlay(() => {
      console.log('开始播放')
    });
    innerAudioContext1.onError((res) => {
      console.log("innerAudioContext1.errMsg:" + res.errMsg);
      console.log("innerAudioContext1.errCode:" + res.errCode);
      that.audioCtx.setSrc(tempPlayUrl);
      that.audioCtx.play();
    });

    common.getStorageValue(that, "HasSound", true, function () {
      wx.setStorageSync("HasSound", that.data.HasSound);
    });
  },
  onLoad: function (options) {
    var that = this;
    var height = app.globalData.systemInfo.screenHeight * 2 - 90;
    var height2 = 750;
    if (app.globalData.IsIPad) {
      height = 960;
      height2 = 670;
      that.setData({
        IsIPad: "_iPad",
      });
    }

    var cardType = options.CardType;
    if (!cardType)
      cardType = 0;
    cardTypeName=constant.arrStudyPattern[cardType]+"练习";
    this.setData({
      CardTypeName: cardTypeName,
    });

    that.setData({
      Containnerheight: height,
      Containnerheight2: height - height2,
      IsShowAnswer: [0, 0],
      CanUndo: 1,
      TaskInfo: {},
      ClickType: app.globalData.ClickType,
      Color: main.getDetailColor(app.globalData.ColorIndex),
    });

    this.audioCtx = wx.createAudioContext('myAudio');


    this.getList();

    this.getColor();

    this.getMemoryLevel();
 

    if (app.globalData.BaiduToken === "")
      main.getBaiduToken();

    if (app.globalData.IsOppo){
      that.setData({
        TextSpace:"nbsp",
      });
    }

  },
  onShow: function () {
    var that = this;
    if (that.data.NumberNew == 0 &&
      that.data.NumberReview == 0 &&
      that.data.NumberHistory == 0) {

      that.setData({
        CanUndo: 0,
        TaskInfo: {},
      });
      listTaskFinished = [];
      that.getTaskTime();
    } else {
      that.setSoundFile(-1);

      var list = app.globalData.CardList;
      if (list && list.length > 0) {
        for (var i = 0; i < list.length; i++) {
          if (TaskList && TaskList[0] && TaskList[0].MiaoguoCardID == list[i].MiaoguoCardID) {
            TaskList[0].Content = list[i].Content;
            TaskList[0].ContentNew = main.changeStringToView(list[i].Content);
            that.setData({
              TaskInfo: TaskList[0],
            });
            app.globalData.CardList = [];
            break;
          }
        }
      }
    }

    
    if (that.data.IsMore){
      //关于更改学习计划后处理
      if (app.globalData.IsUpdateStudyPlan == 1){
        that.gotoNext({ currentTarget: { dataset: { btnnumber:-2}}});
        app.globalData.IsUpdateStudyPlan = 0;
      }
      that.setData({
        IsMore: false,
      });
    }
    
    
    clearTimeout(timeoutHide);
    //console.log("显示");
  },
  onUnload: function () {
    clearInterval(intervalSound);
    clearTimeout(timeoutEveryCard);
    clearTimeout(timeoutHide);
    listTaskFinished = [];

    isPlaying = false;
    if (innerAudioContext1) {
      innerAudioContext1.stop();
    }
  },
  onHide: function (e) {
    //console.log("隐藏");
    var that = this;
    if (isExit) {
      timeoutHide = setTimeout(function () {
        that.onClose();
      }, 60000);
    }
    isExit = true;
  },
  onPullDownRefresh: function () {
    this.onShowAnswer({
      currentTarget: {
        dataset: {
          start: true
        }
      }
    });
    wx.stopPullDownRefresh();
  },
  setSoundFile: function (isFinish) { 
    //isFinish=3搁置 =2撤退 =1结束 =0正常 =-1开始
    var that = this;
    if (that.data.HasSound){
      var url = "/pages/sounds/";
      if (isFinish == 1) {
        url += "end.mp3";
      } else if (isFinish == 2) {
        url += "short3.mp3";
      } else if (isFinish == 3) {
        url += "short1.mp3";
      } else {
        url += "short2.mp3";
      }
      if (isFinish >= 0) {
        innerAudioContext1.src = url;
        innerAudioContext1.play();
      }
    }

    wx.pageScrollTo({
      scrollTop: 0,
    });
  },
  getColor: function () {
    var that = this;

    if (wx.setBackgroundColor) {
      wx.setBackgroundColor({
        backgroundColor: that.data.Color.BackColor,
        backgroundColorTop: that.data.Color.BackColor,
        backgroundColorBottom: that.data.Color.BackColor,
      });
    }
    if (wx.setNavigationBarColor) {
      wx.setNavigationBarColor({
        frontColor: "#ffffff",
        backgroundColor: that.data.Color.BackColor,
      })
    }

  },
  getList: function () {
    var task = app.globalData.TaskToday;
    var that = this;
    var arrNew = task.ListNew;
    var arrHistory = task.ListHistory;
    var listTaskReview = task.ListReview;

    var nMax = [1, 1];
    if (arrNew.length == 0 || arrHistory.length == 0) {
      if (arrNew.length == 0) {
        nMax[0] = 0;
      }
      if (arrHistory.length == 0) {
        nMax[1] = 0;
      }
    } else if (arrNew.length >= arrHistory.length) {
      nMax[0] = Math.floor(arrNew.length / arrHistory.length);
    } else if (arrNew.length < arrHistory.length) {
      nMax[1] = Math.floor(arrHistory.length / arrNew.length);
    }

    arrNew = common.randomArray(arrNew);
    arrHistory = common.randomArray(arrHistory);

    var Len = arrNew.length + arrHistory.length;
    TaskList = [];
    var indexNew = 0,
      indexHistory = 0;
    for (var i = 0; i < Len; i++) {
      for (var j = 0; j < nMax[0]; j++) {
        if (indexNew < arrNew.length) {
          arrNew[indexNew].IsNew = true;
          TaskList.push(arrNew[indexNew++]);
        }
      }
      for (var j = 0; j < nMax[1]; j++) {
        if (indexHistory < arrHistory.length) {
          arrHistory[indexHistory].IsHistory = true;
          TaskList.push(arrHistory[indexHistory++]);
        }
      }
    }

    that.data.NumberReview = listTaskReview.length;
    for (var i = 0; i < listTaskReview.length; i++) {
      listTaskReview[i].IsReview = true;

      TaskList.push(listTaskReview[i]);
    }

    TaskList = updateNumberStr(TaskList);

    //处理列表
    TaskList = formatList(TaskList);

    if (TaskList.length > 0) {
      arrImage = TaskList[0].ContentNew.Images;
      arrImage2 = TaskList[0].ContentNew.Images2;
    }

    var taskInfo = TaskList[0];
    if (!taskInfo)
      taskInfo = {};

    that.setData({
      NumberNew: arrNew.length,
      NumberReview: that.data.NumberReview,
      NumberHistory: arrHistory.length,
      TaskInfo: taskInfo,
      CanUndo: 0,
    });

    listTaskFinished = [];
    that.timeCompute(); //起始时间

    function formatList(list) {
      for (var i = 0; i < list.length; i++) {
        if (list[i].Content) {
          list[i].ContentNew = main.changeStringToView(list[i].Content);
          list[i].TagWidth = 0;
          if (list[i].ContentNew.Tags && list[i].ContentNew.Tags.length > 0) {
            list[i].TagWidth = 92 + (list[i].ContentNew.Tags.length - 1) * 122;
            for (var j = 0; j < list[i].ContentNew.Tags.length; j++) {
              if (list[i].ContentNew.Tags[j].length > 2) {
                list[i].TagWidth += 46 * (list[i].ContentNew.Tags[j].length - 2);
              }
            }
          }
        }

      }
      return list;
    }

    function updateNumberStr(list) {
      for (var i = 0; i < list.length; i++) {
        if (list[i].Number0)
          list[i].Number0Str = main.getMemoryLevel(app.globalData.MemoryLevel, 0, list[i].Number0);
        if (list[i].Number1)
          list[i].Number1Str = main.getMemoryLevel(app.globalData.MemoryLevel, 1, list[i].Number1);
        if (list[i].Number2)
          list[i].Number2Str = main.getMemoryLevel(app.globalData.MemoryLevel, 2, list[i].Number2);
        if (list[i].Number3)
          list[i].Number3Str = main.getMemoryLevel(app.globalData.MemoryLevel, 3, list[i].Number3);;
      }
      return list;
    }
  },

  onShowAnswer: function (e) {
    var clicktype = e.currentTarget.dataset.type;
    if (!(clicktype && clicktype == "all" && app.globalData.ClickType == 0)) {

      var start = e.currentTarget.dataset.start;
      var that = this;
      if (!(that.data.NumberNew == 0 &&
        that.data.NumberReview == 0 &&
        that.data.NumberHistory == 0) && !that.data.IsShowNumberInfo) {

        var recommend = 0;
        if (start) {
          that.data.IsShowAnswer[0] = 0;
          that.data.IsShowAnswer[1] = 0;
        } else {
          if (!that.data.IsShowAnswer)
            that.data.IsShowAnswer=[0,0];
          if (that.data.IsShowAnswer[0]==0 && that.data.IsShowAnswer[1]==0) {
            that.data.IsShowAnswer[0] = 1;
            if (TaskList[0].ContentNew.Field[3].length == 0) {
              that.data.IsShowAnswer[1] = 1;
              if (!that.data.TaskInfo.IsNew)
                recommend = getRecommendTime();
              that.setData({
                Recommend: recommend,
              });
            }
          } else if (that.data.IsShowAnswer[0] && !that.data.IsShowAnswer[1]) {
            that.data.IsShowAnswer[1] = 1;
            if (!that.data.TaskInfo.IsNew)
              recommend = getRecommendTime();
            that.setData({
              Recommend: recommend,
            });
          }
        }
        that.setData({
          IsShowAnswer: that.data.IsShowAnswer,
        });

        if (that.data.IsShowAnswer[1]){
          var query = wx.createSelectorQuery().in(that)
          query.select('#ViewField3').boundingClientRect(function(res){
            if (res && res.top && res.top>130)
              scroll(res.top-130);
          }).exec();
        }
      }

      function scroll(top) {
        wx.pageScrollTo({
          scrollTop: top,
        });
      }

      function getRecommendTime() {
        if (app.globalData.SecondConfigArray[0] > 0) {
          var duration = common.diffDate("s", timeStart, new Date());
          if (duration <= app.globalData.SecondConfigArray[0])
            return 3;
          else if (duration <= app.globalData.SecondConfigArray[1])
            return 2;
          else if (duration <= app.globalData.SecondConfigArray[2])
            return 1;
          else
            return 0;
        } else
          return 0;
      }
    }
  },
  gotoEdit: function () {
    var that = this;
    //console.log(res.tapIndex);
    var list = [];
    list.push(TaskList[0]);
    app.globalData.CardList = list;
    wx.navigateTo({
      url: './add?type=edit1&id=' + TaskList[0].MiaoguoCardID,
    });
    isExit = false;
    clearTimeout(timeoutEveryCard);
  },
  onFontSize: function (e) {
    var value = e.currentTarget.dataset.value;
    TaskList[0].FontSize = value;
    this.setData({
      TaskInfo: TaskList[0],
      IsMore: false,
    });
  },
  //回到上一张题卡
  gotoPrev: function () {
    var that = this;

    if (listTaskFinished.length > 0) {
      var card = listTaskFinished.pop();
      wx.setStorageSync("ListTaskFinished", listTaskFinished);

      timeHistory = 0;
      that.timeCompute();

      card.Card.Number0 = card.Number0Old;
      card.Card.Number0Str = card.Number0StrOld;
      card.Card.Number1 = card.Number1Old;
      card.Card.Number1Str = card.Number1StrOld;
      card.Card.Number2 = card.Number2Old;
      card.Card.Number2Str = card.Number2StrOld;
      card.Card.Number3 = card.Number3Old;
      card.Card.Number3Str = card.Number3StrOld;

      if (card.IsReviewOld)
        card.Card.IsReview = card.IsReviewOld;

      //去除重复
      for (var i = 0; i < TaskList.length; i++) {
        if (TaskList[i].MiaoguoCardID == card.Card.MiaoguoCardID) {
          TaskList.splice(i, 1);
        }
      }

      TaskList.unshift(card.Card);
      var canUndo = 1;
      if (listTaskFinished.length == 0)
        canUndo = 0;

      arrImage = TaskList[0].ContentNew.Images;
      arrImage2 = TaskList[0].ContentNew.Images2;

      that.setData({
        IsShowAnswer: [0, 0],
        TaskInfo: TaskList[0],
        NumberNew: card.NumberNew,
        NumberReview: card.NumberReview,
        NumberHistory: card.NumberHistory,
        CanUndo: canUndo,
        Recommend: 0,
      });

      wx.showToast({
        title: '回到上一张',
        image: "../images/universalpic_undo_white_120x90.png",
      });
      that.setSoundFile(2);
    }
  },
  //进入下一张题卡
  gotoNext: function (e) {
    var that = this;
    //btnnumber可以有 5:秒过 4正常 3困难 2挪到最后 1搁置 0不过 -1今天要练 -2更改计划
    var btnnumber = e.currentTarget.dataset.btnnumber;
    //若是“挪到最后”
    if (btnnumber == 2) {
      var card = TaskList.splice(0, 1);
      card[0].IsFinally=true;
      card[0].LimitTime=common.formatTime(new Date(),"/",true)+" 23:59:59";
      TaskList.push(card[0]);
      that.setData({
        IsShowAnswer: [0, 0],
        TaskInfo: TaskList[0],
        CanUndo: 1,
        Recommend: 0,
        IsMore: false,
      });
    }
    else{
      var time = e.currentTarget.dataset.time;
      //处理当前卡片进入历史数组
      var finishCard = {};
      finishCard.Card = TaskList[0];

      finishCard.NumberNew = this.data.NumberNew;
      finishCard.NumberReview = this.data.NumberReview;
      finishCard.NumberHistory = this.data.NumberHistory;

      finishCard.Number0Old = TaskList[0].Number0;
      finishCard.Number0StrOld = TaskList[0].Number0Str;
      finishCard.Number1Old = TaskList[0].Number1;
      finishCard.Number1StrOld = TaskList[0].Number1Str;
      finishCard.Number2Old = TaskList[0].Number2;
      finishCard.Number2StrOld = TaskList[0].Number2Str;
      finishCard.Number3Old = TaskList[0].Number3;
      finishCard.Number3StrOld = TaskList[0].Number3Str;

      
      //若是当前题卡更改学习计划
      if (btnnumber==-2) {
        for (var i = 0,flag=true; i < listTaskFinished.length;flag?i++:i){
          if (listTaskFinished[i].Card.MiaoguoCardID==finishCard.Card.MiaoguoCardID){
            listTaskFinished.splice(i,1);
            flag=false;
          }
          else
            flag=true;
        }
      }
      else{
        //若不是搁置
        //算出下一次的时间
        if (btnnumber != "1") {

          //若是分钟，则进入复习列表
          if (time.lastIndexOf("m") == time.length - 1) {
            var minute = Number(time.substr(0, time.indexOf("m")));
            TaskList[0].LimitTime = common.formatTime(common.addDate("n", minute, new Date()));
            //若是新建，则10m 1d 4d
            if (TaskList[0].IsNew) {
              if (minute == 1) {
                TaskList[0].Number0 = "1m";
                TaskList[0].Number2 = "10m";
              }
              else {
                TaskList[0].Number0 = "10m";
                TaskList[0].Number2 = "1d";
              }

              TaskList[0].Number0Str = main.getMemoryLevel(app.globalData.MemoryLevel, 0, TaskList[0].Number0);
              TaskList[0].Number2Str = main.getMemoryLevel(app.globalData.MemoryLevel, 2, TaskList[0].Number2);

              delete TaskList[0].Number1;
              delete TaskList[0].Number1Str;

              delete TaskList[0].Number3;
              delete TaskList[0].Number3Str;

              TaskList[0].FirstTime = null;
              TaskList[0].LastTime = null;
            }
            //若是历史的，则10m 1d
            else if (TaskList[0].IsHistory) {
              TaskList[0].Number0 = "10m";
              TaskList[0].Number0Str = main.getMemoryLevel(app.globalData.MemoryLevel, 0, TaskList[0].Number0);

              delete TaskList[0].Number1;
              delete TaskList[0].Number1Str;

              TaskList[0].Number2 = "1d";
              TaskList[0].Number2Str = main.getMemoryLevel(app.globalData.MemoryLevel, 2, TaskList[0].Number2);

              delete TaskList[0].Number3;
              delete TaskList[0].Number3Str;
            }

            finishCard.IsReviewOld = TaskList[0].IsReview;

            TaskList[0].IsReview = true;
            TaskList.push(TaskList[0]);
          }
          //若是天月年
          else {
            var dayNum = Number(time.substr(0, time.indexOf("d")));
            var date = common.addDate("d", dayNum, new Date());
            TaskList[0].LimitTime = common.formatTime(date);
          }

        }

        //修改学习任务个数
        var learningType = 0;
        if (TaskList[0].IsReview) {
          learningType = 2;
        }
        if (TaskList[0].IsNew) {
          learningType = 0;
        } else if (TaskList[0].IsHistory) {
          learningType = 1;
        }

        if (btnnumber == "1") {
          learningType = 3;
        }

        finishCard.IntervalTime = time;
        finishCard.BtnNumber = btnnumber;
        finishCard.LearningType = learningType;

        var duration = common.diffDate("s", timeStart, new Date());
        if (finishCard.btnnumber == 1)
          duration = 0;
        finishCard.Duration = timeHistory + duration;

        console.log("CardTime:" + finishCard.Duration);

        timeHistory = 0;
        that.timeCompute();

        finishCard.LastTime=common.formatTime(new Date());
        //添加完成列表，去掉任务列表数据
        listTaskFinished.push(finishCard);
      }

      wx.setStorageSync("ListTaskFinished", listTaskFinished);
      TaskList.shift();

      that.data.NumberNew = 0;
      that.data.NumberHistory = 0;
      that.data.NumberReview = 0;
      for (var i = 0; i < TaskList.length; i++) {
        if (TaskList[i].IsReview) {
          if (TaskList[i].LimitTime < common.formatTime(new Date())) {
            var card = TaskList.splice(i, 1);
            TaskList.unshift(card[0]);
          }
          that.data.NumberReview++;
        } else if (TaskList[i].IsNew) {
          that.data.NumberNew++;
        } else if (TaskList[i].IsHistory) {
          that.data.NumberHistory++;
        }
        if (TaskList[i].IsFinally){
          var card = TaskList.splice(i, 1);
          TaskList.push(card[0]);
        }
      }

      //console.log(JSON.stringify(TaskList[0]));
      //如果所有任务完成
      if (that.data.NumberNew == 0 &&
        that.data.NumberReview == 0 &&
        that.data.NumberHistory == 0) {
        that.setData({
          IsShowAnswer: [0, 0],
          NumberNew: 0,
          NumberReview: 0,
          NumberHistory: 0,
          CanUndo: 1,
          Recommend: 0,
          IsMore: false,
        });
        clearTimeout(timeoutEveryCard);
        that.setSoundFile(1);
        main.UpdateMiaoguoCardTodayAll(true, function () {
          listTaskFinished = [];
          that.getTaskTime();
        });

      }
      //没有完成任务
      else {
        arrImage = TaskList[0].ContentNew.Images;
        arrImage2 = TaskList[0].ContentNew.Images2;

        //任务没有完成，下一张卡片
        that.setData({
          IsShowAnswer: [0, 0],
          TaskInfo: TaskList[0],
          NumberNew: that.data.NumberNew,
          NumberReview: that.data.NumberReview,
          NumberHistory: that.data.NumberHistory,
          CanUndo: 1,
          Recommend: 0,
          IsMore: false,
        });

        if (btnnumber == "1") {
          that.setSoundFile(3);
          if (time == "1d") {
            wx.showToast({
              title: '搁置一天',
              mask: true,
              image: "../images/universalpic_shelve_white_120x120.png",
            });
          } else {
            wx.showToast({
              title: '已推迟',
              mask: true,
              image: "../images/universalpic_bell_white_120x120.png",
            });
          }
        } else
          that.setSoundFile(0);
      }
    }
  },
  timeCompute: function () {
    var that = this;
    timeStart = new Date();
    clearTimeout(timeoutEveryCard);
    timeoutEveryCard = setTimeout(function () {
      //计算暂停时已经用掉的时长
      timeHistory += common.diffDate("s", timeStart, new Date());
      console.log("timeHistory:" + timeHistory);

      if (!(that.data.NumberNew == 0 &&
        that.data.NumberReview == 0 &&
        that.data.NumberHistory == 0)){
          wx.showModal({
            title: '提醒',
            content: '您已等待了' + app.globalData.CardWaitTimeMax + '分钟',
            showCancel: false,
            confirmText: "知道了",
            success(res) {
              clearTimeout(timeoutEveryCard);
              if (res.confirm) {
                that.timeCompute();
              }
            },
          });
        }
      
    }, app.globalData.CardWaitTimeMax * 60 * 1000);
  },
  gotoCollect: function () {
    var that = this;
    if (!isCollecting) {
      isCollecting = true;
      setTimeout(function () {
        isCollecting = false;
      }, 3000);
      var that = this;
      if (!TaskList[0].IsCollect) {
        TaskList[0].IsCollect = 1;
      } else {
        TaskList[0].IsCollect = 0;
      }
      that.setData({
        TaskInfo: TaskList[0],
      });
      main.setCollect(TaskList[0].MiaoguoCardID, TaskList[0].IsCollect);
    }
  },
  playSound: function (e) {
    clearTimeout(timeoutPlayAudio);

    var that = this;
    var str = e.currentTarget.dataset.content;
    var url;
    if (str == "recorder") {
      url = e.currentTarget.dataset.soundmark;
    } else if (str.indexOf("英 [") >= 0 || str.indexOf("美 [") >= 0) {
      str = str.replace("英 [", "[");
      str = str.replace("美 [", "[");
      url = e.currentTarget.dataset.soundmark;
    } else if (e.currentTarget.dataset.soundmark && e.currentTarget.dataset.soundmark != "undefined") {
      var soundmark = e.currentTarget.dataset.soundmark;
      if (soundmark && soundmark.indexOf("http") < 0) {
        url = app.globalData.audioUrlBaidu;
        url = url.replace("[token]", app.globalData.BaiduToken);
        url = url.replace("[word]", soundmark);
      } else {
        url = soundmark;
      }
    } else {
      url = app.globalData.audioUrlBaidu;
      url = url.replace("[token]", app.globalData.BaiduToken);
      url = url.replace("[word]", str);
    }


    if (url.indexOf("http") > 0)
      url = url.substr(url.indexOf("http"));
    if (url.indexOf("'") > 0)
      url = common.ReplaceAllString(url, "'", "");
    url = url.replace("http://", "https://");

    url = encodeURI(url);
    if (!isPlaying || tempPlayUrl == "" || url != tempPlayUrl) {
      isPlaying = true;
      timeoutPlayAudio = setTimeout(function () {
        isPlaying = false;
      }, 60000);

      wx.showLoading({
        title: '音频下载中',
        mask: true,
      });
      setTimeout(function () {
        wx.hideLoading();
      }, 30000);

      wx.downloadFile({
        url: url,
        success(res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            tempPlayUrlLocal = res.tempFilePath;
            that.audioCtx.setSrc(res.tempFilePath);
            that.audioCtx.play();
            tempPlayUrl = url;
          }
        },
        fail(err) {
          wx.hideLoading();
        }
      });
    } else {
      this.audioCtx.pause();
      if (innerAudioContext1)
        innerAudioContext1.stop();
      isPlaying = false;
    }
  },
  audioBindEnded: function () {
    isPlaying = false;
  },
  audioBindError: function (err) {
    console.log(err);
    innerAudioContext1.src = tempPlayUrlLocal;
    innerAudioContext1.play();
  },
  getTaskTime: function () {
    var that = this;
    var url = "GetMiaoguoTaskTime?";
    url += "UserID=" + app.globalData.userInfo.UserID;
    main.getData(url, function (data) {
      if (data) {
        var duration = data.Duration;
        if (duration > 0) {
          duration = Math.round(duration / 60);
        }

        var speed1 = 0;
        if (data.Duration > 0)
          speed1 = Math.round(100 * data.Count / (data.Duration / 60)) / 100;

        var speed2 = 0 + "秒";
        if (data.Count > 0)
          speed2 = common.getMinuteSecond(Math.round(data.Duration / data.Count), true);


        app.globalData.TaskToday.DayNumber = data.DayNumber;
        that.setData({
          TodayTime: duration,
          Speed1: speed1 + "张题卡",
          Speed2: speed2,
          CardTypeName:"报告",
        });

      }
    });
  },
  showNumberContainner: function () {
    this.setData({
      IsShowNumberInfo: true,
    });
    this.setData({
      CardTypeName:"进度",
    });
  },
  closeNumberContainner: function () {
    this.setData({
      IsShowNumberInfo: false,
      IsMore: false,
    });
    this.setData({
      CardTypeName: cardTypeName,
    });
  },
  showImage: function (e) {
    var name = e.currentTarget.dataset.name;
    if (name && name.length > 5) {
      wx.previewImage({
        current: name,
        urls: arrImage
      });
    }
  },
  onBindError: function (e) {
    var that = this;
    var serverUrl = e.currentTarget.dataset.serverurl;
    var oldTempUrl = e.currentTarget.dataset.name;
    //console.log("serverUrl1:" + serverUrl);
    wx.downloadFile({
      url: serverUrl, // 仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          //console.log("serverUrl2:" + serverUrl);
          //console.log(res.tempFilePath);
          main.saveTempImage(serverUrl, res.tempFilePath);
          for (var i = 0; i < arrImage.length; i++) {
            if (arrImage[i] == oldTempUrl) {
              arrImage[i] = res.tempFilePath;
            }
          }
        }
      }
    });

    clearTimeout(intervalRefresh);
    intervalRefresh = setTimeout(function () {
      TaskList[0].ContentNew = main.changeStringToView(TaskList[0].Content);
      that.setData({
        TaskInfo: TaskList[0],
      });
    }, 1000);

    for (var i = 1; i < this.data.TaskInfo.ContentNew.Field.length; i++) {
      for (var j = 0; j < this.data.TaskInfo.ContentNew.Field[i].length; j++) {
        if (this.data.TaskInfo.ContentNew.Field[i][j].Type == "image") {
          this.data.TaskInfo.ContentNew.Field[i][j].Url = this.data.TaskInfo.ContentNew.Field[i][j].Content;
        }
      }
    }
    this.setData({
      TaskInfo: this.data.TaskInfo,
    });
  },
  onMore: function () {
    for (var i = 0; i < this.data.FontSizeArray.length; i++) {
      if (this.data.FontSizeArray[i].Value == this.data.TaskInfo.FontSize)
        this.data.FontSizeArray[i].CSS = "color:#1E1E1E;background-color:" + this.data.Color.LineColor + ";border:3rpx solid " + this.data.Color.LineColor + ";";
      else
        this.data.FontSizeArray[i].CSS = "";
    }
    this.setData({
      IsMore: true,
      FontSizeArray: this.data.FontSizeArray,
    });
  },
  onClose: function () {
    wx.navigateBack({
      delta: 1,
    });
  },
  getMemoryLevel: function () {
    var index = wx.getStorageSync("MemoryLevel");
    if (!index) {
      index = 0;
    }
    if (index>1)
      index=1;
    app.globalData.MemoryLevel = index;
    this.setData({
      MemoryLevel:index,
    });
  },

  buildShareImage: function () {
    var that = this;
    wx.showLoading({
      title: '生成中',
    });
    setTimeout(function () {
      wx.hideLoading();
    }, 5000);
    //console.log(app.globalData.userInfo.AvatarUrl);
    var avatarUrl = app.globalData.userInfo.AvatarUrl;
    avatarUrl = avatarUrl.substring(0, avatarUrl.lastIndexOf("/") + 1);
    avatarUrl = avatarUrl + "0";
    //console.log(avatarUrl);

    wx.downloadFile({
      url: avatarUrl, // 仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          var canvas = wx.createCanvasContext("shareCanvas", that);
          canvas.setFillStyle(main.getShareImageBackColor());
          canvas.fillRect(360, 0, 600, 360);
          canvas.drawImage(res.tempFilePath, 0, 0, 360, 360);
          canvas.drawImage("../images/universalpic_screenshot_jl_bgimage_360x360.png", 0, 0, 360, 360);
          canvas.fillStyle = "#ffffff";
          canvas.setTextBaseline('top');
          canvas.setFontSize(24);
          canvas.fillText(app.globalData.userInfo.NickName, 30, 282);

          var today = common.formatTime(new Date(), ".", true);
          canvas.setFontSize(18);
          canvas.fillText(today, 30, 315);

          canvas.setFontSize(20);
          canvas.fillText("秒过学习", 390, 30);
          canvas.setFontSize(44);
          canvas.fillText("勤勉接力", 390, 58);
          canvas.setFontSize(20);
          canvas.fillText("见证成长", 390, 120);

          canvas.setFontSize(68);
          if (!that.data.TodayTime)
            that.data.TodayTime=0;
            
          canvas.fillText(that.data.TodayTime, 390, 148);

          canvas.font = "normal 500 68px caption";
          var metrics = canvas.measureText(that.data.TodayTime.toString());
          //console.log(JSON.stringify(metrics));

          var h = 179;
          if (app.globalData.IsIOS)
            h = 176;
          canvas.font = "normal 500 32px caption";
          canvas.fillText("分钟", 393 + Math.round(metrics.width), h);


          canvas.setFontSize(20);
          canvas.fillText("迄今已接力", 390, 267);
          canvas.setFontSize(32);
          canvas.fillText(app.globalData.TaskToday.DayNumber + "次", 390, 295);
          //console.log("生成前");
          canvas.draw(1, function (n) {
            //console.log("生成后1");
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 600,
              height: 360,
              destWidth: 600,
              destHeight: 360,
              canvasId: 'shareCanvas',
              success: function (res2) {
                wx.hideLoading();
                //console.log("生成后2");
                wx.previewImage({
                  current: res2.tempFilePath, // 当前显示图片的http链接
                  urls: [res2.tempFilePath] // 需要预览的图片http链接列表
                });

                main.getData("ShareMiaoguoTask?UserID=" + app.globalData.userInfo.UserID, function (data) { });
              },
              fail: function (e) {
                wx.hideLoading();
                //console.log("生成错误："+e);
              }
            })
          });
        } else {
          wx.hideLoading();
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  saveCardType:function(){
    var that=this;
    var url = 'UpdateMiaoguoCardType?UserID=' + app.globalData.userInfo.UserID;
    url += "&CardType=-1";
    url += "&ID=" + TaskList[0].MiaoguoCardID;
    main.getData(url, function (data) {
      TaskList.splice(0, 1);
      that.setData({
        TaskInfo: TaskList[0],
      });
      that.closeNumberContainner();
    });
  },
  goto: function (e) {
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    });
  },
  //获取导航栏高度
  getBarInfo(e) {
    var h=e.detail.topBarHeight;
    h=h*2;
    this.setData({ 
       topBarHeight: h,
    })
  },
  onShareAppMessage: function () {
    return {
      title: app.globalData.ShareTitle,
      path: app.globalData.SharePath + '?UserID=' + app.globalData.userInfo.UserID,
      imageUrl: app.globalData.ShareImage,
    }
  },
});