/**
 * Created by zhang on 2018/1/31.
 */
const mongoose = require('mongoose');
const installSectionModel = mongoose.model("std_ration_lib_installationSection");
const installFeeItemModel = mongoose.model("std_ration_lib_installation");
let installationFeeModel = mongoose.model("installation_fee");
let engineeringModel = mongoose.model('engineering_lib');
const uuidV1 = require('uuid/v1');
let consts = require('../../main/models/project_consts');

module.exports={
    copyInstallationFeeFromLib:copyInstallationFeeFromLib,
    updateInstallationFee:updateInstallationFee,
    resetToDefault:resetToDefault,
    getData:getData
};
async function updateInstallationFee(projectID,updateData) {
    let result = {};
    let tasks = generateUpdateTask(projectID,updateData);
    if(tasks.length>0){
         result =await installationFeeModel.bulkWrite(tasks);
    }
    return result;
}

function generateUpdateTask(projectID,updateData) {
    let tasks = [];
    if(updateData){
        if(updateData instanceof Array){
            for(let ud of updateData){
                let [uquery,udoc] = createUpdateQuery(projectID,ud);
                let task={
                    updateOne:{
                        filter:uquery,
                        update :udoc
                    }
                };
                tasks.push(task);
            }
        } else {
            let [query,doc] = createUpdateQuery(projectID,updateData);
            let task={
                updateOne:{
                    filter:query,
                    update :doc
                }
            };
            tasks.push(task);
        }
    }
    return tasks;

}

function createUpdateQuery(projectID,data) {
    let updateKey = data.type+'.ID';
    let query = {
        projectID:projectID,
        ID:data.ID,
    };
    query[updateKey] = data.itemID;
    let udoc = {};
    for(let property in data.doc){
        udoc[data.type+'.$.'+property] = data.doc[property];
    }
    return [query,udoc];
}

/*[
    {libID:56,ID:123558}
]*/
async function resetToDefault(projectID,installFees) {
    let newInstallFees = [];
    for(let inf of installFees){
        let newInstallationFee = await getInstallationFeeFromLib(inf.libID);
        if(newInstallationFee){
          let updateResult =  await installationFeeModel.findOneAndUpdate({projectID:projectID,ID:inf.ID},newInstallationFee,{new: true});
            newInstallFees.push(updateResult);
        }
    }
    return newInstallFees;
}


async function copyInstallationFeeFromLib(projectID,engineering_id) {

    //安装增加费用内嵌文档的方式
    let engineering = await engineeringModel.findById(engineering_id);
    let ration_lib = engineering.ration_lib;
    let installationFeeList = [];
    for(let rl of ration_lib){
        let newInstallationFee = await getInstallationFeeFromLib(rl.id);
        if(newInstallationFee){
            newInstallationFee.libID = rl.id;
            newInstallationFee.libName = rl.name;
            newInstallationFee.projectID = projectID;
            newInstallationFee.ID = uuidV1();
            installationFeeList.push(newInstallationFee);
        }
    }
    if(installationFeeList.length > 0){
        await installationFeeModel.insertMany(installationFeeList);
    }
}

async function getInstallationFeeFromLib(libID) {
        let installFeeItems = await installFeeItemModel.find({'rationRepId':libID});
        let installSections = await installSectionModel.find({'rationRepId':libID});
        let positionMap = {};
        let create = false;
        let newInstallationFee={};
        if(installFeeItems && installFeeItems.length > 0) {//费用项
            create = true;
            let tem_installFeeItem = [];
            for(let ifee of installFeeItems){
                let tem_fee ={
                    feeItem:ifee.feeItem,
                    feeType:ifee.feeType,
                    position:ifee.position,
                    ID:ifee.ID
                };
                positionMap[ifee.ID] = ifee.position;//设置选取位置对应表，为给规项赋值
                tem_installFeeItem.push(tem_fee);
            }
            newInstallationFee.installFeeItem = tem_installFeeItem;
        }

        if(installSections && installSections.length > 0){//章节项
            create = true;
            let tem_installSections = [];
            let tem_feeRules = [];
            for(let isect of installSections){
                let tem_sec={
                    ID:isect.ID,
                    name:isect.name,
                    feeItemId:isect.feeItemId
                };
                if(isect.feeRule && isect.feeRule.length > 0){//规则项
                    tem_sec.feeRuleId = isect.feeRule[0].ID; //选中第一个
                    for(let ifeeR of isect.feeRule){
                        let tem_feeRule = {
                            ID: ifeeR.ID,
                            code: ifeeR.code,
                            rule: ifeeR.rule,
                            base: ifeeR.base,
                            feeRate: ifeeR.feeRate,
                            labour: ifeeR.labour,
                            material: ifeeR.material,
                            machine: ifeeR.machine,
                            sectionId:isect.ID,
                            feeItemId:isect.feeItemId,
                            position:positionMap[isect.feeItemId]
                        };
                        tem_feeRules.push(tem_feeRule);
                    }
                }else {
                    tem_sec.feeRuleId = "";
                }
                tem_installSections.push(tem_sec);
            }
            newInstallationFee.installSection = tem_installSections;
            newInstallationFee.feeRule = tem_feeRules;
        }
        if(create == true){
            return newInstallationFee;
        }
        return null;
}


function getData(projectID, callback) {
    installationFeeModel.find({'projectID': projectID}, (err, datas) => {
        if (err) {
            callback(1, '', null);
        } else {
            callback(0, consts.projectConst.INSTALLATION_FEE, datas);
        }
    })
}


