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

const app = getApp();
const arrSentence = [
  "荀子曰:\n君子博学而日参省乎己，\n则知明而行无过矣",
  "为什么订正过的题目还会错？\n天天秒过，反复巩固，不再出错",
  "子曰:\n学而时习之，不亦说乎。",
  "秒过之前，错字连篇\n秒过之后，错字罕见",
  "子曰:\n学而不思则罔\n思而不学则殆",
  "记忆是思考的残留物\n唯有不断思考才能记住",
  "荀子曰:\n青，取之于蓝，而青于蓝\n冰，水为之，而寒于水",
  "舒适区练习不会带来改变\n只有刻意练习才能提高",
  "荀子曰:\n不积跬步，无以至千里\n不积小流，无以成江海",
  "死记硬背? No! \n测试可以知晓自己\n问题在哪里。",
  "荀子曰:\n骐骥一跃，不能十步\n驽马十驾，功在不舍",
  "同一时间反复练习？No! \n要间隔练习、穿插练习、换环境练习",
  "荀子曰:\n锲而舍之，朽木不折\n锲而不舍，金石可镂",
  "所谓的粗心\n只是对细节缺乏敏感\n秒过关注每个细节",
  "孟子曰:\n故天将降大任于是人也\n必先苦其心志，劳其筋骨\n饿其体肤……",
];

var timeout1 = 0, timeout3=0;
var timeoutRedirect=0;

Page({
  data: {
    Sentence:1,
  },
  onPullDownRefresh: function () {
    wx.reLaunch({
      url: './index',
    })
  },
  onLoad: function (options) {
    console.log("Time1:" + new Date().getTime());
    if (options) {
      if (options.UserID) {
        console.log("UserID:" + options.UserID);
        app.globalData.introducer = options.UserID;
      }
      if (options.SourceID) {
        console.log("SourceID:" + options.SourceID);
        app.globalData.SourceID = options.SourceID;
      }
      // 扫码介绍人
      if (options.scene) {
        var scene = decodeURIComponent(options.scene);
        console.log("scene:" + scene);
        if (scene.indexOf("type=print")>=0){
          options.type="print";
          options.PUserID=scene.substr(scene.indexOf("U") + 2);
          options.PrintID=scene.substring(scene.indexOf("P") + 2,scene.indexOf("&U"));
        }
        else{
          var introducer = 0;
          if (scene.indexOf("UserID") >= 0)
            introducer = scene.substr(scene.indexOf("UserID") + 7);
          console.log("introducer:" + introducer);
          app.globalData.introducer = scene;
        }
      }

      if (options.type == "share") {
        if (options.ColorIndex)
          app.globalData.ColorIndex = options.ColorIndex;

        this.setData({
          gotoType: "share",
          gotoUrl: '../main/preview?type=share&id=' + options.MiaoguoCardID,
        });
      }
      else if (options.type == "bebound") {
        this.setData({
          gotoType: "bebound",
          gotoUrl: "../other/binding?type=bebound&ParentUserID=" + options.ParentUserID + "&NickName=" + options.NickName + "&AvatarUrl=" + options.AvatarUrl + "&BindTime=" + options.BindTime,
        });
      }
      else if (options.type == "lesson" || options.type == "video") {
        //console.log("Lesson:" + options.LessonID);
        app.globalData.LessonID = options.LessonID;
        if (options.LessonPage)
          app.globalData.LessonPage = options.LessonPage;
        else
          app.globalData.LessonPage = 1;

        var url="";
        if (options.type == "video"){
          url = '../other/video?LessonID=' + app.globalData.LessonID + '&LessonPage=' + app.globalData.LessonPage
        }
        else{
          if (app.globalData.LessonID === "all") {
            url = '../other/lessonlist';
          }
          else if (app.globalData.LessonID > 0) {
            url = '../other/lesson?LessonID=' + app.globalData.LessonID + '&LessonPage=' + app.globalData.LessonPage
          }
        }
        this.setData({
          gotoType: "other",
          gotoUrl: url,
        });
      }
      else if (options.type == "marketing") {
        this.setData({
          gotoType: "other",
          gotoUrl: '../marketing/index',
        });
      }
      else if (options.type == "homework") {
        this.setData({
          gotoType: "other",
          gotoUrl: "../other/homework",
        });
      }
      else if (options.type == "userbook") {
        this.setData({
          gotoType: "other",
          gotoUrl: "../other/userbook",
        });
      }
      else if (options.type == "activity") {
        this.setData({
          gotoType: "other",
          gotoUrl: "../other/activity?ActivityID=" + options.ActivityID + "&EarlyBirdTimeStart=" + options.EarlyBirdTimeStart + "&EarlyBirdTimeEnd=" + options.EarlyBirdTimeEnd + "&EndTime=" + options.EndTime,
        });
      }
      else if (options.type == "webview") {
        this.setData({
          gotoType: "other",
          gotoUrl: "../other/webview?PageID=" + options.PageID,
        });
      }
      else if (options.type == "help") {
        this.setData({
          gotoType: "other",
          gotoUrl: "../other/help?IsShare=1&id=" + options.ID+"&idchild="+options.IDChild,
        });
      }
      else if (options.type == "paycustom") {
        this.setData({
          gotoType: "other",
          gotoUrl: "../other/pay?PayType=6&PayUserID="+options.PayUserID+"&DayNumber="+options.DayNumber+"&Price="+options.Price+"&Remark="+options.Remark,
        });
      }
      else if (options.type == "print") {
        var pid=options.PrintID;
        if (!pid)
          pid=options.P;
        this.setData({
          gotoType: "other",
          gotoUrl: "../main/mainlist?PrintID="+pid,
        });
      }
      else if (options.type == "paycontinue") { 
        this.setData({ 
          gotoType: "other", 
          gotoUrl: "../other/pay?PayType=7&EndDate="+options.EndDate, 
        }); 
      } 
    }
    this.setData({
      IsRefresh: false,
      Containnerheight: main.getWindowHeight(),
      //Sentence: arrSentence[common.random(0, arrSentence.length - 1)],
      Sentence:common.random(1, 9),
    });

    this.updateProgram();

    this.getUserInfo();

    var that = this;
    timeout1 = setTimeout(function () {
      that.setData({
        IsRefresh: true,
      })
    }, 15000);
  },
  //得到用户信息
  getUserInfo: function (cb) {
    var that = this
    //调用登录接口
    wx.login({
      success: function (res0) {
        app.globalData.userInfo = {};
        app.globalData.userInfo.Code = res0.code;
        console.log("Time2:" + new Date().getTime());
        wx.getSetting({
          scope: "scope.userInfo",
          success(res) {
            if (!res.authSetting['scope.userInfo']) {
              app.globalData.userInfo.nickName = "陌生用户";
              app.globalData.userInfo.language = "";
              app.globalData.userInfo.gender = "0";
              app.globalData.userInfo.city = "";
              app.globalData.userInfo.province = "";
              app.globalData.userInfo.country = "";
              app.globalData.userInfo.avatarUrl = "../images/universalpic_face_default_blue_120x120.png";
              that.login(app.globalData.userInfo);
            }
            else {
              wx.getUserInfo({
                withCredentials: false,
                success: function (res) {
                  console.log("Time3:" + new Date().getTime());
                  app.globalData.userInfo = res.userInfo;

                  app.globalData.userInfo.NickName = app.globalData.userInfo.nickName;
                  app.globalData.userInfo.AvatarUrl = app.globalData.userInfo.avatarUrl;

                  app.globalData.userInfo.Code = res0.code;
                  that.login(app.globalData.userInfo);

                },
                fail: function (res) {
                  that.login(app.globalData.userInfo);
                }
              });

            }
          }
        });
      },
      fail: function () {

      }
    });
  },

  login: function (param) {
    var that = this;
    //var userSource = wx.getLaunchOptionsSync();
    //console.log("userSource1:" + userSource.scene);
    //console.log("userSource2:" + app.globalData.userSource);

    main.getLocalHost(function () {
      main.postData('MiaoguoLogin', {
        Code: param.Code,
        NickName: param.nickName,
        Language: param.language,
        Gender: param.gender,
        City: param.city,
        Province: param.province,
        Country: param.country,
        AvatarUrl: param.avatarUrl,
        Introducer: app.globalData.introducer,
        UserSource: app.globalData.userSource,
        SourceID: app.globalData.SourceID,
        LastUserSource: app.globalData.userSource,
        Brand: app.globalData.systemInfo.brand,
        Model: app.globalData.systemInfo.model,
        PixelRatio: app.globalData.systemInfo.pixelRatio,
        ScreenWidth: app.globalData.systemInfo.screenWidth,
        ScreenHeight: app.globalData.systemInfo.screenHeight,
        WindowWidth: app.globalData.systemInfo.windowWidth,
        WindowHeight: app.globalData.systemInfo.windowHeight,
        WXLanguage: app.globalData.systemInfo.language,
        WXVersion: app.globalData.systemInfo.version,
        System: app.globalData.systemInfo.system,
        Platform: app.globalData.systemInfo.platform,
        SDKVersion: app.globalData.systemInfo.SDKVersion,
        ProgramVersion: app.globalData.Version,
      }, function (data) {
        console.log("Time4:" + new Date().getTime());
        if (!data) {
          timeout3 = setTimeout(function () {
            that.getUserInfo();
            console.log("reboot:" + new Date().getTime());
          }, 2000);
        }
        else {
          app.globalData.userInfo = data;

          var isShow = data.IsShow;
          if (isShow == -1) {
            isShow = 0;
          }
          else {
            var systemInfo = wx.getSystemInfoSync();
            if (isShow == 0 && systemInfo.system && systemInfo.system.indexOf("Android") >= 0) {
              isShow = 1;
            }
          }

          app.globalData.userInfo.IsShow = isShow;
          if (app.globalData.userInfo.IsMember == 1)
            app.globalData.IsLocked = 0;

          wx.removeStorageSync("UserID");
          wx.removeStorageSync("UserName");

          // //测试****************
          // var url = '../main/mainlist';
          // wx.redirectTo({
          //   url: url,
          // });
          // return;
          // //测试****************

          if (that.data.gotoType == "share") {
            wx.reLaunch({
              url: that.data.gotoUrl,
            });
          }
          else if (that.data.gotoType == "bebound") {
            wx.reLaunch({
              url: that.data.gotoUrl,
            });
          }
          else {
            if (that.data.gotoType == "other"){
              app.globalData.GotoUrl = that.data.gotoUrl;
              var url = '../main/default';
              wx.redirectTo({
                url: url,
              });
            }
            else{
              var url = '../main/default';
              timeoutRedirect=setTimeout(function () {
                console.log("Time5:" + new Date().getTime());
                clearTimeout(timeout1);
                app.globalData.FolderList=[];
                wx.redirectTo({
                  url: url,
                });
              }, 2000);
            }
            main.getUserConfig();

          }
          that.getBaiduToken();
          
        }
      });

    });
  },
  getBaiduToken: function () {
    main.getBaiduToken();
  },
  
  updateProgram: function () {
    const updateManager = wx.getUpdateManager();

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      //console.log(res.hasUpdate)
    });

    updateManager.onUpdateReady(function () {
      clearTimeout(timeoutRedirect);
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，重启应用',
        showCancel:false,
        success: function (res) {
          wx.removeStorageSync("UserID");
          wx.removeStorageSync("UserName");
          wx.removeStorageSync("SearchWord3");
          wx.removeStorageSync("HanziUpdateTime");
          wx.removeStorageSync("HanziAll");
          wx.removeStorageSync("EnglishAll");
          // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
          updateManager.applyUpdate();
        }
      });

    });
  },
  
  onShareAppMessage: function () {
    return {
      title: app.globalData.ShareTitle,
      path: app.globalData.SharePath + '?UserID=' + app.globalData.userInfo.UserID,
      imageUrl: app.globalData.ShareImage,
    }
  },
})