/**
 * 活动
 */


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


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


var activityModel;
export function initModel(){
    activityModel = baseDB.model('activity', activitySchema);
    activityModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await activityModel.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 uscc 孵化器统一信用代码
 * @returns 
 */
export async function findOne(param) {
    return await activityModel.selectOnceData(param);
}

/**通过条件查询孵化器得分信息 */
export async function findByParam(param) {
    return await activityModel.find(param);
}

export async function findCountByParam(param) {
    return await activityModel.find(param).countDocuments();
}

export async function createDataByParam(param) {
    return await activityModel.create(param);
}


export async function removeOneData(id:string) {
    return await activityModel.deleteOne({id});
}


/**
 * 创建资讯
 * @param id 
 * @param desc 
 * @param title 
 * @param source 
 * @param imgs 
 */
export async function createActivity(id:string, desc:string, title, source, coverImg, startTime, endTime, target) {
    let addInfo = {id, desc, title, source, coverImg, startTime, endTime, target, createTimeMs:new Date().valueOf() };
    await activityModel.create(addInfo);
}


export async function selectActivityDataById(id:string) {
    return await activityModel.selectOnceData({id});
}


export async function deleteActivityData(id:string) {
    return await activityModel.deleteOne({id});
}

export async function selectActivityByParam(param) {
    return await activityModel.find(param);
}

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

export async function selectActivityyParamCount(param) {
    return await activityModel.find(param).countDocuments();;
}

export async function selectOnceActivityByParamToParam(param) {
    return await activityModel.findOne(param);
}