routerAdd('POST', '/api/system/refresh-token', function (e) {
    const guards = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/middlewares/requestGuards.js`)
    const userService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/userService.js`)
    const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`)
    const { successWithToken, fail } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/response.js`)

    try {
        guards.requireJson(e)
        guards.duplicateGuard(e)

        const payload = guards.validateSystemRefreshBody(e)

        if (e.auth && e.auth.collection().name === 'tbl_auth_users' && e.auth.getString('openid')) {
            const openid = e.auth.getString('openid')
            const data = userService.refreshAuthToken(openid)
            const token = userService.issueAuthToken(data.authRecord)

            return successWithToken(e, '刷新成功', {}, token)
        }

        if (!payload.users_wx_code) {
            return fail(e, 'token已过期，请上传users_wx_code', {}, 401)
        }

        const authData = userService.authenticateWechatUser(payload)
        const token = userService.issueAuthToken(authData.authRecord)

        return successWithToken(e, '刷新成功', {}, token)
    } catch (err) {
        const status =
            (err && typeof err.statusCode === 'number' && err.statusCode)
            || (err && typeof err.status === 'number' && err.status)
            || 400

        logger.error('系统刷新令牌失败', {
            status: status,
            errMsg: (err && err.message) || '未知错误',
            data: (err && err.data) || {},
        })

        return fail(e, (err && err.message) || '操作失败', (err && err.data) || {}, status)
    }
})




