function main() {
    const corpid = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_corpid').value;
    const appkey = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_appkey').value;
    const appid = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_clientId').value;
    const appsecret = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_appsecret').value;
    const accessToken = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_access_token').value;

    let domain = payload.get().headers["Origin"]
    if (!domain) {
        domain = payload.get().headers["Referer"]
    }

    if (payload.get().query.callback) {
        response.headers.set("Location", `https://login.dingtalk.com/oauth2/auth?redirect_uri=${payload.get().query.callback || 'https://l-l.cn/app/login'}&response_type=code&client_id=${appkey}&scope=openid&state=dingtalk&prompt=consent`)
        response.status.movedPermanently()
        return ''
    }

    // 成功时跳转到：https://www.aaaaa.com/a/b?authCode=xxxx&state=dddd
    // 失败时跳转到：https://www.aaaaa.com/a/b?error=yyyyyy&state=dddd

    // if (payload.get().query["error"]) {
    //     return errMsg(511, `授权失败,错误: ${payload.get().query["error"]}`)
    // }

    // 通过回调Code换取AccessToken
    let req = {
        url: `https://api.dingtalk.com/v1.0/oauth2/userAccessToken`,
        method: 'POST',
        content_type: 'application/json',
        data: JSON.stringify({
            clientId: appkey,
            clientSecret: appsecret,
            code: payload.get().path.split('/').pop(),
            // "refreshToken": "String",
            grantType: "authorization_code"
        })
    }


    // console.log(request.toCURL(req))

    let res = request.parse(req).body.toObject()
    //     {
    //   "accessToken" : "abcd",
    //   "refreshToken" : "abcd",
    //   "expireIn" : 7200,
    //   "corpId" : "corpxxxx"
    // }
    
    // console.log(JSON.stringify(res))

    if (!res.accessToken) {
        // {"requestid":"AF130F96-1BB8-7FB1-A21B-2B29842D2D82","code":"invalidParameter.authCode.notFound","message":"不合法的临时授权码"}
        return errMsg(511, `Token获取失败,错误代码: ${res.code},错误信息: ${res.message}`)
    }

    // 通过AccessToken换取用户信息
    req = {
        url: `https://api.dingtalk.com/v1.0/contact/users/me`,
        headers: {
            'x-acs-dingtalk-access-token': res.accessToken,
        }
    }

    res = request.parse(req).body.toObject()
    //     {
    //   "nick" : "zhangsan",
    //   "avatarUrl" : "https://xxx",
    //   "mobile" : "150xxxx9144",
    //   "openId" : "123",
    //   "unionId" : "z21HjQliSzpw0Yxxxx",
    //   "email" : "zhangsan@alibaba-inc.com",
    //   "stateCode" : "86"
    // }

    // console.log(JSON.stringify(res))
    // {"mobile":"17768938295","nick":"舒榆衡","openId":"XlH9GxRUh4oqoDBnf7OWWAiEiE","stateCode":"86","unionId":"ZQOFXUqiPZQcuSiPHZr45gJAiEiE","visitor":false}

    if (!res.mobile) {
        return errMsg(511, `Token验证不通过,错误代码: ${res.code},错误信息: ${res.message}`)
    }

    // 'use api/user/oauth/getUser.js'

    // 绑定用户
    // SQL.push('system_sql', "INSERT INTO sys_users_oauth (relate_id, user_id, login_from, open_id, union_id, username, avatar_img, raw_info) VALUES (?,?,?,?,?,?,?)",
    //     ex.suid().base58(), tokenInfo.uid, 1, res.openid, res.unionId, res.nick, res.avatarUrl, JSON.stringify(res))
    // return okMsg("绑定成功")

    // 查找用户表
    res = SQL.query('system_sql', `SELECT * FROM sys_users WHERE phone = ?;`, res.mobile);


    // console.log(JSON.stringify(res))
    // 生成Token / 7天后过期
    const sevenDays = parseInt((new Date().getTime() + 1000 * 60 * 60 * 24 * 7) / 1000);

    let userData
    // 如果用户在系统内已存在
    if (res && res.length) {
        userData = res[0];
        // if (!userData.idno) {
        // res = SQL.push('system_sql', `UPDATE sys_users SET real_name = ?,idno = ? WHERE phone = ?`, userInfo.clientname, userInfo.idnumber, userInfo.mobile)
        // }
    } else {
        // if (!userInfo.mobile) {
        return errMsg(503, '未绑定用户信息，请选择其他登录方式')
        // }
        // let userId = ex.suid().base58()
        // res = SQL.exec('system_sql', `INSERT INTO sys_users (user_id,username,nickname,real_name,idno,phone) VALUES (?,?,?,?)`, userId, userInfo.idnumber, userInfo.clientname, userInfo.clientname, userInfo.idnumber, userInfo.mobile)
        // if (!res) {
        //     return errMsg(500, '扫码注册失败')
        // }
        // userData = {
        //     user_id: userId,
        //     username: userInfo.idnumber,
        //     nickname: userInfo.clientname,
        //     phone: userInfo.mobile,
        //     role_id: 'hShxtTny1zo',
        //     role_key: '',
        // }
    }

    let token = jwt_issue(userData.user_id, userData.nickname);
    // 更新最后登录时间
    SQL.push('system_sql', 'UPDATE sys_users SET last_login_time = NOW(),last_login_ip = ? WHERE user_id =?', userData.ip, userData.user_id);

    let uaInfo = ex.parseUserAgent(payload.get().headers['User-Agent'][0]);
    let userIp = payload.get().remote_addr.split(':')[0]

    log(uaInfo, userData, userIp, 0)

    response.cookies.setRaw(`token=${token}; Path=/; Max-Age=604800; SameSite=Strict; CrossSite=Strict; Priority=High; PartitionKeySite=Main; HttpOnly; Secure`)
    // response.headers.set("Location", `${payload.get().query.ref}?secret=${encryptData(token)}`)
    // response.status.movedPermanently()
    return okMsg(jwt_parse(token))
}

function log(uaInfo, USER_INFO, addr, status) {
    if (addr == null) {
        return
    }

    // 记录登录日志
    SQL.push(DB_NAME, 'INSERT INTO log_logins (info_id, user_id, username, status, ipaddr, login_location, browser, os, platform, ua) VALUES (?,?,?,?,?,?,?,?,?,?)',
        ex.suid().base58(),
        USER_INFO.user_id,
        USER_INFO.username,
        status,
        addr,
        '未知',
        uaInfo.browser,
        uaInfo.os,
        uaInfo.deviceModel,
        payload.get().headers['User-Agent'][0],
    );
}