/**
 * Created by Tony on 2017/7/6.
 */
let mongoose = require('mongoose');
let cacheUtil = require('./cacheUtil');
let std_glj_type_mdl = mongoose.model("std_glj_type");

const STD_GLJ_GRP = 'std_glj_grp';

function getStdGljTypeCache() {
    let rst = cacheUtil.getCache(STD_GLJ_GRP,'default');
    return rst;
};

class StdGljTypeClass{
    //根据id获取临时数据
    constructor() {
        this.innerGljTypeObj = null;
    };

    build(cache){
        let me = this, rst = {};
        rst.items = [];
        let private_combine_glj_type = function (item, topParentId, parentId) {
            let tmpItem = {};
            tmpItem.ID = item.ID;
            tmpItem.TopParentID = topParentId;
            tmpItem.ParentID = parentId;
            tmpItem.fullName = item.fullName;
            tmpItem.shortName = item.shortName;
            rst["typeId" + item.ID] = tmpItem;
            rst.items.push(tmpItem);
            if (item.items) {
                for (let subItem of item.items) {
                    private_combine_glj_type(subItem, topParentId, item.ID);
                }
            }
        }
        for (let item of cache.typesDefine) {
            private_combine_glj_type(item, item.ID, -1);
        }
        me.innerGljTypeObj = rst;
    };

    getItemById(Id) {
        let me = this, rst = null;
        if (me.innerGljTypeObj) {
            rst = me.innerGljTypeObj["typeId" + Id];
        }
        return rst;
    };

    getTopParentIdByItemId(itemId) {
        let me = this, rst = itemId;
        if (me.innerGljTypeObj) {
            let item = me.innerGljTypeObj["typeId" + itemId];
            if (item) {
                rst = item.TopParentID;
            }
        }
        return rst;
    };

    toArray(){
        let me = this, rst = null;
        return me.innerGljTypeObj.items;
    }
};

module.exports = {
    stdGljTypeObj: null,
    setStdGljTypeCache: function () {
        std_glj_type_mdl.find({typeName: "默认"}, '-_id', function(err, typeObj){
            if(typeObj.length){
                cacheUtil.setCache(STD_GLJ_GRP,'default',typeObj[0]);
            }
        })
    },
    getStdGljTypeCacheObj: function () {
        let me = this,
            rst = null,
            cache = getStdGljTypeCache();
        if (me.stdGljTypeObj) {
            rst = me.stdGljTypeObj;
        } else if (cache) {
            rst = new StdGljTypeClass();
            rst.build(cache);
            me.stdGljTypeObj = rst;
        }
        return rst;
    }
}