/**
 * Created by Zhang on 2018/7/13.
 * 清单模板，新建项目使用
 */
import mongoose from "mongoose";
const uuidV1 = require('uuid/v1');
let moment = require("moment");
let compilationModel = mongoose.model("compilation");
let billTemplateLibModel = mongoose.model("std_bills_template_lib");
let billTemplateItemsModel = mongoose.model("std_bills_template_items");

let billTemplate={
    addLib:addLib,
    copyLib: copyLib,
    getAllLibs:getAllLibs,
    getLibByID:getLibByID,
    saveLib:saveLib,
    deleteLibByID:deleteLibByID,
    getTemplateDatasByLibID:getTemplateDatasByLibID,
    updateTemplateItem:updateTemplateItem,
    getTemplateLibByCompilationID:getTemplateLibByCompilationID
};

async function getTemplateLibByCompilationID(compilationID) {
    return await billTemplateLibModel.find({compilationId:compilationID},['ID','name']);
}

async function updateTemplateItem (libID, datas) {
        for (let data of datas) {
            data.data.libID  = libID;
            let condition = {libID: libID, ID: data.data.ID}, result;
            if (data.type === 'update') {
                result = await billTemplateItemsModel.update(condition, data.data);
                if (result === undefined || result.ok ===undefined || !result.ok) {
                    throw '更新数据错误';
                }
            } else if (data.type === 'new') {
                result = await billTemplateItemsModel.create(data.data);
                if (!result) {
                    throw '新增数据错误';
                }
            } else if (data.type === 'delete') {
                result = await billTemplateItemsModel.deleteOne(condition);
                result = result.result;
                if (result === undefined || result.ok ===undefined || !result.ok) {
                    throw '删除数据错误';
                }
            }
        }
        return true;
}

async function getTemplateDatasByLibID(libID) {
    return await billTemplateItemsModel.find({libID:libID});
}
async function deleteLibByID(ID){
    //删除模板详情：
    await billTemplateItemsModel.deleteMany({libID:ID});
    return billTemplateLibModel.deleteOne({ID:ID});
}

async function getLibByID(ID) {
    return await billTemplateLibModel.findOne({ID:ID});
}

async function getAllLibs(filter = null) {
    if (filter) {
        return await billTemplateLibModel.find(filter);
    }
    return await billTemplateLibModel.find();
}

async function saveLib(param) {
    return await billTemplateLibModel.findOneAndUpdate(param.query,param.data,{new:true});
}

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 billTemplateLibModel.create(newLib);
    }else {
        throw  new Error("没有找到该编办！");
    }
}

async function copyLib(libID, name, userName) {
    const lib = await billTemplateLibModel.findOne({ID: libID}, '-_id').lean();
    const libItems = await billTemplateItemsModel.find({libID}, '-_id').lean();
    lib.creator = userName;
    lib.createDate = Date.now();
    lib.recentOpr = [{operator: userName, operator: moment(lib.createDate).format('YYYY-MM-D HH:mm:ss')}];
    lib.name = name;
    lib.ID = uuidV1();
    await billTemplateLibModel.create(lib);
    libItems.forEach(item => {
        item.libID = lib.ID;
    });
    if (libItems.length) {
        await billTemplateItemsModel.insertMany(libItems);
    }
}

export default  billTemplate