'use api/lib/protect.js'

let qs = require('querystring')

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://auth.cloud.alipay.com/webapi/auth/queryQrCodeStatus",
            "headers": {
                "referrer": "https://usercenterweb.antdigital.com/",
                "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
            },
            "content_type": "application/json",
            "data": JSON.stringify({
                "qrCodeToken": code
            }),
        }

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

        data = res.body.toObject()
        if (data.result?.qrCodeStauts) {
            switch (data.result.qrCodeStauts) {
                case "SCANNED":
                    if (!status) {
                        sse.send(sessionId, 'info', '扫码成功，请在手机上确认登录')
                        status = true
                    }
                    continue
                case "WAIT":
                    continue
                case "EXPIRE":
                    sse.send(sessionId, 'panic', '二维码已失效，请刷新二维码重新扫描')
                    return ''
                case "AUTHORIZED":
                    break
                default:
                    console.log(JSON.stringify(data))
                    continue
            }
        }
        break
    }

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

    let authData = data.result.authorization

    req = {
        "method": "GET",
        "url": "https://user.antdigital.com/webapi/usercenter/user",
        "headers": {
            "authorization": authData,
            "referrer": "https://usercenterweb.antdigital.com/",
            "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
        }
    }

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

    let userInfo = data.result.userInfo

    // 判断是否注册支付宝云服务
    if (!userInfo.antchainCertified) {
        req = {
            "method": "POST",
            "url": "https://achelmetcore.antdigital.com/webapi/helmet/security/process",
            "headers": {
                "authorization": authData,
                "referrer": "https://usercenterweb.antdigital.com/",
                "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
            },
            "content_type": "application/json",
            "data": JSON.stringify({ "bizTag": "CUSTOMER_ENTRY", "bizOp": "POST", "opId": userInfo.customerId }),
        }
        res = request.parse(req)
        if (res.status_code != 200) {
            sse.send(sessionId, 'panic', '安全验证失败，请选择其他登录方式')
            return ''
        }
        data = res.body.toObject()
        req = {
            "method": "POST",
            "url": `https://user.antdigital.com/webapi/usercenter/tenants/${userInfo.customerId}/initResources?`,
            "headers": {
                "authorization": authData,
                "referrer": "https://usercenterweb.antdigital.com/",
                "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
            },
        }
        req.url += qs.stringify({
            "tenantUniqueId": userInfo.customerId,
            "tenantLevel": "N",
            "securityId": data.data.securityId,
            "create": true,
        })
        res = request.parse(req)
        if (res.status_code != 200) {
            sse.send(sessionId, 'panic', '安全验证失败，请选择其他登录方式')
            return ''
        }
        // console.log('扫码注册成功')
    }
    // console.log('登录初始化完成')

    req = {
        "method": "GET",
        "url": "https://adminnew.cloud.alipay.com/onexapi/user/projects",
        "headers": {
            "authorization": authData,
            "referrer": "https://usercenterweb.antdigital.com/",
            "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
        },
    }

    res = request.parse(req)
    if (res.status_code != 200) {
        sse.send(sessionId, 'panic', '身份验证失败，请刷新重试或选择其他登录方式')
        return ''
    }

    data = res.body.toObject().result[0].id
    console.log(data)

    req = {
        "method": "GET",
        "url": `https://adminnew.cloud.alipay.com/webapi/aciamweb/identity/users/accountInfo?tenantId=${data}`,
        "headers": {
            "authorization": authData,
            "x-onex-product-api-domain": "https://admin.cloud.alipay.com",
            "user-agent": "Mozilla/5.0 (X11; CrOS x86_64 8.8.260206) AppleWebKit"
        },
    }

    res = request.parse(req)
    data = res.body.toString()
    if (res.status_code != 200) {
        sse.send(sessionId, 'panic', '身份同步失败，请刷新重试或选择其他登录方式')
        return ''
    }

    data = res.body.toObject()
    // console.log(JSON.stringify(data))

    let userPhone = data.data.masterVO.gotoneAccountMap.MOBILE
    // 查找用户表
    res = SQL.query('system_sql', `SELECT * FROM sys_users WHERE phone = ? OR idno = ?;`, userPhone, data.data.masterVO.certNo);

    // 生成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) {
            SQL.push('system_sql', `UPDATE sys_users SET real_name = ?,idno = ? WHERE phone = ?`, data.data.masterVO.realName, data.data.masterVO.certNo, userPhone)
        }
    } 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,real_name,idno,phone) VALUES (?,?,?,?)`, userId, data.data.masterVO.certNo, data.data.masterVO.realName, data.data.masterVO.realName, data.data.masterVO.certNo, userPhone)
        if (!res) {
            sse.send(sessionId, 'panic', '扫码注册失败')
            return ''
        }
        sse.send(sessionId, 'success', '扫码注册成功')
        userData = {
            user_id: userId,
            username: data.data.masterVO.certNo,
            nickname: data.data.masterVO.realName,
            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, }
    sse.send(sessionId, 'login', JSON.stringify(result))
    sse.send(sessionId, 'success', '扫码登录成功')

    return okMsg(data.result)
}

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