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

const dynamicsSchema = new Schema({
    id:String,
    uscc:{type:String, index:true},//
    enterpriseName:String,//企业名称
    fuHuaQiUscc:String,
    changeType:Number,  //ENTERPRISECHANGETYPE
    content:String,
    oldContent:String,//变更前信息
    createTime:Number,
    isRead:{type:Boolean, default:false}
});



var dynamicsModel;
export function initModel(){
    dynamicsModel = baseDB.model('dynamics', dynamicsSchema);
    dynamicsModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await dynamicsModel.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 findOne(param) {
    return await dynamicsModel.selectOnceData(param);
}

export async function findByParam(param) {
    return await dynamicsModel.find(param);
}

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

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

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