"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.migrateReviewCompletedDate = void 0;
var tslib_1 = require("tslib");
var objectql = require("@steedos/objectql");
function getCollection(name) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var adapter;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    adapter = objectql.getDataSource('default').adapter;
                    return [4, adapter.connect()];
                case 1:
                    _a.sent();
                    return [2, adapter.collection(name)];
            }
        });
    });
}
exports.migrateReviewCompletedDate = {
    rest: {
        method: 'GET',
        fullPath: '/api/pepsico-content/migrate-review-completed-date'
    },
    handler: function (ctx) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, logger, approvalCol, processCol, materialCol, approvals, approvalUpdated, materialUpdatedTotal, skippedIds, approvals_1, approvals_1_1, approval, process_1, materialResult, e_1_1, summary, error_1;
            var e_1, _b;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        user = ctx.meta.user;
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _c.sent();
                        ctx.logger = logger;
                        if (!user || !user.is_space_admin) {
                            return [2, {
                                    status: 403,
                                    msg: "只有管理员可以执行数据迁移",
                                    data: {}
                                }];
                        }
                        _c.label = 2;
                    case 2:
                        _c.trys.push([2, 20, , 21]);
                        return [4, getCollection('pepsico_material_approval')];
                    case 3:
                        approvalCol = _c.sent();
                        return [4, getCollection('pepsico_approval_process')];
                    case 4:
                        processCol = _c.sent();
                        return [4, getCollection('pepsico_material')];
                    case 5:
                        materialCol = _c.sent();
                        return [4, approvalCol.find({
                                current_step: { $in: ['awaiting_deployment', 'conclusion'] },
                                $or: [
                                    { review_completed_date: { $exists: false } },
                                    { review_completed_date: null }
                                ]
                            }, { projection: { _id: 1 } }).toArray()];
                    case 6:
                        approvals = _c.sent();
                        logger === null || logger === void 0 ? void 0 : logger.info("[migrateReviewCompletedDate] \u5F85\u66F4\u65B0\u5BA1\u6279\u5355\u6570: ".concat(approvals.length));
                        approvalUpdated = 0;
                        materialUpdatedTotal = 0;
                        skippedIds = [];
                        _c.label = 7;
                    case 7:
                        _c.trys.push([7, 17, 18, 19]);
                        approvals_1 = tslib_1.__values(approvals), approvals_1_1 = approvals_1.next();
                        _c.label = 8;
                    case 8:
                        if (!!approvals_1_1.done) return [3, 16];
                        approval = approvals_1_1.value;
                        return [4, processCol.findOne({
                                pepsico_material_approval: approval._id,
                                current_step: 'awaiting_deployment'
                            }, { projection: { created: 1 } })];
                    case 9:
                        process_1 = _c.sent();
                        if (!(!process_1 || !process_1.created)) return [3, 11];
                        return [4, processCol.findOne({
                                pepsico_material_approval: approval._id,
                                current_step: 'conclusion'
                            }, { projection: { created: 1 } })];
                    case 10:
                        process_1 = _c.sent();
                        _c.label = 11;
                    case 11:
                        if (!(process_1 && process_1.created)) return [3, 14];
                        return [4, approvalCol.updateOne({ _id: approval._id }, { $set: { review_completed_date: process_1.created } })];
                    case 12:
                        _c.sent();
                        return [4, materialCol.updateMany({ pepsico_material_approval: approval._id }, { $set: { review_completed_date: process_1.created } })];
                    case 13:
                        materialResult = _c.sent();
                        materialUpdatedTotal += (materialResult.matchedCount || ((_a = materialResult.result) === null || _a === void 0 ? void 0 : _a.n) || 0);
                        approvalUpdated++;
                        return [3, 15];
                    case 14:
                        skippedIds.push(approval._id);
                        _c.label = 15;
                    case 15:
                        approvals_1_1 = approvals_1.next();
                        return [3, 8];
                    case 16: return [3, 19];
                    case 17:
                        e_1_1 = _c.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 19];
                    case 18:
                        try {
                            if (approvals_1_1 && !approvals_1_1.done && (_b = approvals_1.return)) _b.call(approvals_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 19:
                        summary = {
                            approvalTotal: approvals.length,
                            approvalUpdated: approvalUpdated,
                            approvalSkipped: skippedIds.length,
                            skippedIds: skippedIds,
                            materialUpdated: materialUpdatedTotal
                        };
                        logger === null || logger === void 0 ? void 0 : logger.info("[migrateReviewCompletedDate] \u8FC1\u79FB\u5B8C\u6210", summary);
                        return [2, {
                                status: 0,
                                msg: "迁移完成",
                                data: summary
                            }];
                    case 20:
                        error_1 = _c.sent();
                        logger === null || logger === void 0 ? void 0 : logger.error("[migrateReviewCompletedDate] \u8FC1\u79FB\u5931\u8D25", error_1);
                        return [2, {
                                status: 500,
                                msg: "\u8FC1\u79FB\u5931\u8D25: ".concat(error_1.message),
                                data: {}
                            }];
                    case 21: return [2];
                }
            });
        });
    }
};
//# sourceMappingURL=migrateReviewCompletedDate.js.map