/**
 * 标签系统
 */


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


const labelSchema = new Schema({
    id:{type:String, index:true},//标识
    labelName:String,
    ctMs:Number,//创建时间
    goal:Number,//目标 LABELGOAL  
    labelType:Number,//标签类型 LABELTYPE 系统标签不可以删除
    state:{type:Boolean, default:false}//是否停用 true表示已停用
});


var labelModel;
export function initModel(){
    labelModel = sasp.model('label', labelSchema);
    labelModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await labelModel.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 createLabel(goal:number, labelType:number, name:string, id:string) {
    let addInfo = { id, goal, labelType, labelName:name, ctMs:new Date().valueOf(), state:false, isDelete:false };
    return await labelModel.create(addInfo);
}

export async function createOneLabel(param) {
    return await labelModel.create(param);
}


export async function findOnceLabel(id:string) {
    return await labelModel.selectOnceData({id});
}

export async function selectLabelList(param) {
    return await labelModel.find(param);
}

export async function selectLabelOne(param) {
    return await labelModel.selectOnceData(param);
}

export async function selectLabelListToPage(param, skipNumber) {
    return await labelModel.find(param).skip(skipNumber).limit(10);
}

export async function selectLabelCount(param) {
    return await labelModel.find(param).countDocuments();
}

export async function addSystemLabel(labels) {
    await labelModel.insertMany(labels);
}

export async function delLabel(id) {
    return await labelModel.deleteOne({id});
}


/**
 * 获取标签名称与标签类型map
 * @param goal 标签目标
 * @returns 
 */
export async function getEffectiveLabelMap(goal:number) {
    let list = await labelModel.find({goal, state:false});
    let map = {};
    list.forEach( info => {
        let {id, labelName, labelType} = info;
        map[id] = {labelName, labelType};
    });
    return map;
}


/**
 * 获取标签名称与状态map
 * @param goal 标签目标
 * @returns 
 */
export async function getLabelNamMap(goal:number) {
    let list = await labelModel.find({goal});
    let nameMap = {};
    list.forEach(info => {
        let {id, labelName, state} = info;
        nameMap[id] = {labelName, state};
    });

    return nameMap;
}