/**
 * VisionKit 视觉能力状态码
 * @param {number} state 状态码
 * @param {boolean} user 用户可操作的项
 * @param {string} msg 状态信息
 */
export const VK_STATE = [
  {
    "state": 0,
    "user": false,
    "msg": "成功"
  },
  {
    "state": 104,
    "user": true,
    "msg": "用户取消授权"
  },
  {
    "state": 112,
    "user": false,
    "msg": "接口未在隐私协议中声明"
  },
  {
    "state": 1025,
    "user": false,
    "msg": "小程序隐私接口被封禁，解决方案参考链接"
  },
  {
    "state": 1026,
    "user": false,
    "msg": "小游戏隐私接口被封禁，解决方案参考链接"
  },
  {
    "state": 2000001,
    "user": false,
    "msg": "参数错误"
  },
  {
    "state": 2003000,
    "user": false,
    "msg": "会话不可用"
  },
  {
    "state": 2000000,
    "user": false,
    "msg": "系统错误"
  },
  {
    "state": 2000002,
    "user": false,
    "msg": "设备不支持"
  },
  {
    "state": 2000003,
    "user": false,
    "msg": "系统不支持"
  },
  {
    "state": 2000004,
    "user": false,
    "msg": "设备不支持"
  },
  {
    "state": 2003001,
    "user": true,
    "msg": "未开启系统相机权限"
  },
  {
    "state": 2003002,
    "user": true,
    "msg": "未开启小程序相机权限"
  }
]
/**
 * 检测当前设备VisionKit 支持版本
 * 如果不是用户可操作的状态，直接取上一次的值
 * v1 / v2 是硬件问题，不需要重复检测
 */
export const checkVKVsion = async () => {
  return new Promise(reslove => {
    const v1 = wx.getStorageSync('vk_version1_err')
    const v2 = wx.getStorageSync('vk_version2_err')
    if (v1 && !VK_STATE.find(el => el.state === v1)?.user) {
      reslove(null)
    } else if (v2 && !VK_STATE.find(el => el.state === v2)?.user) {
      reslove('v1')
    } else {
      const session_v2 = wx.createVKSession({
        track: {
          plane: {
            mode: 1
          },
        },
        version: 'v2'
      })
      const session_v1 = wx.createVKSession({
        track: {
          plane: {
            mode: 3
          },
        },
        version: 'v1',
      })
      session_v2.start((err2) => {
        if (err2) {
          wx.setStorageSync('vk_version2_err', err2)
          session_v1.start(err1 => {
            if (err1) {
              wx.setStorageSync('vk_version1_err', err1)
              reslove(null)
            } else {
              reslove('v1')
            }
            session_v1.destroy()
          })
        } else {
          reslove('v2')
        }
        session_v2.destroy()
      })
    }
  })
}
