const objectql = require('@steedos/objectql');
const ImportManager = require('../../main/default/manager/import');
const ExportManager = require('../../main/default/manager/export');
const { getCollection } = require("../../main/default/utils/collection");
const _ = require('lodash');

module.exports = {
    rest: {
        method: 'POST',
        fullPath: '/api/workflow/flow_copy'
    },
    params: {
        flowId: { type: 'string' }, // 流程id
        options: { type: 'object', optional: true }, // 复制选项
    },
    async handler(ctx) {
        const userSession = ctx.meta.user;
        const { userId, spaceId, locale } = userSession
        const lang = locale === 'zh-cn' ? 'zh-CN' : 'en';
        const { flowId, options } = ctx.params;

        const { company_id } = options || {};

        const flowsObj = this.getObject('flows');
        const db = {
            flows: await getCollection('flows')
        }

        var flow, form, newFlowName, newName, ref;
        var templateSpaceId = objectql.getTemplateSpaceId();
        if (templateSpaceId === 'template' && options.from === 'template') {
            var data = await flowsObj.findOne(flowId, {}, Object.assign({ roles: ['admin'] }, { spaceId: templateSpaceId }));
            await ImportManager.workflow(userId, spaceId, data, enabled, company_id);
        } else {
            var flowQuery = {
                _id: flowId
            }
            if (templateSpaceId) {
                flowQuery["$or"] = [{ space: templateSpaceId }, { space: spaceId }]
            } else {
                flowQuery.space = spaceId
            }
            flow = await db.flows.findOne(flowQuery, {
                projection: {
                    _id: 1,
                    name: 1,
                    form: 1
                }
            });
            if (!flow) {
                throw new Error(`[flow.copy]未找到flow, space: ${spaceId}, flowId: ${flowId}`);
            }
            newFlowName = options != null ? options.name : void 0;
            if (newFlowName) {
                newName = newFlowName;
            } else {
                newName = "复制:" + flow.name;
            }
            form = await ExportManager.exportForm(flow.form, flow._id, true, company_id);
            if (_.isEmpty(form)) {
                throw new Error(`[flow.copy]未找到form, formId: ${flow.form}`);
            }
            form.name = newName;
            if ((ref = form.flows) != null) {
                ref.forEach(function (f) {
                    delete f.api_name
                    return f.name = newName;
                });
            }
            delete form.api_name

            await ImportManager.workflow(userId, spaceId, form, false, company_id);
        }

        return {
            'status': 0, // 返回 0，表示当前接口正确返回，否则按错误请求处理
            'msg': t('workflow_copy_flow_success', {}, lang),//'草稿已删除',
            'data': {}
        }
    }
}