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

const app = getApp();
var intervalRefresh = 0;
var arrOrder = [
  {},
  { Name: "最近更新", Value: "ac.UpdateTime desc,ac.CreateTime desc", CSS: "numberContainerFooter1121Select" },
  { Name: "最近添加", Value: "ac.MiaoguoCardID desc", },
  { Name: "较早添加", Value: "ac.MiaoguoCardID asc" },
  { Name: "练习较多", Value: "ac.LearnNumber desc,ac.MiaoguoCardID desc" },
  { Name: "练习较少", Value: "ac.LearnNumber,ac.MiaoguoCardID" },
  { Name: "最近练习", Value: "ac.LastTime desc" },
  { Name: "到期升序", Value: "ac.LimitTime asc" },
  { Name: "到期降序", Value: "ac.LimitTime desc" },
];

Page({
  data: {
    HasPage: false,
    ArrOrder: arrOrder,
    OrderType: 1,
    CardType:2,
    PrintID:0,
  },
  onLoad: function (options) {
    var that = this;

    var Search = "", IsToday = 0, IsCollect = 0;
    var count = 0;
    if (options.Count)
      count = options.Count;

    if (options.search) {
      Search = options.search;
      wx.setNavigationBarTitle({
        title: "搜索结果"
      });
    }
    else if (options.type == 1) {
      IsToday = 1;
      wx.setNavigationBarTitle({
        title: "未练完的题卡"
      });
    }
    else if (options.type == 2) {
      IsToday = 2;
      wx.setNavigationBarTitle({
        title: "练完的题卡"
      });
    }
    else if (options.IsCollect == 1) {
      wx.setNavigationBarTitle({
        title: "收藏夹"
      });
      IsCollect = 1;
    }
    else if (options.PrintID) {
      wx.setNavigationBarTitle({
        title: "打印卷题卡清单"
      });
      that.setData({
        PrintID:options.PrintID,
      });
      that.getPrintList();
    }
    else if (options.CardType != 2) {
      var title = "日常练习";
      if (options.CardType == 1)
        title = "紧急练习";
      else if (options.CardType == -1)
        title = "留白";
      wx.setNavigationBarTitle({
        title: title + "题卡",
      });
      that.setData({
        CardType: options.CardType,
      });
    }

    that.setData({
      IsCollect: IsCollect,
      Search: Search,
      IsToday: IsToday,
      Count: count,
      Containnerheight: main.getWindowHeight(),
      PageType: options.type,
      IsNew: options.IsNew,
    });
  },
  onShow: function () {
    var that = this;
    if (!that.data.PrintID){
      if (that.data.IsNew)
        that.onOrder({ currentTarget: { dataset: { value: 4 } } });
      else
        that.getList();
    }

    //题卡主题色
    var arrColorIndex = wx.getStorageSync("ColorIndexArr");
    if (!arrColorIndex) {
      app.globalData.ColorIndex = common.random(1, 4);
    }
    else {
      app.globalData.ColorIndex = arrColorIndex[common.random(0, arrColorIndex.length - 1)];
    }
  },
  onPullDownRefresh: function () {
    var that = this;
    if (!that.data.IsCollect && !that.data.IsToday) {
      app.globalData.CardList = [];
      that.gotoNextPage({ currentTarget: { dataset: { id: 0 } } });
    }
    wx.stopPullDownRefresh();
  },
  getList: function () {
    var that = this;
    var list = app.globalData.CardList;
    var len = 16;
    for (var i = 0; i < list.length; i++) {
      var item = list[i];
      item.ScrollLeft = 0;
      item.DeleteStr = "删除";
      item.Content[1].ContentStr = replaceString(item.Content[1].Content);
      if (item.Content[1].ContentStr.length > len)
        item.Content[1].ContentStr = replaceString(item.Content[1].ContentStr.substr(0, len)) + "...";

      item.Content[2].ContentStr = replaceString(item.Content[2].Content);
      if (item.Content[2].ContentStr.length > len)
        item.Content[2].ContentStr = replaceString(item.Content[2].ContentStr.substr(0, len)) + "...";

      var imageUrl = getImage(item.Content[1].Content);
      if (imageUrl.length == 0 && item.Content[2].Content)
        imageUrl = getImage(item.Content[2].Content);
      if (imageUrl.length == 0 && item.Content[3].Content)
        imageUrl = getImage(item.Content[3].Content);

      if (imageUrl.length > 0) {
        item.ImageUrlTemp = main.getTempImage(imageUrl);
        item.ImageUrlServer = imageUrl;
      }
    }

    if (!that.data.IsToday && !that.data.PrintID && !that.data.Search) {
      main.getData("GetUserCardCount?UserID=" + app.globalData.userInfo.UserID+"&CardType="+that.data.CardType+"&IsCollect="+that.data.IsCollect, function (data) {
        if (data) {
          that.setData({
            Count: data.CardNumber,
          });
          var hasPage = false;
          if (list.length < that.data.Count && list.length>=20 && that.data.IsToday == 0)
            hasPage = true;

          that.setData({
            List: list,
            HasPage: hasPage,
          });

          if (that.data.PageType === "3") {
            wx.redirectTo({
              url: './preview?type=show&id=' + list[0].MiaoguoCardID,
            })
          }
        }
      });
    }
    else if (that.data.Search) {
      that.setData({
        List: list,
        Count: list.length,
        HasPage: true,
      });
    }
    else {
      that.setData({
        Count: list.length,
      });

      var hasPage = false;
      if (list.length < that.data.Count && that.data.IsToday == 0)
        hasPage = true;

      that.setData({
        List: list,
        HasPage: hasPage,
      });
    }

    wx.hideLoading();

    function getImage(str) {
      var result = "";
      if (str.indexOf("[图") >= 0) {
        result = str.substring(str.indexOf("[图") + 3, str.indexOf("[/图]"));
        result = result.substring(result.indexOf("]") + 1);
      }
      //console.log(result);
      return result;
    }

    function replaceString(str) {
      //str = str.replace(/\[图]/g, "");
      //str = str.replace(/\[\/图\]/g, "");

      var str2 = "";
      if (str.indexOf("[读 src=") >= 0) {
        str2 = str.substr(str.indexOf("[读 src="));
        str2 = str2.substring(0, str2.indexOf("/读]") + 3);
      }
      str = str.replace(str2, "");

      if (str.indexOf("[读 src=") >= 0) {
        str2 = str.substr(str.indexOf("[读 src"));
        str2 = str2.substring(0, str2.indexOf("/读]") + 3);
      }
      str = str.replace(str2, "");

      str = str.replace(/\[读]/g, "");
      str = str.replace(/\[\/读\]/g, "");

      var str3 = "";
      if (str.indexOf("[图") >= 0) {
        str3 = str.substr(str.indexOf("[图"));
        str3 = str3.substring(0, str3.indexOf("/图]") + 3);
      }
      str = str.replace(str3, "");
      if (str.indexOf("[图") >= 0) {
        str3 = str.substr(str.indexOf("[图"));
        str3 = str3.substring(0, str3.indexOf("/图]") + 3);
      }
      str = str.replace(str3, "");

      str = str.replace(/\[线]/g, "");
      str = str.replace(/\[\/线\]/g, "");
      str = main.encryptUrl(str);
      return str;
    }
  },
  onPreview: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: './preview?type=show&id=' + id,
    })
  },
  playPPT: function () {
    wx.navigateTo({
      url: './preview?type=play',
    })
  },
  onBindError: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;

    var serverUrl = e.currentTarget.dataset.serverurl;
    wx.downloadFile({
      url: serverUrl, // 仅为示例，并非真实的资源
      success(res) {
        if (res.statusCode === 200) {
          main.saveTempImage(serverUrl, res.tempFilePath);
        }
      }
    });

    // clearTimeout(intervalRefresh);
    // intervalRefresh = setTimeout(function () {
    //   that.getList();
    // }, 1000);
  },
  gotoNextPage: function (e) {
    wx.showLoading({
      title: '请稍候',
    });
    setTimeout(function () {
      wx.hideLoading();
    }, 5000);

    var that = this;
    var url = 'GetMiaoguoCardList2?UserID=' + app.globalData.userInfo.UserID;
    var id = e.currentTarget.dataset.id;
    if (id && id > 0)
      url += "&PageID=" + id;
      
    if (that.data.CardType)
      url += "&CardType=" + that.data.CardType;

    if (that.data.Search)
      url += "&Key=" + that.data.Search;

    var orderType = that.data.OrderType;
    if (orderType)
      url += "&OrderType=" + arrOrder[orderType].Value;
    
    if (e.currentTarget.dataset.iscollect==1)
      url += "&IsCollect=1";


    main.getData(url, function (data) {
      if (data) {

        var list = app.globalData.CardList;

        for (var i = 0; i < data.List.length; i++) {
          data.List[i].LastTimeStr = common.formatDateCHS(data.List[i].LastTime);

          list.push(data.List[i]);
        }
        app.globalData.CardList = list;
        that.getList();

        if (data.List.length < 20) {
          that.setData({
            HasPage: false,
          });
        }

        if (orderType > 0) {
          wx.setNavigationBarTitle({
            title: "全部题卡：" + arrOrder[orderType].Name,
          });
        }
      }
    });
  },
  getPrintList: function (e) {
    wx.showLoading({
      title: '请稍候',
    });
    setTimeout(function () {
      wx.hideLoading();
    }, 5000);

    var that = this;
    var url = 'GetMiaoguoCardList2?UserID=' + app.globalData.userInfo.UserID+'&PrintID='+that.data.PrintID;
    main.getData(url, function (data) {
      if (data) {
        if (data.List.length>0){
          var list=[];
          for (var i = 0; i < data.List.length; i++) {
            data.List[i].Number = i+1;
            list.push(data.List[i]);
          }
          app.globalData.CardList = list;
          that.getList();

          wx.setNavigationBarColor({
            frontColor: "#000000",
            backgroundColor: "#ffffff",
          });
        }
        else{
          that.onSearch();
        }
      }
    });
  },
  addCard: function () {
    wx.redirectTo({
      url: './add?type=add&id=0',
    });
  },
  onSearch: function () {
    wx.navigateBack({
      delta: 1,
    });
  },
  onOrder: function (e) {
    var that = this;
    var value = e.currentTarget.dataset.value;
    for (var i = 0; i < this.data.ArrOrder.length; i++) {
      if (i == value)
        this.data.ArrOrder[i].CSS = "numberContainerFooter1121Select";
      else
        this.data.ArrOrder[i].CSS = "";
    }
    this.setData({
      IsOrder: false,
      ArrOrder: this.data.ArrOrder,
      OrderType: value,
    });

    if (!that.data.IsCollect && !that.data.IsToday) {
      app.globalData.CardList = [];
      that.gotoNextPage({ currentTarget: { dataset: { id: 0, OrderType: value } } });
    }
  },
  showOrder: function () {
    this.setData({
      IsOrder: true,
    });
  },
  closeOrder: function () {
    this.setData({
      IsOrder: false,
    });
  },
  DeleteItem: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var list = this.data.List;
    var b = true;
    for (var i = 0; i < list.length; i++) {
      var item = list[i];
      if (id == item.MiaoguoCardID) {
        if (item.DeleteStr == "删除") {
          item.ScrollLeft = 160;
          item.DeleteStr = "确认删除";
        }
        else if (item.DeleteStr == "确认删除") {
          b = false;
          item.DeleteStr = "删除";
          item.ScrollLeft = 0;
          var url = 'DeleteMiaoguoCard?UserID=' + app.globalData.userInfo.UserID;
          url += "&ID=" + id;
          main.getData(url, function (data) {
            var list = app.globalData.CardList;
            for (var i = 0; i < list.length; i++) {
              if (id == list[i].MiaoguoCardID) {
                list.splice(i, 1);
                break;
              }
            }
            app.globalData.CardList = list;
            that.setData({
              List: list,
              Count: --that.data.Count,
            });
          });
        }
      }
      else {
        item.DeleteStr = "删除";
        item.ScrollLeft = 0;
      }
    }
    if (b) {
      that.setData({
        List: list,
      });
    }
  },
  onShareAppMessage: function () {
    return {
      title: app.globalData.ShareTitle,
      path: app.globalData.SharePath + '?UserID=' + app.globalData.userInfo.UserID,
      imageUrl: app.globalData.ShareImage,
    }
  },
})
