'use api/lib/protect.js'

function main() {
    let req
    let res
    let data // 登录数据
    let status // 扫码状态
    let worker = request.new()
    let sessionId = args[0]
    let code = args[1]
    while (true) {
        req = {
            "method": "POST",
            "url": "https://login.dingtalk.com/oauth2/login_with_qr",
            "headers": {
                "referrer": "https://login.dingtalk.com/",
                "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
            },
            "content_type": "application/x-www-form-urlencoded",
            "data": "client_id=dingtsp2ukmhfppwl6xy&code=" + code,
        }

        res = worker.parse(req)
        if (res.status_code != 200) {
            sse.send(sessionId, 'panic', '扫码登录失败，请刷新重试或选择其他登录方式')
            continue
        }

        data = res.body.toObject()
        if (data.errorCode) {
            switch (data.errorCode) {
                case "11041":
                    if (!status) {
                        sse.send(sessionId, 'info', '扫码成功，请在手机上确认登录')
                        status = true
                    }
                    continue
                case "11019":
                    sse.send(sessionId, 'panic', '二维码已失效，请刷新二维码重新扫描')
                    return ''
                default:
                    continue
            }
        }
        break
    }

    if (!data.result) {
        sse.send(sessionId, 'panic', '扫码登录失败，请刷新重试或选择其他登录方式')
        return ''
    }

    let userPhone
    if (data.result.exclusiveCorpId) {
        if (data.result.exclusiveCorpId != 'ding61bdb62c9797ae404ac5d6980864d335') {
            sse.send(sessionId, 'panic', '请使用云上开投APP进行扫码登录')
            return ''
        }

        // 通过私有化钉钉登录成功，通过返回的手机号检索用户
        userPhone = data.result.exclusiveMobile.replaceAll('+86-', '')
        // 查找用户表
        res = SQL.query('system_sql', `SELECT * FROM sys_users WHERE phone = ?`, userPhone);
    } else {
        // 通过钉钉扫码登录
        req = {
            "method": "POST",
            "url": "https://docs.dingtalk.com/portal/api/v1/token/getAccessToken",
        }

        res = worker.parse(req)
        if (res.status_code != 200) {
            sse.send(sessionId, 'panic', '用户授权获取失败，请刷新重试或选择其他登录方式')
            return ''
        }
        let data = res.body.toObject()
        // console.log(JSON.stringify(data))
        let accessToken = data.data.accessToken

        req = {
            "method": "POST",
            "url": "https://docs.dingtalk.com/api/users/getUserInfo",
            "headers": {
                "a-token": accessToken,
            },
        }

        res = worker.parse(req)
        if (res.status_code != 200) {
            sse.send(sessionId, 'panic', '用户信息获取失败，请刷新重试或选择其他登录方式')
            return ''
        }

        data = res.body.toObject().data

        // 查找用户表
        res = SQL.query('system_sql', `SELECT * FROM sys_users WHERE user_id = (SELECT user_id FROM sys_users_oauth WHERE login_from = 'dingtalk' AND open_id = ?)`, data.user.uid);
    }

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

    let userData
    // 如果用户在系统内已存在
    if (res && res.length) {
        userData = res[0];
    } else {
        if (!userPhone) {
            sse.send(sessionId, 'panic', '未绑定用户信息，请选择其他登录方式')
            return ''
        }
        let userId = ex.suid().base58()
        res = SQL.exec('system_sql', `INSERT INTO sys_users (user_id,username,nickname,phone) VALUES (?,?,?,?)`, userId, data.result.exclusiveUserId, data.result.nick, userPhone)
        if (!res) {
            sse.send(sessionId, 'panic', '扫码注册失败')
            return ''
        }
        sse.send(sessionId, 'success', '扫码注册成功')
        userData = {
            user_id: userId,
            username: data.result.exclusiveUserId,
            nickname: data.result.nick,
            phone: userPhone,
            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)

    result = { expire: sevenDays, secret: encryptData(token), userId: userData.user_id, needVerify: !userData.idno }
    sse.send(sessionId, 'login', JSON.stringify(result))
    sse.send(sessionId, 'success', '扫码登录成功')

    return
}

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],
    );
}