/**
 * 管理后台用户
 */

import {Schema} from 'mongoose';
import {sasp} from '../db/mongo/dbInit';

const adminuserSchema = new Schema({
    loginId:{type:String, index:true},//登录账号
    name:{type:String, index:true}, //名称
    pwd:String, //密码
    token:String,
    tokenMs:Number,
})


var adminuserModel;
export function initModel(){
    adminuserModel = sasp.model('adminuser', adminuserSchema);
    adminuserModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await adminuserModel.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);
    });
}


/**
 * 获取符合条件的管理后台用户
 * @param selectParam 
 */
export async function findAdminuserByLoginId(loginId:string) {
    return await adminuserModel.findOne({loginId}).exec();
}


/**
 * 分页获取所有管理后台用户
 * @param selectParam 查询参数
 * @param skipCount 跳过数量
 * @returns [] 管理后台用户列表
 */
export async function findAdminuserListToPage(selectParam, skipCount) {
    return await adminuserModel.find(selectParam).skip(skipCount).limit(10);
}


/**
 * 获取符合条件的管理后台用户数量
 * @param selectParam 查询参数
 * @returns number 数据数量
 */
export async function findAdminuserCount(selectParam) {
    return await adminuserModel.find(selectParam).countDocuments();
}


/**
 * 获取符合条件的管理后台用户
 * @param selectParam 
 */
export async function findAdminuserByParam(selectParam) {
    return await adminuserModel.selectOnceData(selectParam);
}


/**
 * 新增管理后台用户
 * @param param 
 * @returns 
 */
export async function createAdminuserByParam(param) {
    return await adminuserModel.create(param);
}


/**
 * 删除管理后台用户
 * @param id 
 * @returns 
 */
export async function removeOneData(id:string) {
    return await adminuserModel.deleteOne({id});
}




 

