/*
 * @Author: baozhoutao@steedos.com
 * @Date: 2022-04-04 16:34:28
 * @Description: 
 */
const express = require('express');
const router = express.Router();
const auth = require('@steedos/auth');
const ejs = require('ejs');
const _ = require('lodash');
const objectql = require('@steedos/objectql');

router.get('/api/workflow/form_design', auth.requireAuthentication, async function (req, res) {
    try {
        res.set('Content-Type', 'text/html');
        const userSession = req.user;
        let assetUrls = req.query.assetUrls;
        const assetUrl = `assetUrl=${assetUrls.split(',').join("&assetUrl=")}&`;

        // const dataContext = {
        //     rootUrl: process.env.ROOT_URL,
        //     tenantId: userSession.spaceId,
        //     userId: userSession.userId,
        //     authToken: userSession.authToken
        // }
        let locale = userSession.language || process.env.STEEDOS_DEFAULT_LANGUAGE || "zh-CN";
        if (req.query.locale?.startsWith('en')) {
            locale = "en-US";
        } else if (req.query.locale == "zh-cn") {
            locale = "zh-CN";
        }
        const retUrl = req.query.retUrl || process.env.ROOT_URL + '/app/admin/flows/view/' + req.query.fid
        const steedosBuilderUrl = process.env.STEEDOS_BUILDER_URL || 'https://builder.steedos.cn';
        const builderHost = `${steedosBuilderUrl}/object?${assetUrl}retUrl=${retUrl}&locale=${locale}&isObjectDesign=1&pType=objectDesign`;

        const filename = __dirname+'/flow_form_design.ejs';

        const flow = await objectql.getObject('flows').findOne(req.query.fid);
        const data = {
            builderHost,
            assetUrls,
            rootUrl: process.env.ROOT_URL,
            tenantId: userSession.spaceId,
            userId: userSession.userId,
            authToken: userSession.authToken,
            userSession: userSession,
            id: flow.form,
            useOpenAPI: process.env.STEEDOS_PUBLIC_USE_OPEN_API,
            locale
        }
        const options = {}
        ejs.renderFile(filename, data, options, function(err, str){
            if(err){
                console.log(`err`, err)
            }
            // str => Rendered HTML string
            res.send(str);
        });

    } catch (error) {
        console.log(error)
        res.status(500).send({ message: error.message });
    }

});


router.get('/api/workflow/form_design/schema', auth.requireAuthentication, async function (req, res) {
    const id = req.query.id;
    if(!id){
        res.status(200).send({ status: 500, msg: "缺少参数: id", data: {} }); 
    }
    const form = await objectql.getObject("forms").findOne(id);
    res.status(200).send({ 
        status: 0, 
        msg: "", 
        schema: {
            type: 'steedos-flow-form',
            name: form.name,
            label: form.name,
            description: form.description,
            className: "steedos-flow-form steedos-flow-layout-page",
            body: []
        }
     });
})

router.post('/api/workflow/form_design/schema', auth.requireAuthentication, async function (req, res) {
    const id = req.query.id;
    if(!id){
        res.status(200).send({ status: 500, msg: "缺少参数: id", data: {} }); 
    }

    let userSession = req.user;
    const isSpaceAdmin = userSession.is_space_admin;

    if(!isSpaceAdmin){
        throw new Error('no permission!')
    }
    const form = await objectql.getObject("forms").findOne(id);

    

    res.status(200).send({ 
        status: 0, 
        msg: "", 
        schema: {
            type: 'steedos-flow-form',
            name: form.name,
            label: form.name,
            description: form.description,
            className: "steedos-flow-form steedos-flow-layout-page",
            body: []
        }
     });
})
exports.default = router;