/**
 * 用户表
 */
import { Schema } from 'mongoose';
import { baseDB } from '../db/dbInit';

const userSchema = new Schema({
    name:String,//名称
    loginId: {type:String, index:true},//登录账号
    userId:{type:String, index:true},
    pwd:String,//密码
    phone:{type:String, index:true},//登录手机号
    token:String,
    tokenMs:Number,
    position:String,//职务
    adminToken:String,
    adminTokenMs:Number,
});

var userModel;
export function initModel(){
    userModel = baseDB.model('user', userSchema);
    userModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await userModel.findOne(paramater).exec();
        if (selectInfo) {
            if (!selectInfo.runSave) {
                selectInfo.runSave = selectInfo.save;
                selectInfo.save = save.bind(selectInfo)
            }
        }
        return selectInfo;
    }
}
export async function save(throwError=false) {
    if (!this.isModified()) return;
    await this.runSave({validateBeforeSave:false}).catch(err=>{
        console.log(err);
    });
}

export async function findUserInfoByLoginId(loginId:string) {
    return await userModel.selectOnceData({loginId});
}

export async function findUserInfoByUserId(userId:string) {
    return await userModel.selectOnceData({userId});
}

export async function findUserMap() {
    let map = {};
    let userList = await userModel.find({});
    userList.forEach(info => {
        map[info.userId] = info.name;
    });
    return map;
}


export async function createUser(addInfo) {
    await userModel.create(addInfo);
}

export async function createManyUser(userList) {
    await userModel.insertMany(userList);
}