{"size": 7865, "ext": "js", "max_stars_repo_path": "model/user.js", "max_stars_repo_name": "Skylae/wenbo-system2", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model/user.js", "max_issues_repo_name": "Skylae/wenbo-system2", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model/user.js", "max_forks_repo_name": "Skylae/wenbo-system2", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.2442396313, "max_line_length": 279, "alphanum_fraction": 0.4851875397}
const { reject } = require('bcrypt/promises');
const res = require('express/lib/response');
const { resolve } = require('path');

module.exports = class User extends require('./model') {
    // 登录模型
    static login(username){
        return new Promise((resolve, reject) => {
            let sql = "select id, username, password, isSuper from user where username = ?";
            this.query(sql, username).then(result => {
                resolve(result[0]);
            }, err => {
                console.log(`用户查询失败：${err.message}`);
                reject(err);
            })
        })
    }

    // 用于识别用户是否已经登录
    static async session_isExist(req){
        return new Promise((resolve, reject) => {
            let session_exist = false;  //用于判断用户是否多处登录。默认没有异地登录
            //查询sessionStore里面所有session，是否有user且user.id等于当前要登录的user_id，且session时间没有过期。有则多处登录，没有则可以登录
            req.sessionStore.all((err, sessions) => {
                if (err) {
                    console.log(`sessionStore查询失败：${err}`);
                }
                else {
                    for (let session in sessions) {
                        console.log('异地登录验证中的expires：'+new Date(sessions[session].cookie.expires).getTime())
                        console.log(`现在的时间：`+new Date().getTime())

                        if ((new Date(sessions[session].cookie.expires).getTime() >= new Date().getTime()) && sessions[session].user && sessions[session].user.id == req.login.id) {
                            session_exist = true;
                        }
                    }
                    resolve(session_exist);
                }
            })
        })
    }

    // 更新删除sessionStore中过期的session
    static updateSessionStore(req){
        return new Promise((resolve, reject) => {
            req.sessionStore.all((err, sessions) => {
                if(err){
                    console.log(`更新sessionStore失败`)
                    reject(err);
                }
                else {
                    for(let sid in sessions){
                        if( sessions[sid] && (new Date(sessions[sid].cookie.expires).getTime() < new Date().getTime())){
                            req.sessionStore.destroy(sid);
                            req.sessionStore.save();
                        }
                    }
                    resolve(true);
                }
            })
        })
    }

    // 查询 所有发表过文章的管理员
    static getUsersByPublished(){
        return new Promise((resolve, reject) => {
            let sql = 'select distinct article.user_id, user.username as user_name from (select * from aboutus union select * from members union select * from news union select* from projects union select * from researches) as article left join user on article.user_id = user.id'
            this.query(sql).then(results => {
                resolve(results);
            }).catch(err => {
                console.log(`发表人查询失败：${err.message}`)
                reject(err);
            })
        })
    }

    // 获取该用户最后登录时间，不存在返回null
    static lastLoginTime(user_id) {
        return new Promise((resolve, reject) => {
            let sql = 'select time from log where handle = "登录" and user_id = ? order by time desc limit 1, 1';
            this.query(sql, user_id).then(result => {
                if(result[0]){
                    resolve(result[0].time);
                }
                else{
                    resolve(null)
                }
            }, err => {
                console.log(`登录日志查询失败：${err.message}`);
                reject(err);
            });
        })
    }

    // 查询 所有同一权限下的管理员
    static getSumUsersByisSuper(isSuper) {
        return new Promise((resolve, reject) => {
            let sql = 'select count(id) as sumUsers from user where isSuper = ?';
            this.query(sql, isSuper).then(result => {
                if(result[0]){
                    resolve(result[0].sumUsers);
                }
                else{
                    resolve(0); //  没有查到就返回0个  
                }
            }).catch(err => {
                console.log(`同一级别用户查询失败：${err.message}`)
                reject(err);
            })
        })
    }

    // 查询 所有0级权限的管理员
    static getUsers_isSuper_0(start, size=10) {
        return new Promise((resolve, reject) => {
            let sql = 'select id as user_id, username as user_name, isSuper from user where isSuper = 0 order by user_id desc limit ?, ?';
            this.query(sql, [start, size]).then(results => {
                resolve(results);
            }).catch(err => {
                console.log(`0级用户查询失败：${err.message}`);
                reject(err);
            })
        })
    }

    // 查询 user_name和 明文user_password是否匹配规则
    static checkUser_match(user_name, user_password) {
        return new Promise((resolve, reject) => {
            let regExp = /^[a-zA-Z_][a-zA-Z0-9_]{5,15}/;
            let result = undefined;
            if(user_name && !user_password){
                result = regExp.test(user_name);
                console.log(1)
            }
            else if(!user_name && user_password){
                result = regExp.test(user_password);
                console.log(2)
            }
            else if(user_name && user_password){
                result = regExp.test(user_name)
                result = result && regExp.test(user_password);
            }
            resolve(result);
        })
    }

    // 查询 user_name是否已存在
    static checkUsername_exist(user_name) {
        return new Promise((resolve, reject) => {
            let sql = 'select username from user where username = ?';
            this.query(sql, user_name).then(result => {
                if(result.lenght > 0 || result[0]){
                    resolve(true)
                }
                else{
                    resolve(false);
                }
            }).catch(err => {
                console.log(`用户名查询失败：${err.message}`)
                reject(err);
            })
        })

    }

    // 新增 用户名user_name, 权限isSuper的管理员
    static addUser(user_name, user_password, isSuper) {
        return new Promise((resolve, reject) => {
            let sql = 'insert into user set username = ?, password = ?, isSuper = ?'
            this.query(sql, [user_name, user_password, isSuper]).then(result => {
                resolve(result.insertId);
            }).catch(err => {
                console.log(`新增用户失败：${err.message}`)
                reject(err);
            })
        })
    }

    // 删除 user_id的管理员
    static deleteUser(user_id) {
        return new Promise((resolve, reject) => {
            let sql = 'delete from user where id = ?';
            this.query(sql, user_id).then(result => {
                resolve(result.affectedRows);
            }).catch(err => {
                console.log(`删除用户失败：${err.message}`)
                reject(err);
            })
        })
    }

    // 初始化 user_id的管理员密码
    static initPassword(user_id, initPassword) {
        return new Promise((resolve, reject) => {
            let sql = 'update user set password = ? where id = ?'
            this.query(sql, [initPassword, user_id]).then(result => {
                resolve(result.affectedRows);
            }).catch(err => {
                console.log(`初始化用户密码失败：${err.message}`)
                reject(err);
            })
        })
    }

    // 修改 user_id的管理员用户名和密码
    static updateUser(user_id, user_name, user_password){
        return new Promise((resolve, reject) => {
            let sql = 'update `user` set username = ?, `password` = ? where id = ?';
            this.query(sql, [user_name, user_password, user_id]).then(result => {
                resolve(result.affectedRows);
            }).catch(err => {
                console.log(`修改用户名密码失败：${err.message}`)
                reject(err);
            })
        })
    }
}