'use api/lib/protect.js'

let qs = require('querystring')

function main() {
    response.headers.set("Cache-Control", "no-cache, no-store, must-revalidate") // 禁用缓存

    let client_id = '7f5630ca-6bd1-4286-b8ee-297612c19417'

    let params = {
        'client_id': client_id,
        'utype': 0,
        'goto': `https://l-l.cn/api/user/oauth/xjgov?ref=${payload.get().query.ref ? payload.get().query.ref[0] : payload.get().headers["Referer"]}`,
        'state': ex.suid().base58(),
    }

    if (!payload.get().query.code) {
        response.headers.set("Location", `https://zwfw.xinjiang.gov.cn/xjwwrz/sso/login?${qs.stringify(params)}`)
        response.status.movedPermanently()
        return ''
    }

    params = {
        'code': payload.get().query.code[0],
        'client_id': client_id,
        'client_secret': '24005520-d812-465c-9c2d-bdc38f1f3d81',
        // 'redirect_uri': 'https://l-l.cn/api/oauth/xjzw',
        'grant_type': 'authorization_code',
    }

    let req = {
        "method": "POST",
        "url": `https://zwfw.xinjiang.gov.cn/xjwwrz/rest/oauth2/token?${qs.stringify(params)}`,
    }

    let res = request.parse(req)
    if (res.status_code != 200) {
        return errMsg(503, '获取登录授权失败')
    }

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

    req = {
        "method": "POST",
        "url": "https://zwfw.xinjiang.gov.cn/xjwwrz/rest/extranetNeedLoginInterfaceapp/getUserDataForAppEntryt",
        "headers": {
            "authorization": `Bearer ${data.access_token}`,
        }
    }

    res = request.parse(req)
    if (res.status_code != 200) {
        return errMsg(503, '登录失败，请刷新重试或选择其他登录方式')
    }
    data = res.body.toObject()
    // console.log(JSON.stringify(data))

    let userInfo = data.custom
    userInfo.mobile = decode(userInfo.mobile)
    userInfo.idnumber = decode(userInfo.idnumber)

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

    // 生成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(userInfo)
}

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

function decode(data) {
    return crypto.aes.decrypt("ECB", 'xjwwrz2020032318', encoding.from(data).toHEX.decoding().Bytes).toString()
}