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

const app = getApp()
var timeout2, timeout3;

Page({
  data: {
    ImageAll: ["../images/01003.png", "../images/01004.png", "../images/01005.png"],
    indexImage: 0,
  },
  onReady: function (e) {
  },
  onLoad: function (options) {
    if (options) {
      if (options.UserID) {
        console.log("UserID:" + options.UserID);
        app.globalData.introducer = options.UserID;
      }
      if (options.goto) {
        console.log("goto:" + options.goto);
        app.globalData.goto = options.goto;
      }
      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);
        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.ProductID) {
        this.setData({
          ProductID: options.ProductID,
          ProductUserID: options.ProductUserID,
        });
      }
      if (options.GiftID) {
        this.setData({
          GiftID: options.GiftID,
        });
      }
    }
    this.setData({
      Height: common.getSystemHeight(),
      indexImage: common.random(0, 2),
    });

    this.getUserInfo();

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

    this.updateProgram();
  },
  //得到用户信息
  getUserInfo: function (cb) {
    var that = this
    //调用登录接口
    wx.login({
      success: function (res0) {
        app.globalData.userInfo = {};
        app.globalData.userInfo.Code = res0.code;
        //console.log("Code:" + res0.code);

        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/FACE.png";
              that.login(app.globalData.userInfo);
            }
            else {
              wx.getUserInfo({
                withCredentials: false,
                success: function (res) {
                  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 () {
        timeout2 = setTimeout(function () {
          that.getUserInfo();
          console.log("reboot:" + new Date().getTime());
        }, 2000);
      }
    });
  },

  login: function (param) {
    var that = this;

    server.getLocalHost(function () {
      server.postData('HanziLogin', {
        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("UserInfo:" + data);
        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.IsShow = data.IsShow;

          app.globalData.IsLocked = data.IsLocked;
          
          if (that.data.GiftID) {
            var url = "../../package4/main/giftcard?GiftID=" + that.data.GiftID + "&UserID=" + app.globalData.introducer
            wx.redirectTo({
              url: url
            });
          }
          else if (that.data.ProductID) {
            var url = "../../package4/main/activateOK?ProductID=" + that.data.ProductID
              + "&ProductUserID=" + that.data.ProductUserID
              + "&CurrentUserID=" + app.globalData.userInfo.UserID
              + "&CurrentProductID=" + app.globalData.ProgramID;
            wx.redirectTo({
              url: url
            });
          }
          else {
            //app.globalData.userInfo.AvatarUrl = param.avatarUrl;
            that.getHanzi(function(){
              setTimeout(function () {
                wx.redirectTo({
                  url: '../main/index'
                })
              }, 2000);
            });
            that.getPriceList();
            wx.setStorageSync("IsShare", 0);
          }
        }
      });

    });
    
  },
  getHanzi: function (callback) {
    var that = this;
    var time = wx.getStorageSync("HanziUpdateTime");
    server.getData('GetHanziAll?UpdateTime=' + time, function (data) {
      if (data) {
        if (data.List) {
          var arr = common.Decrypt(data.List);
          wx.setStorageSync("HanziAll", arr);
          wx.setStorageSync("HanziUpdateTime", data.UpdateTime);
        }
        app.globalData.BaiduToken = data.String;
        callback();
      }
    });
  },
  getPriceList: function () {
    var that = this;
    if (!wx.getStorageSync("ProductPrice")) {
      server.getData('ProductPayPriceList500', function (data) {
        if (data) {
          var arrProduct = JSON.parse(common.Decrypt(data));
          var programList = server.getProgramList();
          for (var j = 0; j < arrProduct.length; j++) {
            arrProduct[j].ProductList = [];
            var arr = arrProduct[j].ProductNum.split(",");
            for (var k = 0; k < arr.length; k++) {
              for (var i = 0; i < programList.length; i++) {
                if (programList[i].ID == arr[k]) {
                  arrProduct[j].ProductList.push(programList[i]);
                }
              }
            }
          }
          wx.setStorageSync("ProductPrice", arrProduct);
        }
      });
    }
  },
  updateProgram: function () {
    const updateManager = wx.getUpdateManager();

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

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      });

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