"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.doUrgent = exports.canUrgent = exports.getUrgentQuota = void 0;
var tslib_1 = require("tslib");
var consts_1 = require("./consts");
var HALF_YEAR_QUOTA = 6;
var getUrgentQuota = function (ctx, userId, space) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var now, year, half, quota, h1_used, h2_used, available, used, total, h1_remaining;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                now = new Date();
                year = now.getFullYear();
                half = now.getMonth() < 6 ? 1 : 2;
                return [4, ctx.getObject('pepsico_urgent_quota').findOne({
                        filters: [['user', '=', userId], ['space', '=', space], ['year', '=', year]]
                    })];
            case 1:
                quota = _a.sent();
                if (!quota) {
                    return [2, { available: 0, used: 0, total: 0, year: year, half: half, configured: false }];
                }
                h1_used = (quota === null || quota === void 0 ? void 0 : quota.h1_used) || 0;
                h2_used = (quota === null || quota === void 0 ? void 0 : quota.h2_used) || 0;
                if (half === 1) {
                    used = h1_used;
                    total = HALF_YEAR_QUOTA;
                    available = Math.max(0, HALF_YEAR_QUOTA - h1_used);
                }
                else {
                    h1_remaining = Math.max(0, HALF_YEAR_QUOTA - h1_used);
                    total = HALF_YEAR_QUOTA + h1_remaining;
                    used = h2_used;
                    available = Math.max(0, total - h2_used);
                }
                return [2, { available: available, used: used, total: total, year: year, half: half, configured: true }];
        }
    });
}); };
exports.getUrgentQuota = getUrgentQuota;
var canUrgent = function (ctx, approvalId, userId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var approval, spaceUser, reviewSteps, postponedUsers, quota;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_material_approval').findOne(approvalId)];
            case 1:
                approval = _a.sent();
                if (!approval) {
                    return [2, { canUrgent: false, reason: '审批单不存在' }];
                }
                if (approval.is_urgent) {
                    return [2, { canUrgent: false, reason: '该审批单已处于加急状态' }];
                }
                if (approval.owner !== userId) {
                    return [2, { canUrgent: false, reason: '只有发起人可以加急' }];
                }
                return [4, ctx.getObject('space_users').findOne({
                        filters: [['user', '=', userId], ['space', '=', approval.space]],
                        fields: ['is_collaborator']
                    })];
            case 2:
                spaceUser = _a.sent();
                if ((spaceUser === null || spaceUser === void 0 ? void 0 : spaceUser.is_collaborator) === true) {
                    return [2, { canUrgent: false, reason: '只有内部用户可以加急' }];
                }
                reviewSteps = [consts_1.Step.departmental_review, consts_1.Step.personnel_review];
                if (!reviewSteps.includes(approval.current_step)) {
                    return [2, { canUrgent: false, reason: '当前步骤不支持加急' }];
                }
                postponedUsers = approval.review_postponed_users || [];
                if (postponedUsers.length > 0) {
                    return [2, { canUrgent: false, reason: '存在延后审核人，无法加急' }];
                }
                return [4, (0, exports.getUrgentQuota)(ctx, userId, approval.space)];
            case 3:
                quota = _a.sent();
                if (!quota.configured) {
                    return [2, { canUrgent: false, reason: '未配置加急次数', quota: quota }];
                }
                if (quota.available <= 0) {
                    return [2, { canUrgent: false, reason: '暂无加急次数', quota: quota }];
                }
                return [2, { canUrgent: true, quota: quota }];
        }
    });
}); };
exports.canUrgent = canUrgent;
var sendUrgentNotification = function (ctx, space, approvalId, approvalName, fromUserId, toUserId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var error_1, spaceUsers, spaceUsers_1, spaceUsers_1_1, spaceUser, error_2, e_1_1, error_3;
    var e_1, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _b.trys.push([0, 2, , 3]);
                return [4, ctx.broker.call('notifications.add', {
                        message: {
                            name: "\u52A0\u6025\u5BA1\u6279\uFF1A ".concat(approvalName),
                            body: '发起人已标记为加急审核，请优先处理',
                            related_to: {
                                o: 'pepsico_material_approval',
                                ids: [approvalId]
                            },
                            related_name: approvalName,
                            from: fromUserId,
                            space: space
                        },
                        from: fromUserId,
                        to: toUserId
                    })];
            case 1:
                _b.sent();
                return [3, 3];
            case 2:
                error_1 = _b.sent();
                console.log('[urgent] sendUrgentNotification notification error', error_1);
                return [3, 3];
            case 3:
                _b.trys.push([3, 15, , 16]);
                return [4, ctx.getObject('space_users').find({
                        filters: [['user', '=', toUserId], ['space', '=', space]]
                    })];
            case 4:
                spaceUsers = _b.sent();
                _b.label = 5;
            case 5:
                _b.trys.push([5, 12, 13, 14]);
                spaceUsers_1 = tslib_1.__values(spaceUsers), spaceUsers_1_1 = spaceUsers_1.next();
                _b.label = 6;
            case 6:
                if (!!spaceUsers_1_1.done) return [3, 11];
                spaceUser = spaceUsers_1_1.value;
                if (!spaceUser.email) return [3, 10];
                _b.label = 7;
            case 7:
                _b.trys.push([7, 9, , 10]);
                return [4, ctx.broker.call('@builder6/email.send', {
                        to: spaceUser.email,
                        subject: "[\u52A0\u6025\u5BA1\u6838] ".concat(approvalName),
                        html: "\n                            <p>\u60A8\u6709\u4E00\u4EFD\u5BA1\u6279\u5355\u88AB\u6807\u8BB0\u4E3A<strong>\u52A0\u6025\u5BA1\u6838</strong>\uFF0C\u8BF7\u4F18\u5148\u5904\u7406\u3002</p>\n                            <a href=\"".concat(process.env.ROOT_URL, "/app/pepsico_content_review/pepsico_material_approval/view/").concat(approvalId, "?side_object=pepsico_material_approval&side_listview_id=pending\">").concat(approvalName, "</a>\n                        ")
                    })];
            case 8:
                _b.sent();
                return [3, 10];
            case 9:
                error_2 = _b.sent();
                console.log('[urgent] sendUrgentNotification email error', error_2);
                return [3, 10];
            case 10:
                spaceUsers_1_1 = spaceUsers_1.next();
                return [3, 6];
            case 11: return [3, 14];
            case 12:
                e_1_1 = _b.sent();
                e_1 = { error: e_1_1 };
                return [3, 14];
            case 13:
                try {
                    if (spaceUsers_1_1 && !spaceUsers_1_1.done && (_a = spaceUsers_1.return)) _a.call(spaceUsers_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7];
            case 14: return [3, 16];
            case 15:
                error_3 = _b.sent();
                console.log('[urgent] sendUrgentNotification spaceUsers error', error_3);
                return [3, 16];
            case 16: return [2];
        }
    });
}); };
var doUrgent = function (ctx, approvalId, userId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var check, approval, _a, year, half, used, total, existingQuota, updateField, pendingApprovers, pendingApprovers_1, pendingApprovers_1_1, approverId, e_2_1, newUsed, newAvailable;
    var _b, e_2, _c;
    return tslib_1.__generator(this, function (_d) {
        switch (_d.label) {
            case 0: return [4, (0, exports.canUrgent)(ctx, approvalId, userId)];
            case 1:
                check = _d.sent();
                if (!check.canUrgent) {
                    throw new Error(check.reason);
                }
                return [4, ctx.getObject('pepsico_material_approval').findOne(approvalId)];
            case 2:
                approval = _d.sent();
                _a = check.quota, year = _a.year, half = _a.half, used = _a.used, total = _a.total;
                return [4, ctx.getObject('pepsico_urgent_quota').findOne({
                        filters: [['user', '=', userId], ['space', '=', approval.space], ['year', '=', year]]
                    })];
            case 3:
                existingQuota = _d.sent();
                if (!existingQuota) {
                    throw new Error('未配置加急次数');
                }
                updateField = half === 1 ? 'h1_used' : 'h2_used';
                return [4, ctx.getObject('pepsico_urgent_quota').directUpdate(existingQuota._id, (_b = {},
                        _b[updateField] = (existingQuota[updateField] || 0) + 1,
                        _b))];
            case 4:
                _d.sent();
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalId, {
                        is_urgent: true,
                        urgent_times: (approval.urgent_times || 0) + 1,
                        urgent_at: new Date()
                    })];
            case 5:
                _d.sent();
                return [4, ctx.getObject('pepsico_urgent_log').insert({
                        approval: approvalId,
                        approval_name: approval.name,
                        operator: userId,
                        space: approval.space,
                        year: year,
                        half: half
                    })];
            case 6:
                _d.sent();
                pendingApprovers = Array.isArray(approval.person_pending_approve)
                    ? approval.person_pending_approve
                    : [];
                _d.label = 7;
            case 7:
                _d.trys.push([7, 12, 13, 14]);
                pendingApprovers_1 = tslib_1.__values(pendingApprovers), pendingApprovers_1_1 = pendingApprovers_1.next();
                _d.label = 8;
            case 8:
                if (!!pendingApprovers_1_1.done) return [3, 11];
                approverId = pendingApprovers_1_1.value;
                return [4, sendUrgentNotification(ctx, approval.space, approvalId, approval.name, userId, approverId)];
            case 9:
                _d.sent();
                _d.label = 10;
            case 10:
                pendingApprovers_1_1 = pendingApprovers_1.next();
                return [3, 8];
            case 11: return [3, 14];
            case 12:
                e_2_1 = _d.sent();
                e_2 = { error: e_2_1 };
                return [3, 14];
            case 13:
                try {
                    if (pendingApprovers_1_1 && !pendingApprovers_1_1.done && (_c = pendingApprovers_1.return)) _c.call(pendingApprovers_1);
                }
                finally { if (e_2) throw e_2.error; }
                return [7];
            case 14:
                newUsed = used + 1;
                newAvailable = Math.max(0, total - newUsed);
                return [2, {
                        message: "\u52A0\u6025\u6210\u529F\uFF01\u5DF2\u4F7F\u7528 ".concat(newUsed, " \u6B21\uFF0C\u5269\u4F59 ").concat(newAvailable, " \u6B21"),
                        used: newUsed,
                        available: newAvailable,
                        total: total
                    }];
        }
    });
}); };
exports.doUrgent = doUrgent;
//# sourceMappingURL=urgent.js.map