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

const app = getApp();
var isEditSetting = [];//是否修改设置
var intervalAutoPage = 0;
var insertID = 0, hanziNumber = 0;
var isClickFinished = true;//可以点击学会了
var isClickReview = true;//可以点击要复习
Page({
  data: {
    IsAutoPlay: true,//是否自动播放
    IsAutoPage: false,//是否自动翻页
    SortTitle: "课本一致",//排序
    PlayChecked: "checked",
    PageChecked: "",
    IsFinished: false,//是否练会了
    arrIntervalSecond: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],//播放间隔秒数组
    audioPer: [0, 1, 3, 4],//音色
    IntervalSecondIndex: 2,//播放间隔秒数索引
    IsImageError: false,
    SpeakerArray: [{ name: "温柔姐姐(推荐)", value: "woman", isShow: true }, { name: "爽朗哥哥", value: "man", isShow: false }, { name: "古韵叔叔", value: "oldman", isShow: false }, { name: "可爱妹妹", value: "sister", isShow: false }],
    pinyinCss: "",
  },
  onLoad: function (options) {
    var bookID = options.bookid || 0;
    var unitID = options.unitid || 0;
    var wordID = options.wordid || 0;
    var indexID = options.indexID || 0;

    this.audioCtx = wx.createAudioContext('myAudio');
    hanziNumber = 0;
    isClickFinished = true;
    isClickReview = true;
    var isfinished = options.isfinished;
    if (!isfinished || isfinished == "false")
      isfinished = false;
    else if (isfinished == "true")
      isfinished = true;

    if (!options.Type) {
      options.Type = "normal";
    }

    this.setData({
      Height: common.getSystemHeight(),
      IsShowPrev: false,
      IsShowNext: true,
      CurrentIndex: wordID,
      IsFinished: isfinished,
      IsHelpPosition1: 0,
      IsReview: false,
      IsShowWordDetail: false,
      ShowMenu: "sort",
      UnitID: unitID,
      BookID: bookID,
      SelectedRandom: false,
      SpeakerTitle: this.data.SpeakerArray[0].name,
      SpeakerMan: 0,
      ShowPinyin: true,
      IsAudioLengthChecked: true,//显示组词播放音
      WordType: options.Type,
    });

    var that = this;
    common.getStorageValue(that, "IsAutoPlay", true, function () {
      common.getStorageValue(that, "IsAutoPage", false, function () {
        common.getStorageValue(that, "SelectedRandom", false, function () {
          common.getStorageValue(that, "ShowHanzi", true, function () {
            common.getStorageValue(that, "ShowPinyin", true, function () {
              common.getStorageValue(that, "IntervalSecondIndex", 2, function () {
                common.getStorageValue(that, "IsAudioLengthChecked", true, function () {
                  common.getStorageValue(that, "SpeakerMan", 0, function () {
                    that.settingPlay(null, that.data.IsAutoPlay);
                    that.settingPage(null, that.data.IsAutoPage);
                    that.settingSort(null, that.data.SelectedRandom.toString());
                    that.settingShowPinyin(null, that.data.ShowPinyin);
                    that.settingShowHanzi(null, that.data.ShowHanzi);
                    that.settingAudioLength(null, that.data.IsAudioLengthChecked);
                    that.settingSpeaker(null, that.data.SpeakerMan);
                    if (that.data.WordType == "normal")
                      that.init();
                    else if (that.data.WordType == "review")
                      that.initReview(indexID);
                    else if (that.data.WordType == "search")
                      that.initSearch();
                  });
                });
              });
            });
          });
        });
      });
    });

    common.getStorageValue(that, "IsHelpPosition1", 1, function () { });

    if (this.data.WordType == "normal")
      this.submitData();

    var systemInfo = wx.getSystemInfoSync();
    if (systemInfo.model) {
      if (systemInfo.model.indexOf("iPad") >= 0) {
        this.setData({
          pinyinCss: "pinyinCssIpad",
        })
      }
    }

    common.getStorageValue(this, "IsShare", 0, function () {
      if (that.data.IsShare == 0
        && app.globalData.userInfo.IsMember == 0
        && app.globalData.IsShow == 1
        && app.globalData.IsLocked == 1
      ) {
        wx.navigateTo({
          url: '../../package4/main/share',
        })
      }
    });
  },
  onShow: function (e) {
    if (app.globalData.IsSaveCustom) {
      isEditSetting.push("saveCustom");
      app.globalData.IsSaveCustom = false;
    }
  },
  onUnload: function () {
    clearInterval(intervalAutoPage);

    server.postData('UpdateHanziRecord', {
      RecordID: insertID,
      HanziNumber: hanziNumber,
    }, function (data) { });

    if (this.data.IsHelpPosition1 == 1) {
      this.setData({
        IsHelpPosition1: 2,
      });
      wx.setStorageSync('IsHelpPosition1', 2);
    }

    var IsRemindTest = wx.getStorageSync("IsRemindTest");
    if (!IsRemindTest)
      wx.setStorageSync('IsRemindTest', 1);
  },
  submitData: function (content) {
    if (app.globalData.userInfo && app.globalData.userInfo.UserID) {
      server.postData('AddHanziRecord', {
        UserID: app.globalData.userInfo.UserID,
        Category: this.data.BookID,
        Content: this.data.UnitID,
      }, function (data) {
        //console.log(data.insertId);
        insertID = data.insertId;
      });
    }
  },
  init: function () {
    var arr = JSON.parse(wx.getStorageSync("HanziAll"));
    var arrReview = wx.getStorageSync("ReviewList");
    var result;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].ID == this.data.BookID) {
        for (var j = 0; j < arr[i].Units.length; j++) {
          var item = arr[i].Units[j];
          if (item.ID == this.data.UnitID) {
            //查看用户有没有自定义
            var wordArr = wx.getStorageSync("UnitCustom");
            if (wordArr) {
              for (var k = 0; k < wordArr.length; k++) {
                if (wordArr[k].ID == this.data.UnitID) {
                  item.Words = wordArr[k].List;
                }
              }
            }
            for (var k = 0; k < item.Words.length; k++) {
              item.Words[k].PinyinAll = item.Words[k].Pinyin;
              if (item.Words[k].Pinyin.indexOf(",") > 0)
                item.Words[k].Pinyin = item.Words[k].Pinyin.substr(0, item.Words[k].Pinyin.indexOf(","));

              item.Words[k].WordUrl = app.globalData.imageUrl + "/images/hanzi" + item.Words[k].Name + ".jpg";

              item.Words[k].IsReview = false;
              for (var l = 0; l < arrReview.length; l++) {
                if (arrReview[l].Name == item.Words[k].Name) {
                  item.Words[k].IsReview = true;
                  break;
                }
              }
            }
            result = item;
            break;
          }
        }
        break;
      }
    }

    if (this.data.SelectedRandom) {
      result.Words = common.randomArray(result.Words);
    }

    var obj = {
      Title: result.Name,
      Title2: "到底了",
      IsEnd: true,
    }
    result.Words.push(obj);

    this.setData({
      List: result.Words,
    });

    this.restart(this.data.CurrentIndex);
    wx.setNavigationBarTitle({
      title: "练习"
    });
  },
  initReview: function (indexID) {
    var arrReview = wx.getStorageSync("ReviewList");
    for (var l = 0; l < arrReview.length; l++) {
      var item = arrReview[l];
      item.PinyinAll = item.Pinyin;
      if (item.Pinyin.indexOf(",") > 0)
        item.Pinyin = item.Pinyin.substr(0, item.Pinyin.indexOf(","));

      item.WordUrl = app.globalData.imageUrl + "/images/hanzi" + item.Name + ".jpg";
      item.IsReview = true;
    }
    var result = arrReview;

    if (this.data.SelectedRandom) {
      result = common.randomArray(result);
    }

    var wordArr = wx.getStorageSync("UnitCustom");
    if (wordArr) {
      for (var k = 0; k < wordArr.length; k++) {
        for (var n = 0; n < wordArr[k].List.length; n++) {
          for (var i = 0; i < result.length; i++) {
            if (wordArr[k].List[n].ID == result[i].ID) {
              result[i].CombineWords = wordArr[k].List[n].CombineWords;
              break;
            }
          }
        }
      }
    }

    var obj = {
      Title: "复习",
      Title2: "到底了",
      IsEnd: true,
    }
    result.push(obj);

    this.setData({
      List: result,
      CurrentIndex: indexID,
    });

    this.restart(this.data.CurrentIndex);

    wx.setNavigationBarTitle({
      title: "练习"
    });
  },
  initSearch: function () {
    var that = this;

    var result = wx.getStorageSync("CurrentSearchWord");
    result.WordUrl += "?" + new Date().getTime();
    result.PinyinAll = result.Pinyin;
    if (result.Pinyin && result.Pinyin.indexOf(",") > 0)
      result.Pinyin = result.Pinyin.substr(0, result.Pinyin.indexOf(","));


    var arr = JSON.parse(wx.getStorageSync("HanziAll"));
    var arrReview = wx.getStorageSync("ReviewList");
    var title = "汉字";
    for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr[i].Units.length; j++) {
        var item = arr[i].Units[j];
        for (var k = 0; k < item.Words.length; k++) {

          if (result.ID == item.Words[k].ID) {
            title = arr[i].Name.replace("识字能力", "");
            title += " " + item.Name;
          }
          result.IsReview = false;

          for (var l = 0; l < arrReview.length; l++) {
            if (arrReview[l].Name == result.Name) {
              result.IsReview = true;
              break;
            }
          }
        }
      }
    }

    var resultArr = [];
    resultArr.push(result);
    var obj = {
      IsEnd: true,
    }
    resultArr.push(obj);

    wx.setNavigationBarTitle({
      title: title
    });

    if (result.IsNew) {
      wx.showLoading({
        title: '加载中',
      })
      setTimeout(function () {
        wx.hideLoading();
        that.setData({
          List: resultArr,
        });
        that.restart(that.data.CurrentIndex);
      }, 1000);
    }
    else {
      that.setData({
        List: resultArr,
      });
      that.restart(that.data.CurrentIndex);
    }

  },
  playAudio: function (e) {
    //console.log("playAudio");
    var click = false;
    if (e && e.currentTarget.dataset.click)
      click = e.currentTarget.dataset.click;

    if (click && this.data.IsHelpPosition1 == 1) {
      this.setData({
        IsHelpPosition1: 2,
      });
      wx.setStorageSync('IsHelpPosition1', 2);
    }

    var url = app.globalData.audioUrlBaidu;
    url = url.replace("[token]", app.globalData.BaiduToken);
    url = url.replace("per=0", "per=" + this.data.audioPer[this.data.SpeakerMan]);

    if ((click || this.data.IsAutoPlay) && !(click && this.data.IsAutoPage)) {
      if (this.data.CurrentIndex == this.data.List.length - 1) {
        if (this.data.WordType == "review")
          url = url.replace("[word]", "本次复习" + this.data.List[this.data.CurrentIndex].Title2);
        else
          url = url.replace("[word]", "本章节" + this.data.List[this.data.CurrentIndex].Title2);
        url = url.replace("spd=3", "spd=4");
      }
      else {

        var pinyinItem = this.data.List[this.data.CurrentIndex].PinyinAll;

        if (pinyinItem) {
          var pinyinStr = "";
          if (pinyinItem.indexOf(",") > 0) {
            pinyinItem = pinyinItem.substr(0, pinyinItem.indexOf(","));
            if (e && e.currentTarget.dataset.pinyin)
              pinyinItem = e.currentTarget.dataset.pinyin;

            pinyinStr = "(" + pinyin.getPinyinName(pinyinItem) + ")";
          }

          var Name = this.data.List[this.data.CurrentIndex].Name;
          if (!this.data.IsAudioLengthChecked || (e && e.currentTarget.dataset.pinyin)) {
            url = url.replace("[word]", Name + pinyinStr);
            url = url.replace("spd=3", "spd=1");
          }
          else {
            var CombineWords = this.data.List[this.data.CurrentIndex].CombineWords;
            if (CombineWords)
              CombineWords = "，" + CombineWords.replace(Name, Name + pinyinStr) + "的(de5)" + Name;

            url = url.replace("[word]", Name + pinyinStr + CombineWords + pinyinStr);
          }
        }
      }
      url = encodeURI(url);
      this.audioCtx.setSrc(url);
      this.audioCtx.play();
    }
  },
  startAutoPage: function () {
    var that = this;
    clearInterval(intervalAutoPage);
    var second = this.data.arrIntervalSecond[this.data.IntervalSecondIndex] * 1000;
    //console.log("second:" + second);
    intervalAutoPage = setInterval(function () {
      that.nextHandler();
    }, second);
  },
  prevHandler: function () {
    if (this.data.IsShowPrev && !this.data.IsAutoPage) {
      var index = this.data.CurrentIndex;
      var isShowPrev = true;
      var isShowNext = true;

      index--;
      if (index <= 0) {
        index = 0;
        isShowPrev = false;
      }

      this.setCurrentWord(index, isShowPrev, isShowNext);

      this.playAudio();

      hanziNumber++;
    }
  },
  nextHandler: function (e) {
    if (e && e.currentTarget.dataset.status == "click" && this.data.IsAutoPage) {

    }
    else if (this.data.IsShowNext) {
      var index = this.data.CurrentIndex;
      var isShowPrev = true;
      var isShowNext = true;

      index++;
      if (index >= this.data.List.length - 1) {
        index = this.data.List.length - 1;
        isShowNext = false;
      }
      this.setCurrentWord(index, isShowPrev, isShowNext);

      this.playAudio();

      hanziNumber++;
    }
  },
  restart: function (index) {
    var that = this;
    if (!index)
      index = 0;

    var isShowPrev = true;
    if (index == 0)
      isShowPrev = false;

    this.setCurrentWord(index, isShowPrev, true);

    this.playAudio();
    hanziNumber++;

    if (this.data.IsAutoPage) {
      this.startAutoPage();
    }
  },
  startAutoPage: function () {
    var that = this;
    clearInterval(intervalAutoPage);
    var second = this.data.arrIntervalSecond[this.data.IntervalSecondIndex] * 1000;
    //console.log("second:" + second);
    intervalAutoPage = setInterval(function () {
      that.nextHandler();
    }, second);
  },
  setCurrentWord: function (index, isShowPrev, isShowNext) {
    var that = this;
    that.setData({
      CurrentIndex: index,
      IsShowPrev: isShowPrev,
      IsShowNext: isShowNext,
      IsShowWordDetail: false,
      ShowHanzi: wx.getStorageSync("ShowHanzi"),
    });
  },
  getImageError: function () {
    var that = this;
    that.setData({
      IsImageError: true,
    });
  },
  getImageDownload: function () {
    var that = this;
    wx.showLoading({
      title: '请稍等',
    })
    server.getData('SearchHanzi?Word=' + that.data.List[that.data.CurrentIndex].Name, function (data) {
      setTimeout(function () {
        wx.hideLoading();
        wx.redirectTo({
          url: "../main/detail?Type=" + that.data.WordType + "&bookid=" + that.data.BookID + "&unitid=" + that.data.UnitID + "&wordid=" + that.data.CurrentIndex + "&isfinished=" + that.data.IsFinished,
        });
      }, 5000);
    });
  },
  showWordDetailHandler: function (e) {
    var that = this;
    if (this.data.IsShowNext && !this.data.IsAutoPage) {
      this.data.IsShowWordDetail = !this.data.IsShowWordDetail;
      this.setData({
        IsShowWordDetail: this.data.IsShowWordDetail,
      });
      if (!this.data.IsShowWordDetail) {
        this.setData({
          Detail: null,
        });
      }
      if (this.data.IsShowWordDetail) {
        if (this.data.WordType == "search") {
          var result = wx.getStorageSync("CurrentSearchWord");
          result = JSON.parse(result.Details);
          for (var i = 0; i < result.PinYin.length; i++) {
            var item = result.PinYin[i].explain;
            item = common.ReplaceAllString(item, "<p>", "");
            item = common.ReplaceAllString(item, "<span>", "");
            item = common.ReplaceAllString(item, "</span>", "");
            item = common.ReplaceAllString(item, "\r", "");
            item = common.ReplaceAllString(item, "\n", "");

            var arr = item.split("</p>");
            arr.pop();
            result.PinYin[i].explain = arr;
          }
          result.Antonym = result.Antonym.join(" ");
          result.Synonym = result.Synonym.join(" ");
          that.setData({
            Detail: result,
          });
        }
        else {
          var id = e.currentTarget.dataset.id;
          server.getData('GetHanziDetail?ID=' + id, function (data) {
            if (data) {
              //var data = common.Decrypt(data);
              //data=JSON.parse(data);
              data.Antonym = data.Antonym.join(" ");
              data.Synonym = data.Synonym.join(" ");
              that.setData({
                Detail: data,
              });
            }
          });
        }
      }
    }
  },
  //显示设置菜单
  showSettingMenu: function (e) {
    var status = e.currentTarget.dataset.status;
    this.setData({
      isShowSettingMenu: true,
      ShowMenu: status,
    });
  },
  //打开设置界面
  openSetting: function () {
    this.setData({
      IsShowSetting: true,
    });
    isEditSetting = [];

    clearInterval(intervalAutoPage);
  },
  closeSetting: function () {
    var that = this;
    this.setData({
      IsShowSetting: false,
    });

    if (isEditSetting.length > 0) {
      for (var i = 0; i < isEditSetting.length; i++) {
        if (isEditSetting[i] == "page" || isEditSetting[i] == "saveCustom" || isEditSetting[i] == "sort") {
          if (isEditSetting[i] != "saveCustom")
            that.data.CurrentIndex = 0;

          if (that.data.WordType == "normal")
            that.init();
          else if (that.data.WordType == "review")
            that.initReview();

          break;
        }
        else if (isEditSetting[i] == "speaker") {
          that.playAudio();
          break;
        }
      }
    }
    else {
      if (this.data.IsAutoPage) {
        this.startAutoPage();
      }
    }
  },
  closeSettingMenu: function () {
    this.setData({
      isShowSettingMenu: false,
    });
  },

  settingSort: function (e, b) {
    isEditSetting.push("sort");
    var result = b;
    if (e)
      result = e.currentTarget.dataset.id;

    var title = "";
    var SelectedRandom = true;
    if (result == "false") {
      title = "课本一致";
      SelectedRandom = false;
    }
    else {
      title = "随机";
    }
    this.setData({
      isShowSettingMenu: false,
      SortTitle: title,
      SelectedRandom: SelectedRandom,
    });
    wx.setStorageSync('SelectedRandom', SelectedRandom);
  },
  settingSpeaker: function (e, b) {
    isEditSetting.push("speaker");
    var result = b;
    if (e)
      result = e.currentTarget.dataset.id;
    for (var i = 0; i < this.data.SpeakerArray.length; i++) {
      this.data.SpeakerArray[i].isShow = false;
      if (i == result)
        this.data.SpeakerArray[i].isShow = true;
    }

    this.setData({
      SpeakerMan: result,
      isShowSettingMenu: false,
      SpeakerTitle: this.data.SpeakerArray[result].name,
      SpeakerArray: this.data.SpeakerArray,
    });
    wx.setStorageSync('SpeakerMan', result);
  },
  settingShowHanzi: function (e, b) {
    var result = !this.data.ShowHanzi;
    if (b != undefined)
      result = b;
    this.setData({
      ShowHanzi: result,
    });
    wx.setStorageSync('ShowHanzi', result);
  },
  showHanziFunction: function () {
    this.setData({
      ShowHanzi: true,
    });
  },
  settingShowPinyin: function (e, b) {
    var result = !this.data.ShowPinyin;
    if (b != undefined)
      result = b;
    this.setData({
      ShowPinyin: result,
    });
    wx.setStorageSync('ShowPinyin', result);
  },
  settingPlay: function (e, b) {
    isEditSetting.push("play");
    var result = !this.data.IsAutoPlay;
    if (b != undefined)
      result = b;

    var PlayChecked = "";
    if (result)
      PlayChecked = "checked";
    this.setData({
      IsAutoPlay: result,
      isShowSettingMenu: false,
      PlayChecked: PlayChecked,
    });
    wx.setStorageSync('IsAutoPlay', result);
  },
  settingAudioLength: function (e, b) {
    var result = !this.data.IsAudioLengthChecked;
    if (b != undefined)
      result = b;
    this.setData({
      IsAudioLengthChecked: result,
    });
    wx.setStorageSync('IsAudioLengthChecked', result);
  },
  settingPage: function (e, b) {
    isEditSetting.push("page");
    var result = !this.data.IsAutoPage;
    if (b != undefined)
      result = b;

    if (result) {
      this.data.PageChecked = "checked";
      this.data.IsAutoPlay = true;
      this.data.PlayChecked = "checked";
    }
    else {
      clearInterval(intervalAutoPage);
      this.data.PageChecked = "";
    }

    this.setData({
      IsAutoPlay: this.data.IsAutoPlay,
      IsAutoPage: result,
      isShowSettingMenu: false,
      PageChecked: this.data.PageChecked,
      IsAutoPlay: this.data.IsAutoPlay,
      PlayChecked: this.data.PlayChecked,
    });
    wx.setStorageSync('IsAutoPage', result);
  },
  bindPickerChange: function (e) {
    this.setData({
      IntervalSecondIndex: e.detail.value
    });
    wx.setStorageSync('IntervalSecondIndex', Number(e.detail.value));
    isEditSetting.push("page");
  },
  updateFinish: function () {
    var that = this;
    if (isClickFinished) {
      this.setData({
        IsFinished: !this.data.IsFinished,
      });
      isClickFinished = false;

      app.globalData.IsRefreshFinished = true;

      if (!this.data.IsFinished) {
        that.setRemind("取消", "");
      }
      else {
        that.setRemind("学过了", "Remind3");
      }

      server.postData('UpdateHanziFinished', {
        IsFinished: this.data.IsFinished,
        UserID: app.globalData.userInfo.UserID,
        Category: this.data.BookID,
        Title: this.data.UnitID,
      }, function (data) {
        server.getData('GetHanziFinishedData?UserID=' + app.globalData.userInfo.UserID, function (data) {
          if (data) {
            wx.setStorageSync("FinishedList", data);
          }
        });
      });
    }
  },
  setCombine: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../main/setcombine?id=' + id,
    });
  },
  setRemind: function (str, css) {
    var that = this;
    that.setData({
      RemindStr: str,
      RemindCss: css,
    })
    that.animateOpacity(1, "animationData", 500);
    setTimeout(function () {
      isClickReview = true;
      isClickFinished = true;
      that.animateOpacity(0, "animationData", 500);
    }, 1000);
  },
  //动画淡入淡出
  animateOpacity: function (opacity, obj, duration) {
    var animation = wx.createAnimation({
      duration: duration,
      timingFunction: 'ease',
    });

    //this.animation = animation;
    animation.opacity(opacity).step();
    if (obj == "animationData") {
      this.setData({
        animationData: animation.export(),
      });
    }
  },
  reviewHandler: function () {
    var that = this;
    if (this.data.IsShowNext && !this.data.IsAutoPage) {
      if (isClickReview) {
        this.data.List[this.data.CurrentIndex].IsReview = !this.data.List[this.data.CurrentIndex].IsReview;

        this.setData({
          List: this.data.List,
        });

        isClickReview = false;

        var status = "add";
        if (!this.data.List[this.data.CurrentIndex].IsReview) {
          status = "delete";
          that.setRemind("取消", "");
        }
        else {
          that.setRemind("添加到复习", "Remind2");
        }

        server.postData('UpdateHanziReview', {
          UserID: app.globalData.userInfo.UserID,
          Word: this.data.List[this.data.CurrentIndex].Name,
          WordID: this.data.List[this.data.CurrentIndex].ID,
          Status: status,
        }, function (data) {
          if (data) {
            wx.setStorageSync("ReviewList", data);
          }
        });
      }
    }
    else {
      if (that.data.CurrentIndex == that.data.List.length - 1)
        that.restart();
    }
  },
  onShareAppMessage: function () {
    return {
      title: app.globalData.ShareTitle,
      path: 'pages/index/index?UserID=' + app.globalData.userInfo.UserID,
      imageUrl: app.globalData.ShareImage,
    }
  },
});
