'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2019/1/25
 * @version
 */

import mongoose from "mongoose";
const uuidV1 = require('uuid/v1');
let moment = require("moment");
const vvTaxLibModel = mongoose.model('std_vehicleVesselTax_lib');
const vvTaxModel = mongoose.model('std_vehicleVesselTax_items');


let vvTaxLib = {
    findByCondition:async function(conditions,withData=false,single=true){
        if(single == true){
            let lib = await vvTaxLibModel.findOne(conditions);
            if (withData) {
                lib._doc.data = await vvTaxModel.find({libID: conditions.ID}, {_id: 0, libID:0, ID: 0});
            }
            return lib._doc;
        }else {
            return await  vvTaxLibModel.find(conditions);
        }
    },
    addLib : async function (data){
        let now = new Date().getTime();
        let dateStr = moment(now).format('YYYY-MM-DD HH:mm:ss');
        let newLib = {
            creator: data.userAccount,
            createDate: now,
            recentOpr: [{operator: data.userAccount, operateDate: dateStr}],
            name: data.name,
        };
        newLib.ID = uuidV1();
        return await vvTaxLibModel.create(newLib);
    },
    saveLib:async function(param) {
        if (param.edit) {//更改保存车船税具体数据
            await vvTaxModel.deleteMany({libID: param.query.ID});
            let tasks = [];
            for (let data of param.data.data) {
                data.libID = param.query.ID;
                data.ID = uuidV1();
                tasks.push({insertOne: {document: data}});
            }
            if (tasks.length > 0) {
                await vvTaxModel.bulkWrite(tasks);
            }
        } else {
            return await vvTaxLibModel.findOneAndUpdate(param.query,param.data,{new:true});
        }
    },
    deleteLibByID:async function(ID){
        await vvTaxLibModel.deleteOne({ID: ID});
        return await vvTaxModel.deleteMany({libID: ID});
    },
};

export default vvTaxLib;