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

class STDGLJLibGLJListModel extends BaseModel {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = STDRationLibGLJListSchemas;
        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 {String} code
     * @return {Promise}
     */
    async getComponent(code) {
        let result = [];
        let libGljData = await this.findDataByCondition({code: code});
        if (libGljData === null || libGljData.component.length <= 0) {
            return result;
        }

        let componentIdList = [];
        let componentConsume = {};
        // 整理数据
        for (let component of libGljData.component) {
            componentIdList.push(component.ID);
            componentConsume[component.ID] = component.consumeAmt;
        }

        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 = code;
            gljData.consumption = componentConsume[gljData.ID];
            componentData.push(gljData);
        }

        return componentData;
    }

}

export default STDGLJLibGLJListModel;