/**
 * Created by zhang on 2018/4/17.
 */
const projectType = {
    folder: 'Folder',
    tender: 'Tender',
    project: 'Project',
    engineering: 'Engineering',
};
//先导出后require可以解决循环引用问题
module.exports={
    moveProject:moveProject,
    copyProject:copyProject,
    copyExample: copyExample,
    getSummaryInfo: getSummaryInfo,
    getSummaryInfoByTender: getSummaryInfoByTender,
    getTendersFeeInfo: getTendersFeeInfo,
    getConstructionProject: getConstructionProject,
    getFullPath: getFullPath,
    getProjectFeature:getProjectFeature,
    projectType: projectType,
    getPosterityProjects: getPosterityProjects,
    isShare: isShare,
    isFirst: isFirst,
    getShareInfo: getShareInfo,
    prepareInitialData: prepareInitialData,
    changeFile:changeFile,
};



let mongoose = require('mongoose');
let _ = require("lodash");
let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
let glj_facade = require('../../glj/facade/glj_facade');
let project_facade = require('../../main/facade/project_facade');
let logger = require("../../../logs/log_helper").logger;
const uuidV1 = require('uuid/v1');
let projectModel = mongoose.model('projects');
let projectSettingModel =  mongoose.model('proj_setting');
let billsModel = mongoose.model('bills');
let rationModel = mongoose.model('ration');
let gljListModel = mongoose.model("glj_list");
let calcProgramsModel = mongoose.model('calc_programs');
let labourCoesModel = mongoose.model('labour_coes');
let feeRateModel = mongoose.model('fee_rates');
let feeRateFileModel = mongoose.model('fee_rate_file');
let unitPriceFileModel = mongoose.model("unit_price_file");
let mixRatioModel = mongoose.model("mix_ratio");
let unitPriceModel = mongoose.model("unit_price");
let installationFeeModel = mongoose.model("installation_fee");
let rationGLJModel = mongoose.model('ration_glj');
let rationCoeModel = mongoose.model('ration_coe');
let rationInstallationModel = mongoose.model('ration_installation');
let quantityDetailModel = mongoose.model('quantity_detail');
let rationTemplateModel = mongoose.model('ration_template');
let userModel = mongoose.model('user');
let compleGljSectionModel = mongoose.model('complementary_glj_section');
let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');

let featureLibModel =  mongoose.model("std_project_feature_lib");
let scMathUtil = require('../../../public/scMathUtil').getUtil();
let counter = require('../../../public/counter/counter');
import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
let sectionTreeDao = new SectionTreeDao();
import CounterModel from "../../glj/models/counter_model";
import moment from 'moment';
import billsFlags from '../../common/const/bills_fixed';
const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];



//拷贝例题项目
//@param {String}userID {Array}projIDs拷贝的例题项目ID（建设项目、文件夹）@return {Boolean}
async function copyExample(userID, compilation, projIDs){
    let allProjs = [],
        IDMapping = {},
        projMapping = {};
    //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹，否则不自动新建例题项目（这里不报错，让用户没有感觉）
    let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted});
    if (parentExample.length === 0) {
        return false;
    }
    allProjs = allProjs.concat(parentExample);
    for (let i = 0; i < parentExample.length; i++) {
        let data = parentExample[i];
        if (data.projType === projectType.tender || data.projType === projectType.engineering) {
            return false;
        }
        //设置成顶节点，最后一个节点设置成末节
        data.ParentID = -1;
        if (i === parentExample.length - 1) {
            data.NextSiblingID = -1;
        }
    }
    //获取所有的子项目
    let posterityProjs = await getPosterityProjects(projIDs);
    allProjs = allProjs.concat(posterityProjs);
    let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
    //旧ID与新ID映射
    for (let i = 0; i < allProjs.length; i++) {
        let data = allProjs[i];
        let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
        IDMapping[data.ID] = newID;
        projMapping[newID] = data;
    }
    //return;
    //设置新的树结构数据
    let newDate = new Date(),
        parentBulks = [];
    for (let data of allProjs) {
        let orgID = data.ID;
        data.ID = IDMapping[data.ID];
        data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
        data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
        data.createDateTime = newDate;
        data.userID = userID;
        data.compilation = compilation;
        data.shareInfo = [];
        if (data.projType !== projectType.tender) {
            let newData = _.cloneDeep(data._doc);
            delete newData._id;
          //  await projectModel.create(newData);
            parentBulks.push({insertOne: {document: newData}});
        } else {
            //拷贝单位工程
            let rootProjectID = projMapping[data.ParentID].ParentID;
            let projectMap = {
                copy: {
                    document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
                                compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
                }
            };
            await copyProject(userID, compilation, {projectMap}, data.ID);
        }
    }
    //最末顶层项目（兼容测试时已存在有项目，正常用户第一次进费用定额，该费用定额不存在项目）
    let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
    if (lastProj) {
        parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
    }
    //拷贝父级文件
    await projectModel.bulkWrite(parentBulks);
    return true;
}

async function copyProject(userID, compilationID,data,newProjectID = null) {
    let projectMap = data.projectMap;
    let originalID = projectMap['copy'].document.ID;
    if (!newProjectID) {
        newProjectID = await getCounterID("projects");
    }
    let newFeeName = null,newUnitName = null;
    let calcProgramFileID = uuidV1();//新的计算程序文件ID
    let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
    let feeRateFileID = uuidV1();//新的费率文件ID
    let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
    let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息，前端缓存的数据有可能不是最新的
    if(!originalProject){
        throw new Error('没有找到对应的项目，复制失败!');
    }
    let property = originalProject.property;
    if(projectMap['copy'].document.property){//更新项目属性信息
        setProperty(property,projectMap['copy'].document.property);
    }
    let originalProperty = _.cloneDeep(property);
    projectMap['copy'].document.property = property;
    logger.info("复制项目： 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
    //费率文件、单价文件重名检查
    let feeRate =  await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
    if(feeRate){//存在重名的文件
        newFeeName = originalProperty.feeFile.name + '（' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制）';
        projectMap['copy'].document.property.feeFile.name = newFeeName;
    }

    let unitPriceFile =  await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
    if(unitPriceFile){//存在重名的文件
        newUnitName = originalProperty.unitPriceFile.name + '（' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制）';
        projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
    }

    //更新项目的属性;
    projectMap['copy'].document.ID = newProjectID;
    if(projectMap['copy'].document.property.calcProgramFile){
        projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
    }
    if(projectMap['copy'].document.property.labourCoeFile){
        projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
    }
    if(projectMap['copy'].document.property.feeFile){
        projectMap['copy'].document.property.feeFile.id = feeRateFileID;
    }
    if(projectMap['copy'].document.property.unitPriceFile){
        projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
    }
    projectMap['copy'].document.userID = userID;
    projectMap['copy'].document.compilation = compilationID;
    projectMap['copy'].document.createDateTime = new Date();
    //清单、定额ID生成任务
    let IDtasks = [
        createIDsAndReturn(originalID,billsModel),
        createIDsAndReturn(originalID,rationModel),
        getProjectGLJIDAndReturn(originalID,newProjectID)
    ];
    let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
    //所有复制任务异步处理，提升效率  复制清单，定额，4个文件，项目工料机， 定额工料机，人工系数，工程量明细，定额安装增加费，安装增加费
    let copyTasks = [
        createProject(projectMap),
        copyProjectSetting(originalID,newProjectID),
        copyBills(newProjectID,billMap),
        copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
        copyProjectGLJ(projectGLJMap.datas),
        copyInstallFee(originalID,newProjectID),
        copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
        copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
        copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
        copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
        copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel)
    ];
    if(originalProperty.calcProgramFile){
        copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
    }
    if(originalProperty.labourCoeFile){
        copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
    }
    if(originalProperty.feeFile){
        copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
    }
    if(originalProperty.unitPriceFile){
        copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
    }
    let p = await Promise.all(copyTasks);
    return p[0];
}

async function createIDsAndReturn(originalID,model) {
    let uuidMaping = {};//做ID映射
    let datas = [];
    let result = await model.find({"projectID": originalID}, '-_id');
    uuidMaping['-1'] = -1;
    //建立uuid-ID映射
    for(let d of result){
        uuidMaping[d.ID] = uuidV1();
        datas.push(d._doc);
    }
    return{uuidMaping:uuidMaping,datas:datas};
}

async function getProjectGLJIDAndReturn(originalID,newProjectID) {
    let IDMap = {};
    let datas = [];
    let result = await gljListModel.find({project_id:originalID}, '-_id');
    let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
    for(let i = 0; i < result.length; i++){
        let d = result[i];
        let newID = gljCount.sequence_value - (result.length - 1) + i;
        //let newID = await getCounterID("glj_list");
        IDMap[d.id] = newID;
        d._doc.project_id = newProjectID;
        d._doc.id = newID;
        datas.push(d._doc);
    }
    return{IDMap:IDMap,datas:datas};
}

async function createProject(projectMap) {//复制项目
    let tasks = [];
    if(projectMap['update']){//如果复制后存在前一个节点，则更新其NextSiblingID
        tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
    }
    tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
    await projectModel.bulkWrite(tasks);
    return projectMap;
}

async function copyProjectSetting(originalID,newProjectID) {
    let result = null;
    let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
    if(setting){
        setting._doc.projectID =newProjectID;
        result = await projectSettingModel.create(setting._doc);
    }
    return result;
}

async function copyBills(newProjectID,billMap) {
     let uuidMaping = billMap.uuidMaping;//做ID映射
    for(let doc of billMap.datas){
         doc.projectID = newProjectID;
         doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
         doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
         doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
    }
    await insertMany(billMap.datas,billsModel);
    return billMap.datas;
}

async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
    let uuidMaping = rationMap.uuidMaping;
    for(let doc of rationMap.datas){
        doc.projectID = newProjectID;
        doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
        if(doc.billsItemID){
            doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
        }
        if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
        //绑定定类型的工料机 项目工料机ID
        doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
    }
    if(rationMap.datas.length > 0){
        await insertMany(rationMap.datas,rationModel);
    }
    return rationMap.datas;
}

async function copyProjectGLJ(gljList) {
    await insertMany(gljList,gljListModel);
}

async  function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
    let result = null;
    let file = await model.findOne({"ID": oldID}, '-_id');
    if(file){
        file._doc.ID = newID;
        file._doc.projectID =newProjectID;
        result = await model.create(file._doc);
    }
    return result;
}

async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
    let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
    let newFeeRateID = uuidV1();
    if(feeRate){
        feeRate._doc.ID = newFeeRateID;
        await feeRateModel.create(feeRate._doc);
    }
    if(feeRateFile){
        feeRateFile._doc.ID = feeRateFileID;
        newName?feeRateFile._doc.name = newName:'';
        feeRateFile._doc.userID = userID;
        feeRateFile._doc.rootProjectID = rootProjectID;
        feeRateFile._doc.feeRateID = newFeeRateID;
        await feeRateFileModel.create(feeRateFile._doc);
    }
}

async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物

    let taskList = [
        copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
        copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
        copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
    ];

    return await Promise.all(taskList);

    async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
        let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
        if(unitPriceFile){
            unitPriceFile._doc.id = unitPriceFileID;
            newName?unitPriceFile._doc.name = newName:'';
            unitPriceFile._doc.project_id = newProjectID;
            unitPriceFile._doc.user_id = userID;
            unitPriceFile._doc.root_project_id = rootProjectID
        }
        await unitPriceFileModel.create(unitPriceFile._doc);
    }

    async function copySubList(srcFID,newFID,model) {
        let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
        let rList = [];
        for(let m of mList){
            m._doc.unit_price_file_id = newFID;
            m._doc.id = await getCounterID(model.modelName);
            rList.push(m._doc);
        }
        await insertMany(rList,model)
    }
}

async function copyInstallFee(originalPID,newProjectID) {
    let result = null;
    let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
    let newList = [];
    for(let i of installationFee ){
        i._doc.ID = uuidV1();
        i._doc.projectID = newProjectID;
        newList.push(i._doc);
    }
    if(newList.length >0){
        result =  await installationFeeModel.insertMany(newList);
    }
    return result;
}

async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机，附注条件，工程量明细，定额安装增加费,模板子目
    let subList = await model.find({projectID:originalPID}, '-_id');
    let newList =[];
    for(let s of subList){
        s._doc.ID = uuidV1();
        s._doc.projectID = newProjectID;
        s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
        s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
        s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
        s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
        if(s._doc.templateList && s._doc.templateList.length > 0 ){
            for(let t of s._doc.templateList){
                if(t.billID && billIDMap[t.billID]) t.billID =  billIDMap[t.billID];
                if(t.fxID && billIDMap[t.fxID]) t.fxID =  billIDMap[t.fxID];
            }
        }
        newList.push(s._doc);

    }
    await insertMany(newList,model);
}

async function moveProject(data) {
    data = JSON.parse(data);
    let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
    let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
    let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时，任务有可能出现重复的情况
    if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
        let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件，重名检查
        for(let projectID in feeRateMap){
            let rename = feeRateMap[projectID].name;
            let feeRateID =  feeRateMap[projectID].query.ID;
            let checkFee = _.find(feeRates,{'name':rename});
            let newID = feeRateID;
            if(checkFee){//说明费率名字已存在，需要重命名
                rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '（' + new Date().Format('MM-dd hh:mm:ss') + '移动）';
                projectMap[projectID]['update']['property.feeFile.name'] = rename;
                if(feeRateMap[projectID].action == 'move'){
                    feeRateMap[projectID].update.name = rename;
                }
            }
            if(feeRateMap[projectID].action == 'copy'){
                newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
                feeRateMap[projectID].name = rename;
                feeRateMap[projectID].ID =  newID;
                projectMap[projectID]['update']['property.feeFile.id'] = newID;
            }
            if(!feeUniqMap[feeRateID]){
                await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
                feeUniqMap[feeRateID] = {name:rename,ID:newID};
            }
        }
    }
    if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
        let unitPriceFiles =  await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
        for(let projectID in unitPriceMap){
            let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
            let rename = unitPriceMap[projectID].name;
            let unitPriceID = unitPriceMap[projectID].query.id;
            let newID = unitPriceID;
            if(checkUn){//重名检查
                rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '（' + new Date().Format('MM-dd hh:mm:ss') + '移动）';
                projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
                if(unitPriceMap[projectID].action =='move'){
                    unitPriceMap[projectID].update.name = rename;
                }
            }
            if(unitPriceMap[projectID].action =='copy'){
                newID =  priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
                unitPriceMap[projectID].name = rename;
                unitPriceMap[projectID].id = newID;
                projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
            }
            if(!priceUniqMap[unitPriceID]){
                await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
                priceUniqMap[unitPriceID] = {name:rename,id:newID};
            }
        }
    }

    if(!_.isEmpty(projectMap)){
        for(let projectID in projectMap){
            projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
        }
    }

    projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
    feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
    feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
    unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
    unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
    mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
    return projectMap;
}

async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
    if(data.action == 'move'){
        let task = {
            updateOne:{
                filter : data.query,
                update : data.update
            }
        };
        feeRateFileTask.push(task);
    }
    if(data.action == 'copy'){//copy 费率的时候用insertOne方法
        let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
        let newFeeRateID =  uuidV1();
        let newFeeRate = {
            ID:newFeeRateID,
            rates:feeRate.rates
        };
        let newFeeRateFile = {
            ID:data.ID,
            rootProjectID:data.rootProjectID,
            userID:feeRateFile.userID,
            name:data.name,
            libID:feeRateFile.libID,
            libName:feeRateFile.libName,
            feeRateID:newFeeRateID
        };
        feeRateTask.push({insertOne :{document:newFeeRate}});
        feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
    }
}

async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
    if(data.action == 'move'){
        let task = {
            updateOne:{
                filter : data.query,
                update : data.update
            }
        };
        unitPriceFileTask.push(task);
    }
    if(data.action == 'copy'){
        let newUnitFile = {
            id:data.id,
            name: data.name,
            project_id:projectID,
            user_id:user_id,
            root_project_id: data.rootProjectID
        };
        unitPriceFileTask.push({insertOne :{document:newUnitFile}});
        let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
        mixRatios = JSON.stringify(mixRatios);
        mixRatios = JSON.parse(mixRatios);
        for(let m of mixRatios){
            delete m._id;  // 删除原有id信息
            delete m.id;
            m.unit_price_file_id = data.id;
            m.id = await getCounterID('mix_ratio');
            mixRatioTask.push(m);
        }
        let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
        unitPrices = JSON.stringify(unitPrices);
        unitPrices = JSON.parse(unitPrices);
        for(let u of unitPrices){
            delete u._id;  // 删除原有id信息
            delete u.id;
            u.unit_price_file_id = data.id;
            u.id = await getCounterID('unit_price');
            unitPriceTask.push(u);
        }
    }
}


async function getCounterID(collectionName){
    let counterModel = new CounterModel();
    return  await counterModel.getId(collectionName);
}

async function insertMany(datas,model) {
    while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
        let newList = datas.splice(0,1000);//一次插入1000条
        await model.insertMany(newList);
    }
    await model.insertMany(datas);

}

function setProperty(Obj,updateData) {
    for(let ukey in updateData){
        if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
            setProperty(Obj[ukey],updateData[ukey]);
        }else {
            Obj[ukey] = updateData[ukey];
        }
    }


}

function isDef(v){
    return typeof v !== 'undefined' && v !== null;
}

function getTotalFee(bills, feeName) {
    if(!isDef(bills)){
        return 0;
    }
    if(!isDef(bills.fees) || bills.fees.length <= 0){
        return 0;
    }
    for(let fee of bills.fees){
        if(isDef(fee.fieldName) && fee.fieldName === feeName){
            return isDef(fee.totalFee) ? fee.totalFee : 0;
        }
    }
    return 0;
}

function summarizeToParent(parent, child) {
    const decimal = -2;
    let costFields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
    for (let field of costFields) {
        parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
    }
   /* const decimal = -2;
    parent.engineeringCost = scMathUtil.roundTo(parseFloat(parent.engineeringCost) + parseFloat(child.engineeringCost), decimal);
    parent.subEngineering = scMathUtil.roundTo(parseFloat(parent.subEngineering) + parseFloat(child.subEngineering), decimal);
    parent.measure = scMathUtil.roundTo(parseFloat(parent.measure) + parseFloat(child.measure), decimal);
    parent.safetyConstruction = scMathUtil.roundTo(parseFloat(parent.safetyConstruction) + parseFloat(child.safetyConstruction), decimal);
    parent.other = scMathUtil.roundTo(parseFloat(parent.other) + parseFloat(child.other), decimal);
    parent.charge = scMathUtil.roundTo(parseFloat(parent.charge) + parseFloat(child.charge), decimal);
    parent.tax = scMathUtil.roundTo(parseFloat(parent.tax) + parseFloat(child.tax), decimal);*/
}

function getBuildingArea(projFeature){
    if(!projFeature || projFeature.length === 0){
        return null;
    }
    for(let f of projFeature){
        if(f.key === 'buildingArea'){
            return f.value;
        }
    }
    return null;
}

//根据单位工程ID获取汇总信息
//@param {Number}tenderID {String}summaryType @return {Object}
async function getSummaryInfoByTender(tenderID, summaryType) {
    const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
    let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
    let parentName;
    let summaryList = [];
    if(!tender){
        return null;
    }
    let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
    if(!engineering){
        return null;
    }
    let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
    if(!project){
        return null;
    }
    let summaryInfo = await getSummaryInfo([project.ID]);
    if(summaryType === projectType.engineering){
        parentName = engineering.name ? engineering.name : '';
        let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted});
        for(let t of tenders){
            if(summaryInfo[t.ID]){
                summaryInfo[t.ID]['name'] = t.name ? t.name : '';
                summaryList.push(summaryInfo[t.ID]);
            }
        }
    }
    else {
        parentName = project.name ? project.name : '';
        let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted});
        for(let e of engs){
            if(summaryInfo[e.ID]){
                summaryInfo[e.ID]['name'] = e.name ? e.name : '';
                summaryList.push(summaryInfo[e.ID]);
            }
        }
    }
    return {parent: {name: parentName}, subList: summaryList};
}

//获取单位工程的各标段费用信息(不进行汇总)
async function getTendersFeeInfo(tenders) {
    let IDMapping = {};
    //固定清单类别与汇总金额字段映射
    let flagFieldMapping = {};
    flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
    flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
    flagFieldMapping[billsFlags.MEASURE] = 'measure';
    flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
    flagFieldMapping[billsFlags.OTHER] = 'other';
    flagFieldMapping[billsFlags.CHARGE] = 'charge';
    flagFieldMapping[billsFlags.TAX] = 'tax';
    let tenderIDs = [];
    if(tenders.length > 0){
        for(let tender of tenders){
            tenderIDs.push(tender.ID);
            IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
            IDMapping[tender.ID]['buildingArea'] = '';
        }
        //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
        let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
            billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
        //获取单位工程汇总金额需要用到的所有清单
        let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
            '-_id projectID fees flags');
        //进行单位工程级别的汇总
        for(let bills of allBills){
            let billsFlag = bills.flags[0]['flag'];
            let costField = flagFieldMapping[billsFlag];
            IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
            //暂估合价(工程造价暂估合价)
            if (billsFlag === billsFlags.ENGINEERINGCOST){
                IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
            }
        }
        //占造价比例、单方造价
        for(let tender of tenders){
            let tenderInfo = IDMapping[tender.ID];
            tenderInfo.rate = '';
            //单方造价
            tenderInfo.perCost = '';
        }
    }
    return IDMapping;
}

async function getSummaryInfo(projectIDs){
    //ID与汇总信息映射
    let IDMapping = {};
    //固定清单类别与汇总金额字段映射
    let flagFieldMapping = {};
    flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
    flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
    flagFieldMapping[billsFlags.MEASURE] = 'measure';
    flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
    flagFieldMapping[billsFlags.OTHER] = 'other';
    flagFieldMapping[billsFlags.CHARGE] = 'charge';
    flagFieldMapping[billsFlags.TAX] = 'tax';
    let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
    //设置建设项目的总建筑面积
    for(let project of projects){
        let grossArea = '';
        if(project.property && project.property.basicInformation){
            for(let basicInfo of project.property.basicInformation){
                if(basicInfo.key === 'basicInfo'){
                    for(let k of basicInfo.items){
                        if(k.key === 'grossArea'){
                            grossArea = k.value;
                        }
                    }
                }
            }
        }
        IDMapping[project.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
    }

    //单项工程
    let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
    //单位工程
    let tenders = [];
    let engIDs = [];
    for(let eng of engineerings){
        engIDs.push(eng.ID);
        IDMapping[eng.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
    }
    if(engIDs.length > 0){
        tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
    }
    let tenderIDs = [];
    if(tenders.length > 0){
        for(let tender of tenders){
            tenderIDs.push(tender.ID);
            IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, rate: 0, estimate: 0,
                buildingArea: '', perCost: '',changeMark:tender.changeMark,property:tender.property};
            let buildingArea = getBuildingArea(tender.property.projectFeature);
            if(buildingArea){
                IDMapping[tender.ID]['buildingArea'] = buildingArea;
            }
        }
        //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
        let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
            billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
        //获取单位工程汇总金额需要用到的所有清单
        let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
                                            '-_id projectID fees flags');
        //进行单位工程级别的汇总
        for(let bills of allBills){
            let billsFlag = bills.flags[0]['flag'];
            let costField = flagFieldMapping[billsFlag];
            IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
            //暂估合价(工程造价暂估合价)
            if (billsFlag === billsFlags.ENGINEERINGCOST){
                IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
            }
        }
        //进行单项工程级别的汇总
        for(let tender of tenders){
            summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID]);
        }
        //进行建设项目级别的汇总
        for(let eng of engineerings){
            summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID]);
        }
        //占造价比例、单方造价
        const rateDecimal = -2;
        const perCostDecimal = -2;
        for(let tender of tenders){
            let tenderInfo = IDMapping[tender.ID];
            let engInfo = IDMapping[tender.ParentID];
            tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
            //单方造价
            tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0 ?
                                 tenderInfo.buildingArea.toString().trim() : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
        }
        for(let eng of engineerings){
            let engInfo = IDMapping[eng.ID];
            let projInfo = IDMapping[eng.ParentID];
            engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
        }
        //建设项目占造价比例及单方造价
        for(let project of projects){
            let projectInfo = IDMapping[project.ID];
            projectInfo.rate = 100;
            projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0 ?
                                  projectInfo.buildingArea.toString().trim() : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
        }
    }
    return IDMapping;
}

//根据项目ID获取所属建设项目
//@param {Number}projectID @return {Object}
async function getConstructionProject(projectID){
    function returnProject(project){
        if(!project || project.projType === projectType.folder){
            return null;
        }
        if(project.projType === projectType.project){
            return project;
        }
    }
    let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
    let returnV = returnProject(project);
    if(returnV !== undefined){
        return returnV;
    }
    let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
    returnV = returnProject(parent);
    if(returnV !== undefined){
        return returnV;
    }
    let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
    returnV = returnProject(grandParent);
    return returnV !== undefined ? returnV : null;
}

//获取单位工程完整目录结构
//@param {Number}projectID @return {Arry}
async function getFullPath(projectID) {
    let fullPath = [];
    let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
    if(project){
        fullPath.push(project.name);
        await getParent(project.ParentID);
    }
    fullPath = fullPath.reverse();
    return fullPath;
    async function getParent(ParentID) {
        if(ParentID != -1){
            let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
            if(parent){
                fullPath.push(parent.name);
                await getParent(parent.ParentID);
            }
        }
    }
}

async function getProjectFeature(libID,feeStandardName){
    let lib = await featureLibModel.findOne({'ID':libID})
    if(lib){
        let eng = _.find(lib.feature,{'key':'engineering'})
        if(eng) eng.value = feeStandardName;
        return lib.feature;
    }else {
        return [];
    }
}

//获取projectIDs文件下所有子项目（不包括projectIDs本身）
async function getPosterityProjects(projectIDs) {
    let rst = [];
    async function getProjects(IDs) {
        if (IDs.length > 0) {
            let newIDs = [];
            let projs = await projectModel.find({ParentID: {$in: IDs}, $or: notDeleted}, '-_id');
            for (let proj of projs) {
                rst.push(proj);
                newIDs.push(proj.ID);
            }
            await getProjects(newIDs);
        }
    }
    await getProjects(projectIDs);
    return rst;
}

//根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
//@param {String}userId {Object}tender @return {Object} || {null}
async function getShareInfo(userId, project) {
    //与该用户相关的分享
    let shareList = [];
    while (project) {
        for(let shareData of project.shareInfo){
            if(shareData.userID === userId){
                shareList.push(shareData);
                break;
            }
        }
        project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
    }
    //获取最新分享
    shareList.sort(function (a, b) {
        let aV = Date.parse(a.shareDate),
            bV = Date.parse(b.shareDate);
        if (aV > bV) {
            return -1;
        } else if (aV < bV) {
            return 1;
        }
        return 0;
    });
    return shareList[0] || null;
}

//打开的单位工程是否是被分享的.
async function isShare(userId, project){
    //判断是否是打开分享的项目，属于分享文件的子项也算
    while (project) {
        for(let shareData of project.shareInfo){
            if(shareData.userID === userId){
                return true;
            }
        }
        project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
    }
    return false;
}

//用户是否第一次进入费用定额
async function isFirst(userId, compilationId) {
    let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
    let first = false;
    if (userData) {
        first = !_.find(userData.used_list, function (o) {
            return o.compilationId === compilationId;
        });;
    }
    return first;
}

//用户第一次进入费用定额的数据准备
async function prepareInitialData(userId, compilation, example) {
    let first = await isFirst(userId, compilation);
    if (first) {
        await updateUsedList(userId, compilation);
        let prepareTask = [
            copyCompleRationSection(userId, compilation),
            copyCompleGljSection(userId, compilation)
        ];
        if (example && example.length > 0) {
            prepareTask.push(copyExample(userId, compilation, example));
        }
        await Promise.all(prepareTask);
    }
}

async function updateUsedList(userId, compilation) {
    await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
}

//拷贝补充定额章节树
async function copyCompleRationSection(userId, compilationId) {
    await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
}
//拷贝补充人材机分类树
async function copyCompleGljSection(userId, compilationId) {
    let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
    if (templateData.length > 0) {
        let insertDatas = [],
            uuidMapping = {};
        //将ID替换成UUID
        for (let temData of templateData) {
            uuidMapping[temData.ID] = uuidV1();
        }
        for(let temData of templateData) {
            let insertD = {
                userId: userId,
                compilationId: compilationId,
                Name: temData.Name,
                ID: uuidMapping[temData.ID],
                ParentID: uuidMapping[temData.ParentID] || -1,
                NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
            };
            insertDatas.push(insertD);
        }
        //插入数据
        await compleGljSectionModel.insertMany(insertDatas);
    }
}


async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件，type从单前建设项目还是从其它建设项目中复制
    let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件，选中多个的时候只需复制一次
    let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
    for(let d of datas){
        let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
        if(type == 1 && tem_file){//从建设项目复制时，只有第一次需要复制，剩下的就相当于使用同个建设项目的情况了
            let newID =  from == "feeRateFile"?tem_file.ID:tem_file.id;
            newFile = {id:newID,name:tem_file.name};
            type = 0;
        }
        projectIDs.push({ID:d.projectID})
    }
    await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态

}