var _eval, logger;

_eval = require('eval');

const _ = require('lodash');

global.InstanceManager = {};

// logger = new Logger('Workflow -> InstanceManager');

InstanceManager.handlerInstanceByFieldMap = function (ins, field_map) {
    var context, e, flow, res, script;
    res = ins;
    if (ins) {
        if (!field_map) {
            flow = db.flows.findOne({
                _id: ins.flow
            }, {
                fields: {
                    field_map: 1
                }
            });
            if (flow != null ? flow.field_map : void 0) {
                field_map = flow.field_map;
            }
        }
        if (field_map) {
            context = _.clone(ins);
            context._ = _;
            script = `var instances = ${field_map}; exports.instances = instances`;
            try {
                res = _eval(script, "handlerInstanceByFieldMap", context, false).instances;
            } catch (error) {
                e = error;
                res = {
                    _error: e
                };
                // logger.error(e);
                console.error(e);
            }
        }
    }
    return res;
};

InstanceManager.getCurrentApprove = function (instance, handler, type) {
    var currentApprove, currentApproves, currentTraces;
    if (!instance || !instance.traces || instance.traces.length < 1) {
        return;
    }

    currentTraces = _.filter(instance.traces, { is_finished: false });

    if (currentTraces.length) {
        if (type){
            currentApproves = _.filter(currentTraces[0].approves, { is_finished: false, handler: handler, type: type});
        }
        else {
            currentApproves = _.filter(currentTraces[0].approves, { is_finished: false, handler: handler });
        }
        currentApprove = currentApproves.length > 0 ? currentApproves[0] : null;
    }

    if (!currentApprove) {
        // 当前是传阅
        _.each(instance.traces, function (t) {
            _.each(t.approves, function (a) {
                if (a.type === 'cc' && a.user === handler && a.is_finished === false) {
                    currentApprove = a;
                }
            });
        });
    }
    if (!currentApprove) {
        return;
    }
    return currentApprove;
};

InstanceManager.getCurrentTrace = function (instance, traceId) {
    return instance.traces.findPropertyByPK("_id", traceId);
};

InstanceManager.getMyApprove = function (instanceId, userId) {
    var flow, instance, judge, my_approve, nextSteps, next_user_ids, step, step_type, trace;
    instance = db.instances.findOne({
        _id: instanceId
    });
    flow = uuflowManager.getFlow(instance.flow);
    my_approve = InstanceManager.getCurrentApprove(instance, userId);
    if (my_approve) {
        //		lang = Steedos.locale(that.userId, true)
        trace = InstanceManager.getCurrentTrace(instance, my_approve.trace);
        step = uuflowManager.getStep(instance, flow, trace.step);
        step_type = step.step_type;
        judge = step_type === "sign" ? "approved" : "";
        nextSteps = uuflowManager.getNextSteps(instance, flow, step, judge);
        if (nextSteps.length === 1) {
            if (step_type === "sign" || step_type === "counterSign") {
                my_approve.judge = 'approved';
            }
            next_user_ids = getHandlersManager.getHandlers(instance._id, nextSteps[0], userId);
            if (!next_user_ids) {
                my_approve.next_steps = [
                    {
                        step: nextSteps[0],
                        users: []
                    }
                ];
                return my_approve;
            }
            if (next_user_ids.length === 1) {
                my_approve.next_steps = [
                    {
                        step: nextSteps[0],
                        users: next_user_ids
                    }
                ];
                return my_approve;
            }
        }
    }
};

//			else
//				throw new Error(t('workflow_error_multiple_next_step_users', {insname: instance.name}, lang))
//		else
//			throw new Error(t('workflow_error_multiple_next_step', {insname: instance.name}, lang))
InstanceManager.getBatchInstances = function (space, categoryId, flowIds, inbox_user) {
    var FIELDS, _batch_instances, categoryFlows, inbox_instances, query, unCategoryFlows;
    _batch_instances = new Array();
    query = {
        space: space,
        inbox_users: inbox_user
    };
    FIELDS = {
        name: 1,
        applicant_name: 1,
        submit_date: 1,
        flow_version: 1,
        "traces.step": 1,
        flow: 1,
        current_step_name: 1,
        flow_name: 1
    };
    if (categoryId) {
        if (categoryId === '-1') {
            unCategoryFlows = flowManager.getUnCategoriesFlows(space, {
                _id: 1
            }).fetch().getProperty("_id");
            query.flow = {
                $in: unCategoryFlows
            };
        } else {
            categoryFlows = flowManager.getCategoriesFlows(space, categoryId, {
                _id: 1
            }).fetch().getProperty("_id");
            query.flow = {
                $in: categoryFlows
            };
        }
    }
    if (flowIds) {
        query.flow = {
            $in: flowIds
        };
    }
    //	console.log("query", JSON.stringify(query))
    inbox_instances = db.instances.find(query, {
        fields: FIELDS,
        skip: 0,
        limit: 100
    });
    inbox_instances.forEach(function (ins) {
        var currentStep, currentStepId, flow, myApprove;
        currentStepId = _.last(ins.traces).step; //TODO 此代码不适用传阅批处理
        flow = db.flows.findOne({
            _id: ins.flow
        });
        currentStep = stepManager.getStep(ins, flow, currentStepId);
        myApprove = InstanceManager.getMyApprove(ins._id, inbox_user);
        if (stepManager.allowBatch(currentStep) && myApprove) {
            delete ins.flow_version;
            delete ins.traces;
            delete ins.flow;
            ins.approve_start_date = myApprove.start_date;
            return _batch_instances.push(ins);
        }
    });
    //		else
    //			console.log("批量审批-异常数据", ins._id)
    return _batch_instances;
};


module.exports = InstanceManager;