/*
 * @Author: sunhaolin@hotoa.com 
 * @Date: 2022-03-26 10:49:56 
 * @Last Modified by: sunhaolin@hotoa.com
 * @Last Modified time: 2022-03-26 10:53:34
 */
'use strict';
// @ts-check
const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const objectql = require('@steedos/objectql');
const _ = require('lodash');
const Fiber = function(fun){console.log('TODO Fiber...')}
const { excuteTriggers } = require('../utils/trigger');
const { getStep } = require('../uuflowManager');
const UUFlowManager = require('../manager/uuflow_manager');
const afterHook = require('./afterHook');
/**
 * 审批中提交申请单
 * body {
    "Approvals": [
        {
            "_id": "3c9636c152d52b056ef9ccec",
            "instance": "siDye2BhC3XMGHmrK",
            "trace": "848556e079844c1c94305a63",
            "is_finished": false,
            "user": "61d425a7e9aa4c36e87ba8d1",
            "user_name": "孙浩林",
            "handler": "61d425a7e9aa4c36e87ba8d1",
            "handler_name": "孙浩林",
            "handler_organization_fullname": "s",
            "start_date": "2022-03-18T06:19:13.811Z",
            "due_date": "2022-03-25T06:19:13.765Z",
            "is_read": true,
            "values": {
                "文本": "",
                "文本1": ""
            },
            "read_date": "2022-03-18T11:40:54.469Z",
            "id": "3c9636c152d52b056ef9ccec",
            "description": "",
            "judge": "approved",
            "next_steps": [
                {
                    "step": "8c240799-753d-437e-8928-7683494688e4",
                    "users": [
                        "61d425a7e9aa4c36e87ba8d1"
                    ]
                }
            ]
        }
    ]
 * }
 */
router.post('/api/workflow/engine', requireAuthentication, afterHook, async function (req, res) {
    const startTime = Date.now();
    console.log(`[workflow/engine] start`);
    try {
        let userSession = req.user;
        const spaceId = userSession.spaceId;
        const userId = userSession.userId;
        userSession._id = userId;
        // const isSpaceAdmin = userSession.is_space_admin;

        var hashData = req.body;
        const approve_from_client = hashData['Approvals'][0];

        // beforeStepSubmit
        const insId = approve_from_client.instance;
        const t1 = Date.now();
        const instanceDoc = await objectql.getObject('instances').findOne(insId, { fields: ['flow', 'flow_version'] });
        console.log(`[workflow/engine] getObject instances took ${Date.now() - t1}ms`);
        const flowId = instanceDoc.flow;
        const t2 = Date.now();
        await excuteTriggers({ when: 'beforeStepSubmit', userId, flowId, insId });
        console.log(`[workflow/engine] beforeStepSubmit took ${Date.now() - t2}ms`);
        // beforeEnd
        const t3 = Date.now();
        const flowDoc = await objectql.getObject('flows').findOne(flowId);
        console.log(`[workflow/engine] beforeEnd find logic took ${Date.now() - t3}ms`);
        const next_steps = approve_from_client["next_steps"];
        const next_step_id = next_steps[0]["step"];
        const next_step = getStep(instanceDoc, flowDoc, next_step_id);
        const next_step_type = next_step["step_type"];
        if (next_step_type == "end") {
            await excuteTriggers({ when: 'beforeEnd', userId, flowId, insId });
        }
        console.log(`[workflow/engine] beforeEnd logic took ${Date.now() - t3}ms`);

        try {
            const t4 = Date.now();
            const instance = await UUFlowManager.workflow_engine(approve_from_client, userSession, userId);
            console.log(`[workflow/engine] workflow_engine took ${Date.now() - t4}ms`);
            // afterStepSubmit
            const t5 = Date.now();
            await excuteTriggers({ when: 'afterStepSubmit', userId, flowId, insId });
            console.log(`[workflow/engine] afterStepSubmit took ${Date.now() - t5}ms`);
            // afterEnd
            if (instance.state === 'completed') {
                const t6 = Date.now();
                await excuteTriggers({ when: 'afterEnd', userId, flowId, insId });
                console.log(`[workflow/engine] afterEnd took ${Date.now() - t6}ms`);
            }
            console.log(`[workflow/engine] total took ${Date.now() - startTime}ms`);
            res.status(200).send({});
        } catch (e) {
            console.log(`[workflow/engine] inner catch total took ${Date.now() - startTime}ms`);
            console.error(e);
            res.status(200).send({
                errors: [{ errorMessage: e.message }]
            });
        }

    } catch (e) {
        console.log(`[workflow/engine] outer catch total took ${Date.now() - startTime}ms`);
        res.status(200).send({
            errors: [{ errorMessage: e.message }]
        });
    }
});
exports.default = router;