/**
 * Created by zhang on 2019/1/2.
 */
module.exports={ //先导出后require可以解决循环引用问题
    changeUnitFile:changeUnitFile,
    updateEvaluateMaterial:updateEvaluateMaterial
};

const mongoose = require('mongoose');
const ProjectModel = require('../../pm/models/project_model').project;
const commonFacade = require('../../main/facade/common_facade');
const UnitPriceFileModel = require("../models/unit_price_file_model");
const UnitPriceModel = require("../models/unit_price_model");
const MixRatioModel = require("../models/mix_ratio_model");
let evaluateListModel = mongoose.model("evaluate_list");
let bidEvaluationMode = mongoose.model("bid_evaluation_list");
let contractorListModel = mongoose.model("contractor_list");
let projectGLJModel = mongoose.model("glj_list");
let unitFileMode = mongoose.model("unit_price");

async function changeUnitFile(projectData,unitFile,type,userID) {
    let projectId = projectData.projectID;
    let changeUnitPriceId = unitFile.id;
    let newName = unitFile.name;
    type = parseInt(type);

        let currentUnitPriceId = await commonFacade.getUnitPriceFileId(projectId);
        let unitPriceFileModel = new UnitPriceFileModel();

        let insertData = null;
        if (type > 0) {
            let currentUnitPrice = await unitPriceFileModel.findDataByCondition({id: changeUnitPriceId});
            if (currentUnitPrice === null) {
                throw '不存在对应单价文件';
            }
            // 获取当前项目的rootProjectId
            let projectData = await ProjectModel.getProject(projectId);
            let rootProjectId = projectData.property.rootProjectID !== undefined ? projectData.property.rootProjectID : 0;

            insertData = JSON.parse(JSON.stringify(currentUnitPrice));
            insertData.root_project_id = rootProjectId;
            newName?insertData.name = newName:'';
            insertData.user_id = userID;
            delete insertData._id;
            delete insertData.ID;
        }
        // 获取即将更改的单价文件信息
        let targetUnitPriceFile = type === 0 ? await unitPriceFileModel.findDataByCondition({id: changeUnitPriceId}) :
            await unitPriceFileModel.add(insertData);
        if (targetUnitPriceFile === null) {
            throw '没有找到对应的单价文件';
        }

        // 查找对应单价文件的项目工料机数据
        let unitPriceModel = new UnitPriceModel();
        if(type ===1){//从其它项目复制，则先复制一份数据。
            let needCopyList = await unitPriceModel.findDataByCondition({unit_price_file_id: changeUnitPriceId}, null, false);
            if(needCopyList){
                // 过滤mongoose格式
                needCopyList = JSON.stringify(needCopyList);
                needCopyList = JSON.parse(needCopyList);
                let copyList = [];
                for(let n of needCopyList){
                    delete n._id;  // 删除原有id信息
                    delete n.id;
                    n.unit_price_file_id = targetUnitPriceFile.id;
                    copyList.push(n);
                }
                copyList.length>0 ? await unitPriceModel.add(copyList):'';
                  //也要复制一份组成物信息和材料计算信息
                  let mixRatioModel = new MixRatioModel();
                  await mixRatioModel.copyNotExist(changeUnitPriceId, targetUnitPriceFile.id,{},true);//复制组成物
            }
        }


        let copyResult = await unitPriceModel.copyNotExist(currentUnitPriceId, targetUnitPriceFile.id,projectId);
        // 复制成功后更改project数据
        if (!copyResult) {
            throw '复制数据失败';
        }

        let changeUnitPriceFileInfo = {
            id: targetUnitPriceFile.id,
            name: targetUnitPriceFile.name
        };
        let result = ProjectModel.changeUnitPriceFileInfo(projectId, changeUnitPriceFileInfo);
        if (!result) {
            throw '切换单价文件失败!';
        }
        return changeUnitPriceFileInfo;
}


async function updateEvaluateMaterial(data) {
    let modelMap = {
        "glj_list":projectGLJModel,
        "evaluate_list":evaluateListModel,
        "unit_price":unitFileMode,
        "bid_evaluation_list":bidEvaluationMode,
        "contractor_list":contractorListModel
    };
    for(let t of data.tasks){
        let model = modelMap[t.type];
        switch (t.action) {
            case "update":
                let query = {};
                if(t.hasOwnProperty('ID')) query['ID'] = t.ID;
                if(t.hasOwnProperty('id')) query['id'] = t.id;
                await model.update(query,t.doc);
                break;
            case "add":
                await model.create(t.doc);
                break;
            case "delete":
                await model.deleteOne({ID:t.ID});
                break;
        }
    }
}
