/**
 * 计价规则标准库业务逻辑
 *
 * @author CaiAoLin
 * @date 2017/8/31
 * @version
 */
import mongoose from "mongoose";
import BaseModel from "../../common/base/base_model";

class EngineeringLibModel extends BaseModel {
    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model('engineering_lib');
        parent.init();
    }

    /**
     * 获取标准库数据
     *
     * @param {Object} data
     * @return {Promise}
     */
    async getLib(data) {
        if (data.length <= 0) {
            return data;
        }
        let valuationIDs = [];
        // 整理出数据库需要查找的id，一次查找
        for(let valuation of data) {
            if (valuation === null) {
                continue;
            }
            if(valuation.id){
                valuationIDs.push(valuation.id);
            }
        }

        // 查找对应的id数据
        let condition = {visible:true,valuationID: {"$in": valuationIDs}};
        let engineeringLibList = await this.findDataByCondition(condition,null,false);
        engineeringLibList = JSON.parse(JSON.stringify(engineeringLibList));
        // 组合计价规则id对应专业工程标准库数据
        let engineeringLib = {};
        for(let engineering of engineeringLibList){
            let tem = {//做一下转换，和原来的结构一致
                engineering_id:engineering._id.toString(),
                engineering:engineering.engineering,
                lib:engineering
            };
            if(engineeringLib[engineering.valuationID] === undefined){
                engineeringLib[engineering.valuationID] = [tem];
            }else {
                engineeringLib[engineering.valuationID].push(tem);
            }
        }

        // 替换计价规则数据
        let valuationData = JSON.parse(JSON.stringify(data));

        for(let valuation of valuationData) {
            if (valuation === null) {
                continue;
            }
            valuation.engineering_list = [];
            if(engineeringLib[valuation.id]){
                valuation.engineering_list = engineeringLib[valuation.id]
            }
        }
        return valuationData;
    };

    async getEngineering(engineering_id) {
        let condition = {_id: engineering_id};
        let engineering = await this.findDataByCondition(condition);

        return engineering;
    };

}

module.exports = EngineeringLibModel;
