/**
 * 工料机总库相关业务逻辑
 *
 * @author CaiAoLin
 * @date 2017/7/11
 * @version
 */
import mongoose from "mongoose";
import BaseModel from "../base/base_model";

class STDGLJLibGLJListModel extends BaseModel {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model("std_glj_lib_gljList");
        parent.init();
    }

    /**
     * 根据id获取数据
     *
     * @param {Number|Array} id
     * @return {Promise}
     */
    async getDataById(id) {
        let result = null;
        try {
            if (!id instanceof Array) {
                id = parseInt(id);
                if (isNaN(id)) {
                    throw 'id有误';
                }
            }
            let condition = {ID: {"$in": id}};
            result = await this.findDataByCondition(condition, null, false);
        } catch (error) {
            console.log(error);
            result = null;
        }

        return result;
    }

    /**
     * 获取对应组成物数据
     *
     * @param {Number} gljId
     * @return {Promise}
     */
    async getComponent(gljId) {
        let result = [];
        let libGljData = await this.findDataByCondition({ID: gljId});
        if (libGljData === null || libGljData.component.length <= 0) {
            return result;
        }

        let componentIdList = [];
        let componentConsume = {};
        // 整理数据
        for (let component of libGljData.component) {
            componentIdList.push(component.ID);
            if(component.consumeAmt != undefined && component.consumeAmt != null) {
                componentConsume[component.ID] = component.consumeAmt;
            }else if(component.consumeAmtProperty){
                componentConsume[component.ID] = component.consumeAmtProperty;
            }
        }

        let condition = {ID: {$in: componentIdList}};
        let componentGljData = await this.findDataByCondition(condition, null, false);

        if (componentGljData === null) {
            return result;
        }

        let componentData = [];
        componentGljData = JSON.stringify(componentGljData);
        componentGljData = JSON.parse(componentGljData);
        for(let gljData of componentGljData) {
            gljData.connectCode = libGljData.code;
            gljData.consumption = componentConsume[gljData.ID];
            gljData.from='std';
            componentData.push(gljData);
        }

        return componentData;
    }

}

export default STDGLJLibGLJListModel;