/*
 * @Author: baozhoutao@steedos.com
 * @Date: 2022-09-15 13:09:51
 * @LastEditors: sunhaolin@hotoa.com
 * @LastEditTime: 2023-01-14 11:06:17
 * @Description: 
 */
const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const _ = require('lodash');
const {
    remove_instance_tasks_by_instance_id,
} = require('../manager/instance_tasks_manager')
const WorkflowManager = require('../manager/workflow_manager');
const UUFlowManager = require('../manager/uuflow_manager');
const pushManager = require('../manager/push_manager');
const { getCollection } = require("@steedos-labs/plugin-workflow/main/default/utils/collection");
//TODO 
/**
 * body: {
 *  instance: {
 *     _id: 'xxx'
 *  }
 * }
 */
router.post('/api/workflow/v2/remove', requireAuthentication, async function (req, res) {
    try {
        const db = {
            flows: await getCollection('flows'),
            organizations: await getCollection('organizations'),
            instances: await getCollection('instances'), 
            deleted_instances: await getCollection('deleted_instances')
        }
        let userSession = req.user;
        const current_user = userSession.userId;
        const { instance: data } = req.body;
        var cc_users, delete_obj, flow, inbox_users, instance, space, spaceUserOrganizations, space_id, space_user, user_ids;
        instance = await UUFlowManager.getInstance(data._id);
        space_id = instance.space;
        space = await UUFlowManager.getSpace(space_id);
        space_user = await UUFlowManager.getSpaceUser(space_id, current_user);
        flow = await db.flows.findOne({
        _id: instance.flow
        });
        spaceUserOrganizations = await db.organizations.find({
        _id: {
            $in: space_user.organizations
        }
        }).toArray();
        if ((instance.submitter !== current_user) && (!space.admins.includes(current_user)) && !WorkflowManager.canAdmin(flow, space_user, spaceUserOrganizations)) {
        throw new Error("您不能删除此申请单。");
        }
        delete_obj = await db.instances.findOne({_id: data._id});
        delete_obj.deleted = new Date;
        delete_obj.deleted_by = current_user;
        await db.deleted_instances.insert(delete_obj);
        await db.instances.remove({_id: data._id});
        // 删除instance_tasks
        await remove_instance_tasks_by_instance_id(data._id)
        if (delete_obj.state !== "draft") {
            inbox_users = delete_obj.inbox_users ? delete_obj.inbox_users : [];
            cc_users = delete_obj.cc_users ? delete_obj.cc_users : [];
            user_ids = _.uniq(inbox_users.concat(cc_users));
            _.each(user_ids, function(u_id) {
                return pushManager.send_message_to_specifyUser("terminate_approval", u_id);
            });
            pushManager.send_instance_notification("monitor_delete_applicant", delete_obj, "", Object.assign({}, userSession, {_id: userSession.userId}));
        }
        
        res.status(200).send({
            status: 0,
            msg: '',
            data: {}
        });
    } catch (error) {
        console.error(error);
        res.status(200).send({
            error: error.message
        });
    }
});
exports.default = router;