// 开这个模块的最初原因：重构ESModule为CommonJS以升级node版本后，遇到module循环引用问题，将造成循环引用的方法抽离放到这个模块
module.exports = {
    getNewProjectGLJFromMissMixratio,
    getProjectGLJNewData,
    setIDfromCounter,
    getUnitPriceFileId,
};

const scMathUtil = require('../../../public/scMathUtil').getUtil();
const mongoose = require('mongoose');
const std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
const counterModel = mongoose.model('counter');
const projectsModel = mongoose.model('projects');

//根据缺少项目工料机的组成物信息，反向生成对应的项目工料机
async function getNewProjectGLJFromMissMixratio(projectID, lessMix, projectGLJMap, newProjectGLJList, ext) {
    let lessIDList = [];
    let uniqMap = {};//去重
    let lessStdMix = [];//防止组成物中改了名称等，但是通过glj_id取出来的是还没改前的原始数据
    if (lessMix.length > 0) {
        for (let lm of lessMix) {
            let parentglj = projectGLJMap[lm.connect_key];
            if (!parentglj) throw `含有组成物工料机${lm.connect_key}，没有找到，添加定额失败`;
            if ((parentglj.from == "std" || lm.from == "std") && lm.code != "80CCS") {//车船税特殊处理
                if (!uniqMap[lm.glj_id]) {
                    lessIDList.push(lm.glj_id);
                    uniqMap[lm.glj_id] = lm;
                }
                lessStdMix.push(lm);
            } else {//来自组成物的直接设置    
                lm.from = 'cpt';
                lm.gljType = lm.type;
                let t_mg = getProjectGLJNewData(lm, projectID);
                newProjectGLJList.push(t_mg);
                projectGLJMap[getIndex(lm)] = t_mg;
            }
        }
    }

    if (lessIDList.length > 0) {
        let less_stds = await std_glj_lib_gljList_model.find({ 'ID': { '$in': lessIDList } }).lean();
        let less_stds_map = {};
        for (let les of less_stds) {
            less_stds_map[les.ID] = les;
        }
        for (let t_l_m of lessStdMix) {
            let t_nglj = less_stds_map[t_l_m.glj_id];
            t_nglj.from = 'std';
            //防止组成物中改了名称等，但是通过glj_id取出来的是还没改前的原始数据
            t_nglj.name = t_l_m.name;
            t_nglj.code = t_l_m.code;
            t_nglj.gljType = t_l_m.type;
            t_nglj.specs = t_l_m.specs;
            t_nglj.unit = t_l_m.unit;
            let t_np = getProjectGLJNewData(t_nglj, projectID, ext);
            newProjectGLJList.push(t_np);
            projectGLJMap[getIndex(t_l_m)] = t_np;
        }
    }
    return newProjectGLJList;
}


function getProjectGLJNewData(tmp, projectId, ext) {
    let gljData = {
        glj_id: tmp.ID,
        repositoryId: tmp.repositoryId,
        project_id: projectId,
        code: tmp.code,
        name: tmp.name,
        specs: tmp.specs ? tmp.specs : '',
        unit: tmp.unit === undefined ? '' : tmp.unit,
        type: tmp.gljType,
        adjCoe: tmp.adjCoe,
        original_code: tmp.code,
        materialType: tmp.materialType,   //三材类别
        materialCoe: tmp.materialCoe,
        base_price: tmp.basePrice,
        market_price: tmp.basePrice,
        is_main_material: tmp.is_main_material ? tmp.is_main_material : 1,
        from: tmp.from ? tmp.from : "std"
    };
    if (gljData.from == 'std' && ext && ext.priceField && (tmp.priceProperty && tmp.priceProperty[ext.priceField] != undefined && tmp.priceProperty[ext.priceField] != null)) {
        const basePrice = scMathUtil.roundTo(tmp.priceProperty[ext.priceField], -6);
        gljData.base_price = basePrice;
        gljData.market_price = basePrice;
    }
    return gljData;
}

async function setIDfromCounter(name, list, map, keyfield) {//map,keyfield

    let update = { $inc: { sequence_value: list.length } };
    let condition = { _id: name };
    let options = { new: true };

    // 先查找更新
    let counter = await counterModel.findOneAndUpdate(condition, update, options);
    let firstID = counter.sequence_value - (list.length - 1);
    for (let a of list) {
        a.id = firstID;
        firstID += 1
        if (map && keyfield) {
            let key = a[keyfield];
            map[key] ? map[key].push(a) : map[key] = [a]
        }
    }

}

/**
 * 根据项目id获取单价文件列表id
 *
 * @param {Number} projectId
 * @return {Promise}
 */
async function getUnitPriceFileId(projectId) {
    let result = 0;
    let startTime = +new Date();
    let projectData = await projectsModel.find({ ID: projectId }, ['property.unitPriceFile']);
    if (projectData === null) {
        return result;
    }
    let endTime = +new Date();
    console.log("取单价文件列表id时间-----" + (endTime - startTime));
    projectData = projectData[0];
    result = projectData.property.unitPriceFile !== undefined ? projectData.property.unitPriceFile.id : 0;
    return result;
};