// ------ 用户登录 --------
cache.new('link-auth')

'use api/lib/protect.js'

function main() {
    response.headers.set("Cache-Control", "no-cache, no-store, must-revalidate") // 禁用缓存
    switch (payload.get().method) {
        case 'GET':
            return auth()
        case 'POST':
            return login()
        default:
            response.status.notFound()
            return `404 page not found`
    }
}

function login() {
    const username = payload.get().path.split('/').pop()
    // 设置登录缓存，60秒内仅允许请求一次
    // if (cache.get('link-auth', username)) {
    //     return errMsg(511, '请勿重复请求');
    // }

    let loginType = 'username'

    // 手机号
    if (username.match(/^\d+$/)) {
        loginType = 'phone'
    }
    // 身份证号
    else if (username.match(/^\d{17}[\dXx]$/)) {
        loginType = 'idno'
    }
    // 邮箱
    else if (username.match(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)) {
        loginType = 'email'
    }


    // 查找用户表
    const res = SQL.query('system_sql', `SELECT * FROM sys_users WHERE ${loginType} = ?`, username);

    if (res && res.length) {
        const userData = res[0];

        userData.ip = payload.get().remote_addr.split(':')[0]

        const id = ex.suid().base58();
        cache.set('link-auth', id, userData, 180 * 1000)

        // let sendId = encoding.from(id).toBase58.encoding().toString()
        // 如果存在Origin头，则优先使用Origin头中的域名，否则使用Referer头中的域名。
        let sid = runtime.call('api/utils/sortUrl/function.js', `https://x.p-q.co/app/auth/confirm.html?code=${id}`).short_url.sid
        let msg = `【仓湖】您正在进行账户登陆操作,请通过 dx5.cn/${sid} 完成身份验证,若非您本人操作,请勿点击并警惕账户安全风险。`
        loginType = 'sms'
        let sendScript = 'api/utils/sms/send.js'
        let hasDingAccount = runtime.call('api/utils/yskt/checkPhone.js', userData.phone)
        if (hasDingAccount) {
            loginType = 'ding'
            sendScript = 'api/utils/yskt/sendMsg.js'
            msg = msg.replace('dx5.cn', 'https://dx5.cn')
        }

        // 发送短信
        runtime.exec(sendScript, userData.phone, msg, userData.nickname)
        // console.log('send:', id)

        const code = encryptData(id)
        return okMsg({ code: code, type: loginType, needVerify: !userData.idno });
    }

    return errMsg(511, '用户不存在');
}

function auth() {
    if (!payload.get().headers['User-Agent']) {
        return errMsg(413, '参数错误');
    }

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

    let id = payload.get().path.split('/').pop()

    const userData = cache.get('link-auth', id)
    if (!userData) {
        return errMsg(511, '会话过期');
    }

    // 根据角色id获取key
    // const roleRes = SQL.query(DB_NAME, 'SELECT role_key FROM sys_roles WHERE role_id = ?', userData.role_id);

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

    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);
    log(uaInfo, userData, payload.get().remote_addr.split(':')[0], 0)
    // response.headers.set('Authorization', 'Bearer ' + token)
    // let sessionToken = `token=${token}; Path=/; Max-Age=604800; SameSite=Strict; CrossSite=Strict; Priority=High; Partitioned; HttpOnly; Secure`
    // response.cookies.setRaw(sessionToken)
    let result = { expire: sevenDays, secret: encryptData(token), userId: userData.user_id, sessionId: encryptData(id), needVerify: !userData.idno }
    // let result = { expire: sevenDays, userId: userData.user_id, ip: userData.ip, sessionId: encryptData(id) }
    sse.send(result.sessionId, 'login', JSON.stringify(result))
    // cache.set('link-auth', id, result, 180 * 1000)
    return okMsg(true);
}

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