/*
 * @Author: sunhaolin@hotoa.com
 * @Date: 2022-12-24 11:56:18
 * @LastEditors: sunhaolin@hotoa.com
 * @LastEditTime: 2022-12-26 11:18:12
 * @Description: 
 */
'use strict';
// @ts-check
const express = require('express');
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const WorkflowManager = require('../manager/workflow_manager');
const { getCollection } = require('../utils/collection');
const _ = require('underscore');
const moment = require('moment')
const fs = require('fs')
const path = require('path')
/**
@api {get} /api/workflow/export/instances 申请单导出
@apiVersion 0.0.0
@apiName /api/workflow/export/instances
@apiGroup service-workflow
@apiQuery {String} space_id 工作区ID
@apiQuery {String} flow_id 流程ID
@apiQuery {String} type 类型
@apiQuery {String} timezoneoffset 时区
@apiSuccessExample {xls} Success-Response:
    HTTP/1.1 200 OK
@apiErrorExample {json} Error-Response:
    HTTP/1.1 200 OK
    {
      errors: [{ errorMessage: e.message }]
    }
 */
router.get('/api/workflow/export/instances', requireAuthentication, async function (req, res) {
    try {
        const userSession = req.user;
        const userId = userSession.userId;
        const query = req.query;
        const space_id = query.space_id;
        const flow_id = query.flow_id;
        const type = parseInt(query.type);
        const timezoneoffset = parseInt(query.timezoneoffset);

        const flowsCollection = await getCollection('flows');
        const formsCollection = await getCollection('forms');
        const spacesCollection = await getCollection('spaces');
        const instancesCollection = await getCollection('instances');

        const flow = await flowsCollection.findOne(
            { _id: flow_id },
            { projection: { form: 1 } }
        );
        const form = await formsCollection.findOne(
            { _id: flow.form },
            { projection: { name: 1, 'current.fields': 1 } }
        );
        const form_name = form.name;
        const fields = form.current.fields;
        const table_fields = [];
        _.each(fields, function (field) {
            if (field.type === "table") {
                table_fields.push(field);
            }
        });

        let ins_to_xls = [];
        const now = new Date();
        const selector = {
            space: space_id,
            flow: flow_id,
            state: { $in: ["pending", "completed"] }
        };

        const uid = userId;
        const space = await spacesCollection.findOne({ _id: space_id });
        if (!space) {
            selector.state = "none";
        }
        if (space && !space.admins.includes(uid)) {
            const flow_ids = await WorkflowManager.getMyAdminOrMonitorFlows(space_id, uid);
            if (!flow_ids.includes(flow_id)) {
                selector.$or = [
                    { submitter: uid },
                    { applicant: uid },
                    { inbox_users: uid },
                    { outbox_users: uid }
                ];
            }
        }

        // 0-本月
        if (type === 0) {
            const start_date = new Date(now.getFullYear(), now.getMonth(), 1);
            selector.submit_date = { $gte: start_date };
        // 1-上月
        } else if (type === 1) {
            const last_month_date = new Date(new Date(now.getFullYear(), now.getMonth(), 1) - 1000 * 60 * 60 * 24);
            const start_date = new Date(last_month_date.getFullYear(), last_month_date.getMonth(), 1);
            const end_date = new Date(now.getFullYear(), now.getMonth(), 1);
            selector.submit_date = { $gte: start_date, $lte: end_date };
        // 2-整个年度
        } else if (type === 2) {
            const start_date = new Date(now.getFullYear(), 0, 1);
            selector.submit_date = { $gte: start_date };
        }
        // 3-所有: 不加 submit_date 过滤

        ins_to_xls = await instancesCollection.find(selector).sort({ submit_date: 1 }).toArray();

        const ejs = require('ejs');
        const str = fs.readFileSync(path.resolve(__dirname, '../server/ejs/export_instances.ejs'), 'utf8');
        const template = ejs.compile(str);
        let lang = 'en';
        if (userSession.locale === 'zh-cn') {
            lang = 'zh-CN';
        }
        const utcOffset = timezoneoffset / -60;
        const formatDate = function (date, formater) {
            return moment(date).utcOffset(utcOffset).format(formater);
        };
        const ret = template({
            lang: lang,
            formatDate: formatDate,
            form_name: form_name,
            fields: fields,
            table_fields: table_fields,
            ins_to_xls: ins_to_xls
        });
        const fileName = "SteedOSWorkflow_" + moment().format('YYYYMMDDHHmm') + ".xls";
        res.setHeader("Content-type", "application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + encodeURI(fileName));
        return res.end(ret);
    } catch (e) {
        console.error(e);
        res.status(200).send({
            errors: [{ errorMessage: e.message }]
        });
    }
});
exports.default = router;
