/**
 * Created by zhang on 2018/9/3.
 */
import mongoose from "mongoose";
const uuidV1 = require('uuid/v1');
let moment = require("moment");
let billCodeLibModel = mongoose.model('std_bill_code_lib');
let billCodeItemModel = mongoose.model('std_bill_code_item');
let compilationModel = mongoose.model('compilation');


let billCodeLib = {
    findByCondition:async function(conditions,options,single=true){
        if(single == true){
            return await billCodeLibModel.findOne(conditions,options);
        }else {
            return await billCodeLibModel.find(conditions,options);
        }
    },
    findItemsByCondition:async function(conditions,options){
        return await  billCodeItemModel.find(conditions,options).lean();
    },
    addLib : async function (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,
            };
            newLib.ID = uuidV1();
            return await billCodeLibModel.create(newLib);
        }else {
            throw  new Error("没有找到该编办！");
        }
    },
    saveLib:async function(param) {
        await billCodeItemModel.deleteMany({libID:param.query.ID});
        const items = param.data.data.map((item) => {
            item.libID = param.query.ID;
            item.ID = uuidV1();
            return item;
        });
        return await billCodeItemModel.insertMany(items);
    },
    deleteLibByID:async function(ID){
        await billCodeItemModel.deleteMany({libID:ID});
        return await billCodeLibModel.deleteOne({ID:ID});
    },
};

export default billCodeLib