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

const app = getApp();
var intervalRefresh = 0;
var isCollecting = false;

var arrOrder = [{},
  {
    Name: "按最近练习时间",
    Value: "ac.LastTime desc"
  },
  {
    Name: "按最近修改时间",
    Value: "ac.UpdateTime desc,ac.CreateTime desc",
    CSS: "PanelBtnSelect2"
  },
  {
    Name: "创建最早",
    Value: "ac.MiaoguoCardID asc"
  },
  {
    Name: "创建最近",
    Value: "ac.MiaoguoCardID desc",
  },
  {
    Name: "到期最早",
    Value: "ac.LimitTime asc"
  },
  {
    Name: "到期最晚",
    Value: "ac.LimitTime desc"
  },
  {
    Name: "练习较少",
    Value: "ac.LearnNumber,ac.MiaoguoCardID"
  },
  {
    Name: "练习较多",
    Value: "ac.LearnNumber desc,ac.MiaoguoCardID desc"
  },
  {
    Name: "归档最早",
    Value: "ac.PigeonholeTime asc"
  },
  {
    Name: "归档最近",
    Value: "ac.PigeonholeTime desc"
  },
];

Page({
  data: {
    ImagePath: app.globalData.uploadImageUrl,
    IsShowCardShowDetail: false, //显示题卡显示细节
    IsHelp: false,
    IsFilter:false,
    HasPage: false, //有没有分页
    CardTypeStr: "全部",
    IsShowSelectCardType: false, //是否显示选择题卡模式
    ArrOrder: arrOrder, //可选择的排序数组
    OrderType: 2, //选择的排序类型
    CardType: 2, //练习模式类型，缺省为日常+紧急
    PrintID: 0, //打印ID
    CardShowDetail: 0, //0 创建时间 1 修改时间 2到期时间 3练习时间 4练习次数
    FolderListCss:"",//卡单时列表样式
  },
  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;
      that.setOrderSelect(5);
      that.setData({
        CardShowDetail: 2,
      });
      wx.setNavigationBarTitle({
        title: "未练完的题卡"
      });
    } else if (options.type == 2) { //练完的情况
      IsToday = 2;
      that.setOrderSelect(1);
      that.setData({
        CardShowDetail: 3,
      });
      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.FolderID) { //卡单题卡情况
      wx.setNavigationBarTitle({
        title: "卡单"
      });
      that.setData({
        FolderID: options.FolderID,
        FolderName:options.Name,
        IconName:options.IconName,
        ColorName:options.ColorName,
        FolderListCss:"CellHide00",
      });
    } else if (options.CardType != 2) { //如果不是日常+紧急
      var title = "日常题卡";
      if (options.CardType == 1) {
        title = "紧急题卡";
      } else if (options.CardType == -1) {
        title = "归档"; 

        that.setOrderSelect(10);
        that.setData({
          CardShowDetail: 2,
        });
      } else if (options.CardType == -2) {
        title = "回收";

        that.setOrderSelect(10);
        that.setData({
          CardShowDetail: 2,
        });
      }
      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, //列表类型，1 今天未练完 2 今天已经练完
      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)];
    }
    
    that.getFilter();

    if (that.data.FolderID && app.globalData.TempStr){
      that.setData({
        FolderName:app.globalData.TempStr.Name,
        IconName:app.globalData.TempStr.IconName,
        ColorName:app.globalData.TempStr.ColorName,
        FolderListCss:"CellHide00",
      });
      app.globalData.TempStr="";
    }

    if (wx.getStorageSync("TempCardNoSaved")) {
      wx.navigateTo({
        url: '../other/recover',
      });
    }
  },
  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.DeleteType = 0;
      item.Content[1].ContentStr = main.replaceCardInfoString(item.Content[1].Content);
      if (item.Content[1].ContentStr.length > len)
        item.Content[1].ContentStr = main.replaceCardInfoString(item.Content[1].ContentStr.substr(0, len)) + "...";

      item.Content[2].ContentStr = main.replaceCardInfoString(item.Content[2].Content);
      if (item.Content[2].ContentStr.length > len)
        item.Content[2].ContentStr = main.replaceCardInfoString(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 (item.FirstTime < "1900-01-02")
        item.CardCategory = "新题卡";
      else
        item.CardCategory = "旧题卡";

      if (that.data.PrintID){
        item.CardShowDetailStr2=item.Number;
      }
      else if (that.data.CardType == "-2") {
        item.CardShowDetailStr2 = common.formatDateCHS(item.DeleteTime);
      } else {
        switch (Number(that.data.CardShowDetail)) {
          case 0:
            item.CardShowDetailStr2 = common.formatDateCHS(item.CreateTime);
            break;
          case 1:
            item.CardShowDetailStr2 = common.formatDateCHS(item.UpdateTime);
            break;
          case 2:
            if (that.data.CardType==2 && item.CardType == -1){
              item.CardShowDetailStr2 = "不适用";
            }
            else if (item.CardType == -1)
              item.CardShowDetailStr2 = common.formatDateCHS(item.PigeonholeTime);
            else
              item.CardShowDetailStr2 = common.formatDateCHS(item.LimitTime);
            break;
          case 3:
            if (item.LastTime < "1900-01-02")
              item.CardShowDetailStr2 = "不适用";
            else
              item.CardShowDetailStr2 = common.formatDateCHS(item.LastTime);

            break;
          case 4:
            item.CardShowDetailStr2 = item.LearnNumber + "次";
            break;
        }
      }

      item.CardTypeStr = constant1.arrStudyPattern[item.CardType];
    }

    if (!that.data.IsToday && !that.data.PrintID && !that.data.Search && that.data.CardType != "-2" && !that.data.FolderID) {
      main.getData("GetUserCardCount?UserID=" + app.globalData.userInfo.UserID + "&CardType=" + that.data.CardType + "&IsCollect=" + that.data.IsCollect+"&OrderType="+that.data.OrderType, 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.data.FolderID > 0) {
      var hasPage = false;
      if (list.length < that.data.Count)
        hasPage = true;
      that.setData({
        List: list,
        HasPage: hasPage,
      });
    } else if (that.data.CardType != -2) {
      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,
      });
    } else {
      that.setData({
        List: list,
      });
    }

    var strCardShowDetail = constant1.arrCardShowDetail[that.data.CardShowDetail];
    if (that.data.CardShowDetail == 2 && that.data.CardType == -1)
      strCardShowDetail = "归档";
    else if (that.data.CardType == -2)
      strCardShowDetail = "删除";
    else if (that.data.PrintID)
      strCardShowDetail = "打印卷序号";
      
    that.setData({
      CardShowDetailStr: strCardShowDetail,
    });

    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;
    }
    
  },
  onPreview: function (e) {
    var id = e.currentTarget.dataset.id;
    var url='./preview?type=show&id=' + id;
    if (this.data.PrintID)
      url+="&PrintID="+this.data.PrintID;
    wx.navigateTo({
      url: url,
    })
  },
  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);
        }
      }
    });
  },
  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 (e.currentTarget.dataset.IsToday)
      url += "&IsToday="+e.currentTarget.dataset.IsToday;


    var cardtype = e.currentTarget.dataset.cardtype;
    if (cardtype || cardtype == "0") {

      url += "&CardType=" + cardtype;
      var str = constant1.arrStudyPattern[cardtype];
      if (cardtype == "2")
        str = "全部";

      that.setData({
        CardType: Number(cardtype),
        CardTypeStr: str,
      })
    } else {
      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";
    
    if (e.currentTarget.dataset.folderid)
      url += "&FolderID="+e.currentTarget.dataset.folderid;
    
    

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

        var list = app.globalData.CardList;
        if (id == 0) {
          list = [];
          that.setData({
            Count: data.Count,
          });
        }

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

        that.getFilter();
      }
    });

    that.setData({
      IsOrder: false,
      IsHelp: false,
      IsShowSelectCardType: false,
    });
  },
  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();
        }
      }
    });
  },
  getFilter:function(){
    var that = this;
    if (app.globalData.TempStr2){
      if (that.data.Count<=1)
        isFilter=false;
      else{
        var arr=[["全部",0,"",2,0],["",0,"",0,0]];
        var isFilter=false;
        var str=app.globalData.TempStr2;
        if (str.indexOf("IsCollect=1")>=0){
          arr[1][0]="星标";
          arr[1][3]=0;
          arr[1][4]=1;
          isFilter=true;
        }
        else if (str.indexOf("CardType=0")>=0){
          arr[1][0]="日常";
          arr[1][3]=0;
          arr[1][4]=0;
          isFilter=true;
        }
        else if (str.indexOf("CardType=1")>=0){
          arr[1][0]="紧急";
          arr[1][3]=1;
          arr[1][4]=0;
          isFilter=true;
        }
        else if (str.indexOf("CardType=-1")>=0){
          arr[1][0]="归档";
          arr[1][3]=-1;
          arr[1][4]=0;
          isFilter=true;
        }
        
        if (that.data.CardType==2){
          arr[0][1]=that.data.Count;
          arr[0][2]="panelTop40";
        }
        else{
          arr[1][1]=that.data.Count;
          arr[1][2]="panelTop40";
          arr[0][2]="";
        }
        //console.log("CardType:"+that.data.CardType);
        

        that.setData({
          FilterArr:arr,
        });
      }
      that.setData({
        IsFilter:isFilter,
      });
    }
  },
  addCard: function () {
    var url='./add?type=add&id=0';
    if (this.data.FolderID){
      url+="&FolderID="+this.data.FolderID+"&FolderName="+this.data.FolderName;
    }
    else{
      var cardtype=this.data.CardType;
      if (cardtype==1 || cardtype==-1){
        url+="&CardType="+cardtype;
      }
    }
    
    wx.redirectTo({
      url: url,
    });
  },
  onSearch: function (e) {
    var id=1;
    if (e.currentTarget.dataset.id)
      id=Number(e.currentTarget.dataset.id);
    wx.navigateBack({
      delta: id,
    });
  },
  onOrder: function (e) {
    var that = this;
    var value = e.currentTarget.dataset.value;
    switch (Number(value)) {
      case 1:
        that.data.CardShowDetail = 3;
        break;
      case 2:
        that.data.CardShowDetail = 1;
        break;
      case 3:
      case 4:
        that.data.CardShowDetail = 0;
        break;
      case 5:
      case 6:
        that.data.CardShowDetail = 2;
        break;
      case 7:
      case 8:
        that.data.CardShowDetail = 4;
        break;
      case 9:
      case 10:
        that.data.CardShowDetail = 2;
        break;
    }
    for (var i = 0; i < that.data.ArrOrder.length; i++) {
      if (i == value) {
        that.data.ArrOrder[i].CSS = "PanelBtnSelect2";
      } else
        that.data.ArrOrder[i].CSS = "";
    }
    that.setData({
      IsOrder: false,
      ArrOrder: that.data.ArrOrder,
      OrderType: value,
      CardShowDetail: that.data.CardShowDetail,
    });

    if (that.data.IsToday!=1) {
      app.globalData.CardList = [];
      that.gotoNextPage({
        currentTarget: {
          dataset: {
            id: 0,
            IsToday:that.data.IsToday,
            OrderType: value,
            cardtype: that.data.CardType,
            iscollect: that.data.IsCollect,
            folderid: that.data.FolderID,
          }
        }
      });
    }
  },
  showOrder: function () {
    this.setData({
      IsOrder: true,
    });
  },
  closeHelp: function () {
    this.setData({
      IsOrder: false,
      IsHelp: false,
      IsShowSelectCardType: 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.DeleteType == 0) {
          item.ScrollLeft = 440;
          item.DeleteType = 1;
        } else if (item.DeleteType == 1) {
          b = false;
          item.DeleteType = 0;
          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.DeleteType = 0;
        item.ScrollLeft = 0;
      }
    }
    if (b) {
      that.setData({
        List: list,
      });
    }
  },
  showSelectCardShowDetail: function () {
    var that = this;
    var arr = [];
    for (var i = 0; i < 5; i++) {
      var obj = {};
      obj.Name = constant1.arrCardShowDetail[i];

      if (that.data.CardType == -1 && i == 2)
        obj.Name = "归档";
      if (i < 4)
        obj.Name += "时间";

      if (i == that.data.CardShowDetail)
        obj.IsSelected = "PanelBtnSelect";
      else
        obj.IsSelected = "";
      arr.push(obj);
    }
    that.setData({
      IsShowCardShowDetail: true,
      CardShowDetailArr: arr,
    });
  },
  hideSelectCardShowDetail: function () {
    var that = this;
    that.setData({
      IsShowCardShowDetail: false,
    });
  },
  selectCardShowDetail: function (e) {
    var that = this;
    that.data.CardShowDetail = e.currentTarget.dataset.id;
    that.setData({
      IsShowCardShowDetail: false,
      CardShowDetail: that.data.CardShowDetail,
    });
    that.getList();
    that.hideSelectCardShowDetail();
  },
  showHelp: function () {
    var that = this;
    that.setData({
      IsHelp: true,
    });
  },
  showSelectCardType: function () {
    var that = this;
    var arr = [
      ["全部", "", 2],
      ["日常", "", 0],
      ["紧急", "", 1],
      ["归档", "", -1]
    ];
    switch (that.data.CardType) {
      case 2:
        arr[0][1] = "PanelBtnSelect";
        break;
      case 0:
        arr[1][1] = "PanelBtnSelect";
        break;
      case 1:
        arr[2][1] = "PanelBtnSelect";
        break;
      case -1:
        arr[3][1] = "PanelBtnSelect";
        break;
    }

    that.setData({
      IsShowSelectCardType: true,
      CardTypeArr: arr,
    });
  },
  recoverItem: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var url = "DeleteMiaoguoCardWeb?UserID=" + app.globalData.userInfo.UserID;
    var param = {};
    param.IsRecover = "true";
    param.VisitType = "vtqOSthN7vSwYmhc1gCjfw==";
    param.ID = common.Encrypt(id);
    main.postData(url, param, function () {
      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,
      });
    });
  },
  setCollect: function (e) {
    var that = this;
    if (!isCollecting) {
      isCollecting = true;
      setTimeout(function () {
        isCollecting = false;
      }, 3000);

      var id=e.currentTarget.dataset.id;
      var collect=e.currentTarget.dataset.collect;
      if (collect==0) {
        collect = 1;
      }
      else {
        collect = 0;
      }
      main.setCollect(id, collect, function () {
        var list = app.globalData.CardList;
        for (var i = 0; i < list.length; i++) {
          if (id == list[i].MiaoguoCardID) {
            if (collect==0)
              list.splice(i, 1);
            else
              list[i].IsCollect = collect;
            break;
          }
        }
        app.globalData.CardList = list;
        that.setData({
          List: list,
        });
      });
    }
  },
  editField: function (e) {
    var id=e.currentTarget.dataset.id;
    var that = this;
    wx.navigateTo({
      url: './add?type=edit&id=' + id,
    });
  },  
  removeFolder:function(e){
    var that = this;
    var id=e.currentTarget.dataset.id;
    var url = 'RemoveFolder?UserID=' + app.globalData.userInfo.UserID;
    url += "&ID=" + id;
    url += "&FolderID=" + that.data.FolderID;
    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,
      });
    });
  },
  setOrderSelect:function(od){
    var that=this;
    for(var k=0;k<arrOrder.length;k++){
      if (k==od)
        arrOrder[k].CSS = "PanelBtnSelect2";
      else
        arrOrder[k].CSS = "";
    }
    that.setData({
      ArrOrder: arrOrder,
      OrderType:od,
    });
  },
  goto: function (e) {
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: './' + url,
    })
  },
  redirect: function (e) {
    var that=this;
    var url = e.currentTarget.dataset.url;
    app.globalData.TempStr2="CardType="+that.data.CardType+"&IsCollect="+that.data.IsCollect;
    wx.redirectTo({
      url: './' + url,
    })
  },
  onShareAppMessage: function () {
    return {
      title: app.globalData.ShareTitle,
      path: app.globalData.SharePath + '?UserID=' + app.globalData.userInfo.UserID,
      imageUrl: app.globalData.ShareImage,
    }
  },
})