const tempId = 'klJpOQl9j5FSOB-enbs0KDXZ-8OGivhr8AnLDAeE2xk'

export const getSubOpen = () => {
  let userInfo = wx.getStorageSync('userInfo');
  // console.error(userInfo)
  // userInfo.isAdmin = true
  if (!userInfo.isAdmin) {
    return;
  }
  
  wx.getSetting({
    withSubscriptions: true,
    success: res => {
      let itemSettings = res.subscriptionsSetting
      if (!itemSettings || !itemSettings[tempId] || itemSettings[tempId] === 'reject') {
        wx.showModal({
          title: '温馨提示',
          content: '您是工作人员，请允许消息推送',
          showCancel: true, //是否显示取消按钮
          cancelText: "取消", //默认是“取消”
          confirmText: "确定", //默认是“确定”
          success: (res) => {
            authMsg() 
          }
        })
      }
    }
  })
}

export const authMsg = () => {
  wx.requestSubscribeMessage({
    tmplIds: [tempId],
    success(res) {
      console.log('成功订阅消息', res)
      if (res[tempId] === 'reject') {
        rejectAuth()
      }
    },
    fail: (e) => {
      console.error(e)
      if (e.errCode === 20004) {
        rejectAuth()
      }
    }
  })
}

export const rejectAuth = () => {
  wx.showModal({
    title: '温馨提示',
    content: '您关闭了授权，将跳转到设置页面，请打开VR带看提醒开关',
    showCancel: true, //是否显示取消按钮
    cancelText: "取消", //默认是“取消”
    confirmText: "确定", //默认是“确定”
    success: (res) => {
      wx.openSetting({
        withSubscriptions: true,
        success: (res) => {
          if (!res.subscriptionsSetting.mainSwitch) {
            this.getSubOpen()
          }
        }
      })
    }
  })
}