/**
 * 资讯  包括企业和孵化器
 * 
 */

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

const informationSchema = new Schema({
    id:{type:String, index:true},//唯一标识
    title:String,//标题
    desc:String,//内容
    source:String,//来源
    createTimeMs:Number,//创建时间
    coverImg:{type:String, default:""},
    target:{type:[Number], default:[]},//标签
    closeTimeMs:Number,//关闭时间
    isPermanent:{type:Boolean, default:false},//是否永久有效
    state:{type:Boolean, default:false},//非自动状态  true=关闭，false=开启
});

var informationModel;
export function initModel(){
    informationModel = baseDB.model('information', informationSchema);
    informationModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await informationModel.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 id 
 * @param desc 
 * @param title 
 * @param source 
 * @param imgs 
 */
export async function createInformation(id:string, desc:string, title:string ,source:string, coverImg:string ) {
    let addInfo = {id, desc, title, source, coverImg, createTimeMs:new Date().valueOf() };
    await informationModel.create(addInfo);
}


export async function selectInformationDataById(id:string) {
    return await informationModel.selectOnceData({id});
}


export async function deleteInformationData(id:string) {
    return await informationModel.deleteOne({id});
}

export async function selectInformationByParam(param) {
    return await informationModel.find(param);
}

export async function selectInformationByParamToPage(param, skipNumber:number) {
    return await informationModel.find(param).sort({createTimeMs:-1}).skip(skipNumber).limit(10);
}

export async function selectInformationByParamCount(param) {
    return await informationModel.find(param).countDocuments();;
}

export async function selectOnceInformationByParamToParam(param) {
    return await informationModel.findOne(param);
}