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

const app = getApp();
var intervalSound = 0, intervalRefresh = 0;
var arrImage = [];
var isCopying = false;
var isPlaying = false;
var isCollecting = false;
var playList = [];
var innerAudioContext1;
var timeoutPlayAudio;
var tempPlayUrl = "";
var tempPlayUrlLocal = "";

Page({
  data: {
    IsExistCard: false,
    Containnerheight:1440,
    IsShowMenu:false,
    TextSpace:"ensp",
    IsCardInfoCloseMenu:1,
    IsClickShowAnswer:false,
    Flag:0,
  },
  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();
    });
  },
  onLoad: function (options) {

    var that = this;
    isCopying = false;
    var id = 0;
    if (options.id)
      id = options.id;

    that.setData({
      Containnerheight: main.getWindowHeight(),
      ShowType: options.type,
      MiaoguoCardID: id,
      Color: main.getDetailColor(app.globalData.ColorIndex),
    });
    console.log("MiaoguoCardID:" + id);

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

    if (options.type == "show") {
      wx.setNavigationBarTitle({
        title: "浏览题卡"
      });

      if (wx.setBackgroundColor) {
        wx.setBackgroundColor({
          backgroundColor: that.data.Color.BackColor,
          backgroundColorTop: "#ffffff",
          backgroundColorBottom: that.data.Color.BackColor,
        })
      }
    }
    else {
      if (options.type == "share") {
        wx.setNavigationBarTitle({
          title: "来自分享"
        });
      }
      else if (options.type == "play") {
        wx.setNavigationBarTitle({
          title: "幻灯片"
        });
        if (that.data.ShowType == "play") {
          playList = [];
          for (var i = 0; i < app.globalData.CardList.length; i++) {
            playList.push(app.globalData.CardList[i].MiaoguoCardID);
          }
          playList = common.randomArray(playList);
          that.data.MiaoguoCardID = playList[0];
          that.setData({
            MiaoguoCardID: that.data.MiaoguoCardID,
            CurrentIndex: 0,
            PlayListCount: playList.length,
          });
        }
      }

      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,
        })
      }
    }

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

    

    if (options.PrintID){
      that.setData({
        PrintID:options.PrintID,
      });
    }
    else{
      common.getStorageValue(that, "IsCardInfoCloseMenu", 1, function () {
        if (options.type == "preview"){
          that.setData({
            IsCardInfoCloseMenu:1,
          });
        }
      });
    }

  },
  onShow: function () {
    var that = this;
    if (that.data.ShowType)
      if (that.data.ShowType == "share") {
        var url = "GetMiaoguoCardInfo?UserID=" + app.globalData.introducer + "&MiaoguoCardID=" + that.data.MiaoguoCardID;
        main.getData(url, function (data) {
          if (data) {
            app.globalData.CardList = [data];
            that.init();
          }
          else {
            var time = 2000;
            wx.showToast({
              title: '分享人已删除',
              mask: true,
              duration: time,
              complete: function () {
                setTimeout(function () {
                  wx.reLaunch({
                    url: './default?IsStart=1',
                  });
                }, time);
              }
            });
          }
        });
      }
      else
        that.init();
  },
  onUnload: function () {
    isPlaying = false;
    if (innerAudioContext1) {
      innerAudioContext1.stop();
    }
  },
  onPullDownRefresh: function () {
    var that = this;
    if (that.data.IsClickShowAnswer) {
      that.onHideAnswer();
    }
    wx.stopPullDownRefresh();
  },
  init: function () {
    var that = this;
    var list = app.globalData.CardList;
    if (app.globalData.CardList2){
      for(var i=0;i<app.globalData.CardList2.length;i++)
        list.push(app.globalData.CardList2[i]);
    }

    var card = {};
    var prevId = 0, nextId = 0;
    for (var i = 0; i < list.length; i++) {
      if (this.data.MiaoguoCardID == list[i].MiaoguoCardID) {
        if (i > 0)
          prevId = list[i - 1].MiaoguoCardID;
        else
          prevId = 0;
        if (i < list.length - 1)
          nextId = list[i + 1].MiaoguoCardID;
        else
          nextId = 0;

        card = main.changeStringToView(list[i].Content);
        card.MiaoguoCardID = list[i].MiaoguoCardID;
        card.LimitTime = list[i].LimitTime;
        card.FontSize = list[i].FontSize;
        card.IsCollect = list[i].IsCollect;
        card.CardType = list[i].CardType;
        card.FolderName=list[i].FolderName;
        card.Flag=list[i].Flag;
        break;
      }
    }
    if (!card.FontSize)
      card.FontSize = 48;

    arrImage = card.Images;

    //console.log("arrImage:" + arrImage);

    var limitTimeStr = common.formatDateCHS(card.LimitTime);

    var isTodayPractice = true;
    var task = app.globalData.TaskToday;
    if (task && task.ListNew && (task.ListNew.length > 0 || task.ListHistory.length > 0 || task.ListReview.length > 0)) {
      for (var i = 0; i < task.ListNew.length; i++) {
        if (task.ListNew[i].MiaoguoCardID == that.data.MiaoguoCardID) {
          isTodayPractice = false;
          break;
        }
      }
      for (var i = 0; i < task.ListHistory.length; i++) {
        if (task.ListHistory[i].MiaoguoCardID == that.data.MiaoguoCardID) {
          isTodayPractice = false;
          break;
        }
      }
      for (var i = 0; i < task.ListReview.length; i++) {
        if (task.ListReview[i].MiaoguoCardID == that.data.MiaoguoCardID) {
          isTodayPractice = false;
          break;
        }
      }
    }

    var TagWidth = 0;
    if (card.Tags && card.Tags.length > 0) {
      TagWidth = 92 + (card.Tags.length - 1) * 122;
      for (var j = 0; j < card.Tags.length; j++) {
        if (card.Tags[j].length > 2) {
          TagWidth += 46 * (card.Tags[j].length - 2);
        }
      }
    }

    if (that.data.IsClickShowAnswer) {
      that.onHideAnswer();
    }
    else{
      that.onShowAnswer();
    }
    
    this.setData({
      ID: card.MiaoguoCardID,
      CardType:card.CardType,
      Field: card.Field,
      Tags: card.Tags,
      FontSize:card.FontSize,
      TagWidth: TagWidth,
      PrevID: prevId,
      NextID: nextId,
      FontSize: card.FontSize,
      LimitTime: card.LimitTime,
      LimitTimeStr: limitTimeStr,
      IsTodayPractice: isTodayPractice,
      IsCollect: card.IsCollect,
      FolderName:card.FolderName,
      Flag:card.Flag,
    });

    wx.pageScrollTo({
      scrollTop: 0,
    });

    isPlaying = false;

    if (app.globalData.TempStr=="deleteCard"){
      that.deleteCard();
      app.globalData.TempStr="";
    }
  },
  copyCard: function () {
    if (!isCopying) {
      isCopying = true;
      setTimeout(function () {
        isCopying = false;
      }, 15000);

      wx.showLoading({
        title: '处理中',
      });
      setTimeout(function () {
        wx.hideLoading();
      }, 5000);
      var that = this;
      var url = "CollectMiaoguoCard?";
      url += "MiaoguoCardID=" + that.data.MiaoguoCardID;
      url += "&UserIDSource=" + app.globalData.introducer;
      url += "&UserIDTarget=" + app.globalData.userInfo.UserID;

      main.getData(url, function (data) {
        wx.hideLoading();

        var title = "题卡已存在！";
        var image = "universalpic_wrong_white_120x120";
        if (data == 1) {
          title = "已保存";
          image = "universalpic_saved_white_120x120";
        }
        wx.showToast({
          title: title,
          mask: true,
          image: "../images/" + image + ".png",
          duration: 2000,
          success: function () {
            that.setData({
              IsExistCard: true,
            });
          }
        });
      });
    }
  },
  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,
      });
      var timeout=setTimeout(function () {
        wx.hideLoading();
      }, 30000);
      console.log(url);
      wx.downloadFile({
        url: url,
        success(res) {
          clearTimeout(timeout);
          wx.hideLoading();
          if (res.statusCode === 200) {
            tempPlayUrlLocal = res.tempFilePath;
            that.audioCtx.setSrc(res.tempFilePath);
            that.audioCtx.play();
            tempPlayUrl = url;
          }
          //console.log("res.statusCode:" + res.statusCode);
        },
        fail(err) {
          wx.hideLoading();
          console.log("downling err:"+err);
          clearTimeout(timeout);
        }
      });
    }
    else {
      this.audioCtx.pause();
      if (innerAudioContext1)
        innerAudioContext1.stop();
      isPlaying = false;
    }
  },
  goto: function (e) {
    var url=e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    });
  },
  audioBindEnded:function(){
    isPlaying = false;
  },
  audioBindError: function (err) {
    //console.log(err);
    innerAudioContext1.src = tempPlayUrlLocal;
    innerAudioContext1.play();
  },
  getDetailInfo: function () {
    this.setData({
      IsShowMenu:false,
    });
    wx.navigateTo({
      url: './cardInfo?id=' + this.data.MiaoguoCardID,
    });
  },
  deleteCard: function () {
    var that = this;
    wx.showModal({
      title: '提醒',
      content: '确定删除吗？一定时间内可以在「回收」里找回。',
      success(res) {
        if (res.confirm) {
          var url = 'DeleteMiaoguoCard?UserID=' + app.globalData.userInfo.UserID;
          url += "&ID=" + that.data.MiaoguoCardID;
          main.getData(url, function (data) {
            var list = app.globalData.CardList;
            for (var i = 0; i < list.length; i++) {
              if (that.data.MiaoguoCardID == list[i].MiaoguoCardID) {
                list.splice(i, 1);
                break;
              }
            }
            app.globalData.CardList = list;

            var taskToday = app.globalData.TaskToday;
            taskToday.CardNumber--;
            app.globalData.TaskToday = taskToday;

            wx.navigateBack({
              delta: 1,
            });
          });
        }
      }
    });
  },
  previewNext: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      MiaoguoCardID: id,
    });
    that.init();
  },

  close: function () {
    wx.navigateBack({
      delta: 1,
    });
  },
  editField: function (e) {
    if (this.data.ShowType == "show") {
      var that = this;
      var strType="edit";
      if (e.currentTarget.dataset.type)
        strType="edit1";
      var url='./add?type='+strType+'&id=' + that.data.MiaoguoCardID+"&opentype="+e.currentTarget.dataset.type;
      wx.navigateTo({
        url: url,
      });
    }
  },
  gotoCollect: function () {
    var that = this;
    if (!isCollecting) {
      isCollecting = true;
      setTimeout(function () {
        isCollecting = false;
      }, 3000);

      if (!that.data.IsCollect) {
        that.data.IsCollect = 1;
      }
      else {
        that.data.IsCollect = 0;
      }
      that.setData({
        IsCollect: that.data.IsCollect
      });
      main.setCollect(that.data.MiaoguoCardID, that.data.IsCollect, function () {
        var list = app.globalData.CardList;
        for (var i = 0; i < list.length; i++) {
          if (that.data.MiaoguoCardID == list[i].MiaoguoCardID) {
            list[i].IsCollect = that.data.IsCollect;
            break;
          }
        }
      });
    }
  },  
  setClickShowAnswer: function () {
    this.setData({
      IsClickShowAnswer:true,
      IsShowAnswer: [0, 0],
      IsShowMenu:false,
    });
  },
  setAlwaysShowAnswer: function () {
    this.setData({
      IsClickShowAnswer:false,
      IsShowAnswer: [1, 1],
      IsShowMenu:false,
    });
  },
  onHideAnswer: function () {
    this.setData({
      IsShowAnswer: [0, 0],
    });
  },
  onShowAnswer: function () {
    this.setData({
      IsShowAnswer: [1, 1],
    });
  },
  onPlayAgain: function () {
    playList.push(this.data.MiaoguoCardID);
    this.setData({
      PlayListCount: playList.length,
      NextID: 1,
    });
    wx.showToast({
      title: '稍后回放',
      mask: true,
      duration: 500,
    });
  },
  playNext: function (e) {
    var that = this;
    var div = e.currentTarget.dataset.div;
    if (div == 1) {
      this.data.CurrentIndex++;
      if (this.data.CurrentIndex >= playList.length) {
        this.data.CurrentIndex = playList.length - 1;
      }
    }
    else {
      this.data.CurrentIndex--;
      if (this.data.CurrentIndex < 0)
        this.data.CurrentIndex = 0;
    }
    that.setData({
      CurrentIndex: this.data.CurrentIndex,
      MiaoguoCardID: playList[this.data.CurrentIndex],
      PlayListCount: playList.length,
    });
    that.init();
  },
  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 () {
      that.init();
    }, 1000);
  },
  returnDefault: function () {
    wx.reLaunch({
      url: './default?IsStart=1',
    });
  },
  btnMore:function(){
    this.setData({
      IsShowMenu: true,
    });
  },
  closeMenu:function(){
    this.setData({
      IsShowMenu: false,
    });
  },
  closeIsCardInfoCloseMenu:function(){
    this.setData({
      IsCardInfoCloseMenu: 1,
    });
    wx.setStorageSync('IsCardInfoCloseMenu', 1);
  },
  openIsCardInfoCloseMenu:function(){
    this.setData({
      IsCardInfoCloseMenu: 0,
    });
    wx.setStorageSync('IsCardInfoCloseMenu', 0);
  },
  onShareAppMessage: function () {
    var that = this;
    this.setData({
      ShowType: 'sharepreview',
      IsCardInfoCloseMenu: 1,
    });

    var url = 'ShareMiaoguoCard?UserID=' + app.globalData.userInfo.UserID;
    url += "&MiaoguoCardID=" + that.data.MiaoguoCardID;
    main.getData(url, function (data) { });

    setTimeout(function () {
      that.setData({
        ShowType: 'show',
      });
      common.getStorageValue(that, "IsCardInfoCloseMenu", 1, function () {});

    }, 1000);
    return {
      title: '我的分享',
      path: app.globalData.SharePath + '?UserID=' + app.globalData.userInfo.UserID + '&type=share&ColorIndex=' + app.globalData.ColorIndex + '&MiaoguoCardID=' + this.data.MiaoguoCardID,
    }
  },
})
