/**
 * Created by zhang on 2018/7/14.
 */

import mongoose from "mongoose";
const uuidV1 = require('uuid/v1');
let moment = require("moment");
let compilationModel = mongoose.model("compilation");
let mainColLibModel = mongoose.model("std_main_col_lib");

let mainCol={
    addLib:addLib,
    getAllLibs:getAllLibs,
    deleteLibByID:deleteLibByID,
    getLibByID:getLibByID,
    saveLib:saveLib,
    getColLibsByCompilationID:getColLibsByCompilationID
};

async function saveLib(param) {
    if(param.data.main_tree_col){
        param.data.main_tree_col = JSON.parse(param.data.main_tree_col);
    }
    return await mainColLibModel.findOneAndUpdate(param.query,param.data,{new:true});
}

async function getLibByID(ID) {
    return await mainColLibModel.findOne({ID:ID});
}
async function getColLibsByCompilationID(compilationID) {
    return await mainColLibModel.find({compilationId:compilationID},['ID','name']);
}


async function deleteLibByID(ID){
    return mainColLibModel.deleteOne({ID:ID});
}

async function getAllLibs() {
    return await mainColLibModel.find();
}

async function addLib(data){
    let now = new Date().getTime();
    let dateStr = moment(now).format('YYYY-MM-DD HH:mm:ss');
    //取编办信息
    let compilation = await compilationModel.findOne({_id:data.compilationId});
    if(compilation){
        let newLib = {
            creator: data.userAccount,
            createDate: now,
            recentOpr: [{operator: data.userAccount, operateDate: dateStr}],
            name: data.name,
            compilationId: data.compilationId,
            compilationName: compilation.name,
            deleted: false
        };
        newLib.ID = uuidV1();
        return await mainColLibModel.create(newLib);
    }else {
        throw  new Error("没有找到该编办！");
    }
}



export default  mainCol