/*
 * @Author: 殷亮辉 yinlianghui@hotoa.com
 * @Date: 2025-10-09 10:12:49
 * @LastEditors: 殷亮辉 yinlianghui@hotoa.com
 * @LastEditTime: 2025-10-29 09:38:43
 */
const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const objectql = require('@steedos/objectql')
// const { cc_do } = require('../methods/trace_approve_cc');
const { getCollection } = require('../utils/collection');
const { set_approve_have_read } = require('../methods/instance_approve');
const { cc_read } = require('../methods/trace_approve_cc');
// const InstanceManager = global.InstanceManager;
const InstanceManager = require('../manager/instance_manager');

router.post('/api/workflow/v2/set_have_read', requireAuthentication, async function (req, res) {
    try {
        let userSession = req.user;
        if (!userSession) {
            return res.status(200).send({
                error: "unauthorized"
            });
        }
        const userId = userSession.userId;
        const { instanceTaskId, isRead } = req.body;
        if (isRead){
            return res.status(200).send({
                success: true
            });
        }


        const db = {
            instances: await getCollection('instances'),
            instance_tasks: await getCollection('instance_tasks')
        };
        const instance_task = await db.instance_tasks.findOne({
            _id: instanceTaskId
        }, {
            fields: {
                "instance": 1,
                "is_read": 1,
                "type": 1,
                space: 1
            }
        });
        if(!instance_task){
            return res.status(200).send({
                success: true
            });
        }


        // 更新当前用户相关的通知为已读
        const notificationsObj = objectql.getObject('notifications');
        await notificationsObj.directUpdateMany([
            ['owner', '=', userId],
            ['is_read', '!=', true],
            ['related_to.o', '=', 'instances'],
            ['related_to.ids', '=', instance_task.instance]
        ], {
            is_read: true
        });
        console.log(`b6-microservice.broadcast`, {name: '$notification.users', data: {tenantId: instance_task.space, users: [userId], message: null}});
        await broker.call('b6-microservice.broadcast', {name: '$notification.users', data: {tenantId: instance_task.space, users: [userId], message: null}})

        if (instance_task.is_read){
            return res.status(200).send({
                success: true
            });
        }

        const instanceId = instance_task.instance;
        const ins = await db.instances.findOne({_id: instanceId});
        var myApprove = InstanceManager.getCurrentApprove(ins, userId, instance_task.type);
        if (instance_task.type == "cc") {
            // 传阅
            await cc_read(ins, myApprove, { userId });
        }
        else{
            await set_approve_have_read(ins._id, myApprove.trace, myApprove._id, { userId });
        }        
        return res.status(200).send({
            success: true
        });

    } catch (error) {
        console.error(error);
        return res.status(200).send({
            error: error.message
        });
    }
});
exports.default = router;