let config = require("./config/config.js");
const { defaultObj, huanLeChengObj } = require("./utils/mouldStyle.js")
const Http = require("./utils/HttpBasics");
const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}

let businessSwitch = extConfig.attr.businessSwitch ? extConfig.attr.businessSwitch : false

if (businessSwitch) {
  var myPluginInterface = requirePlugin('auto-points-plugin')
}
App({
  data: {
    newArr: [], //存放分享二维进入消息信息
    businessSwitch: businessSwitch || null, //判断是否开启商圈自助积分
  },

  onLaunch: function (options) {
    // wx.hideTabBar()
    var that = this;
    if (that.globalData.previewFlag) { //解决微信图片预览重复进入app.js onshow
      that.globalData.previewFlag = false
      return
    }
    if (options.query.scene) {
      that.globalData.newArr = decodeURIComponent(options.query.scene).split(":");
    }
    that.globalData.sceneAddress = options.scene
    /**
     * 小程序版本更新
     */
    that.autoUpdate();
    /**
     * 用户登录
     */
    that.userLogin(options.scene);
    wx.getSystemInfo({
      success: res => {
        that.statusBarHeight = res.statusBarHeight
      }
    })

  },

  onShow: function (options) {
    //自助积分 需要openId 且必须写在onshow里面
    let _this = this
    if (businessSwitch && wx.getStorageSync('openId')) {
      myPluginInterface.getLocation(wx.getStorageSync('openId')).then(res => { console.log("商圈位置授权onS") })
    }
    // if (businessSwitch) {
    //   wx.login({
    //     success: (res) => {
    //       if (wx.getStorageSync('openId')) {
    //         myPluginInterface.getLocation(wx.getStorageSync('openId')).then(res => {})
    //       } else {
    //         if (res.code) {
    //           let usrdata = {
    //             appId: config.weapp.AppId,
    //             code: res.code,
    //           }
    //           Http.post({
    //             url: config.api.login,
    //             data: usrdata
    //           }).then(res => {
    //             if (_this.data.businessSwitch) {
    //               myPluginInterface.getLocation(res.data.openId).then(res => {
    //                 console.log(res, "我是地理位置")
    //               })
    //             }
    //           })
    //         }
    //       }

    //     }
    //   })
    // }


  },
  statusBarHeight: 0,
  /**
   * 用户登录
   */
  userLogin: function (sceneAddress) {
    let that = this;
    // 登录
    wx.login({
      success: ({
        code
      }) => {
        let usrdata = {
          appId: config.weapp.AppId,
          code: code,
          sceneAddress: sceneAddress
        }
        if (that.globalData.newArr && that.globalData.newArr[1] == 'in_u') {
          usrdata.UId = that.globalData.newArr[2]
        } else if (that.globalData.newArr && that.globalData.newArr[1] == 'md') {
          usrdata.MId = that.globalData.newArr[2]
        }
        Http.post({
          url: config.api.login,
          data: usrdata
        })
          .then(res => {
            console.log(res.data, "login!!!!!!!!!!!");
            const isAgreeProtocol = res.data.agreeProtocol ? 1 : 0
            wx.setStorageSync("isAgreeProtocol", isAgreeProtocol)

            if (res.data.mall) {
              that.globalData.marketName = res.data.mall.name ? res.data.mall.name : ""
            }
            wx.setStorageSync('openId', res.data.openId)
            if (businessSwitch && res.data.openId) {
              myPluginInterface.getLocation(res.data.openId).then(res => { console.log("商圈位置授权onL") }).catch(err => {
                console.log(err, "商圈位置授权onL err")
              })
            }
            if (res.data && res.data.mouldType == 0) {//原风格尺寸
              this.globalData.goHomeUrl = "/index/index"
              this.globalData.mouldConfig = defaultObj
            } else if (res.data && res.data.mouldType == 1) {
              this.globalData.goHomeUrl = "/pages/theme/index1/index"
              this.globalData.mouldConfig = huanLeChengObj
            }
            that.globalData.mouldType = res.data.mouldType ? res.data.mouldType : 0
            if (res.data.subMalls) {
              const squareList = JSON.parse(res.data.subMalls)
              wx.setStorageSync("squareList", squareList)
            }
            if (res.data.mall) {
              wx.setStorageSync("selectedMall", res.data.mall.tenantId)
            }
            if (res.data && res.data.score) {
              if (res.data.score != 0) {
                that.globalData.score = res.data.score;
              }
            }
            Http.setToken(res.data.token);
            that.globalData.token = res.data.token;
            console.log(that.tokenCallback, "that.tokenCallback")


            if (that.tokenCallback) {
              that.tokenCallback(res.data.token);
            }
          })
          .catch(err => {
            console.log(err)
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '登录失败，请重新尝试',
              success: function (res) {
                if (res.cancel) {
                  //点击取消,默认隐藏弹框
                } else {
                  //点击确定
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          })
      }
    })
  },
  autoUpdate: function () {
    let that = this;
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      // 1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          // 检测到新版本，需要更新，给出提示
          wx.showModal({
            title: '更新提示',
            content: '检测到新版本，是否下载新版本并重启小程序？',
            success: function (res) {
              if (res.confirm) {
                //2. 用户确定下载更新小程序，小程序下载及更新静默进行
                that.downLoadAndUpdate(updateManager)
              } else if (res.cancel) {
                //用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                wx.showModal({
                  title: '温馨提示~',
                  content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                  showCancel: false, //隐藏取消按钮
                  confirmText: "确定更新", //只保留确定更新按钮
                  success: function (res) {
                    if (res.confirm) {
                      //下载新版本，并重新应用
                      that.downLoadAndUpdate(updateManager)
                    }
                  }
                })
              }
            }
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  /**
   * 下载小程序新版本并重启应用
   */
  downLoadAndUpdate: function (updateManager) {
    let that = this
    wx.showLoading();
    //静默下载更新小程序新版本
    updateManager.onUpdateReady(function () {
      wx.hideLoading()
      //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
      updateManager.applyUpdate()
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
      })
    })
  },
  globalData: {
    userName: "",//用户名
    userAvatarUrl: "",//用户头像地址
    goHomeUrl: '/index/index',
    mouldConfig: {},//模板尺寸
    mouldType: 0,//主题风格模板
    styleLsit: {},
    previewFlag: false, //解决图片预览调用noshow
    activityId: '', //活动id方便授权数据回传
    typeLsit: [], //初始哈样式
    scene: "",
    // token
    token: null,
    // user openId
    openId: null,
    // 渠道
    sceneAddress: null,
    // location info
    locationInfo: null,
    // 二维码参数
    scene: null,
    // 支持智慧停车, 用户名下有车
    phone: null,
    supportCar: false,
    parkVendor: 1, // 1-ETCP, 2-TJD停简单 3-Dahua大华, 4-ShangAn尚安, 5-BoLink泊链
    // ETCP token
    etcpToken: null,
    carLogin: false,
    marketName: "",//商场，名称
    // 当前商场信息
    market: {
      name: ""
    },
    // websocket
    socketClient: null,
    socketReceiver: function (e) { }, //收到消息回调
    curHtml: '', //富文本相关，由于浏览器传参长度有限制
  },

  // 初始化websocket
  initSocket: function () {
    let that = this;
    // socket是否连接
    let socketConnected = false;
    // 待发送的消息队列
    let messageQueue = [];
    // 是否断线重连
    let reconnect = true;

    // 发送消息
    function sendSocketMessage(msg) {
      // console.log(msg);
      // 如果socket已连接则发送消息
      if (socketConnected) {
        wx.sendSocketMessage({
          data: msg
        })
      } else {
        // socket没有连接将消息放入队列中
        messageQueue.push(msg);
      }
    }

    // 关闭连接
    function close() {
      if (socketConnected) {
        wx.closeSocket()
        socketConnected = false;
      }
    }

    // 符合WebSocket定义的对象
    var ws = {
      send: sendSocketMessage,
      close: close
    }

    // 创建一个 WebSocket 连接
    function connect() {
      wx.connectSocket({
        url: config.wsurl,
        header: {
          token: that.globalData.token //从服务端获取一个token，服务端验证token是否允许连接,案例中没做限制
        }
      })
    }
    connect();

    // 监听 WebSocket 连接打开事件
    wx.onSocketOpen(function (res) {
      console.log("WebSocket 连接成功")
      socketConnected = true;
      ws.onopen();
      // 连接成功后，将队列中的消息发送出去
      let queueLength = messageQueue.length
      for (let i = 0; i < queueLength; i++) {
        sendSocketMessage(messageQueue.shift())
      }
    })

    // 监听 WebSocket 接受到服务器的消息事件
    wx.onSocketMessage(function (res) {
      ws.onmessage(res);
    })

    // 监听 WebSocket 错误事件
    wx.onSocketError(function (res) {
      console.log("WebSocket 错误事件")
      if (!socketConnected) {
        // 断线重连
        if (reconnect) {
          connect();
        }
      }
    })

    // 监听 WebSocket 连接关闭事件
    wx.onSocketClose(function (res) {
      console.log("WebSocket 连接关闭")
      socketConnected = false;
      // 断线重连
      if (reconnect) {
        connect();
      }
    })

    const Stomp = require('/utils/stomp.min.js').Stomp;

    /**
     * 定期发送心跳或检测服务器心跳
     *  The heart-beating is using window.setInterval() to regularly send heart-beats and/or check server heart-beats.
     *  可看stomp.js的源码（195,207，489行），由于小程序没有window对象，所以我们要调用小程序的定时器api实现
     */
    Stomp.setInterval = function (interval, f) {
      return setInterval(f, interval);
    };
    // 结束定时器的循环调用
    Stomp.clearInterval = function (id) {
      return clearInterval(id);
    };

    const stompClient = Stomp.over(ws);

    that.globalData.socketClient = stompClient;

    stompClient.connect({}, function (callback) {

      // 订阅自己的
      stompClient.subscribe('/user/' + config.weapp.AppId + '/' + that.globalData.openId + '/message', function (message, headers) {
        console.log('收到只发送给我的消息:', message);
        that.globalData.socketReceiver(JSON.parse(message.body));
        // 通知服务端收到消息
        message.ack();
      });

      stompClient.subscribe('/topic/' + config.weapp.AppId, function (message, headers) {
        console.log('收到TOPIC的消息:', message);
        that.globalData.socketReceiver(JSON.parse(message.body));
        // 通知服务端收到消息
        //message.ack();
      });

      // 向服务端发送消息
      stompClient.send("/app/message", {}, JSON.stringify({
        'msg': 'client: ' + that.globalData.openId
      }));
    })
  },

  //统一发送消息
  sendSocketMessage: function (msg) {
    this.globalData.socketClient.send("/app/message", {}, JSON.stringify(msg));
  }
});
// wxfa336cad86ed598d 测试
// wx453ae0d37f3550d0 生产