"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadDocFromOneDriveDoc = exports.downloadBulkFromOneDriveDoc = exports.deleteDocOneDriveShareLink = exports.deleteBulkDocOneDriveShareLink = exports.uploadBulkDocToOneDrive = exports.getOneDriveMaterials = exports.getPendingUploadsToOneDriveMaterials = exports.uploadDocToOneDrive = exports.getUserReviewedAllMaterialsStatus = exports.getApproverFieldByType = exports.getApproverField = exports.submitMaterial = exports.addBulkMaterials = exports.hasDuplicateMaterials = void 0;
var tslib_1 = require("tslib");
var consts_1 = require("./consts");
var _ = require("lodash");
var mime_types_1 = require("mime-types");
var const_1 = require("../const");
var hasDuplicateMaterials = function (ctx, approvalId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var materials, md5s, md5Files;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject("pepsico_material").directFind({
                    filters: [['pepsico_material_approval', '=', approvalId], ['void_material', '!=', true]],
                    fields: ['_id', 'material', 'md5']
                })];
            case 1:
                materials = _a.sent();
                md5s = _.compact(_.map(materials, 'md5'));
                if (md5s.length !== _.uniq(md5s).length) {
                    return [2, true];
                }
                return [4, ctx.getObject("pepsico_material").directFind({
                        filters: ['md5', '=', md5s],
                        fields: ['_id']
                    })];
            case 2:
                md5Files = _a.sent();
                return [2, md5s.length < md5Files.length];
        }
    });
}); };
exports.hasDuplicateMaterials = hasDuplicateMaterials;
var addBulkMaterials = function (ctx, approvalId, fileIds) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var user, approval, materialsQuantity, quantityLimit, sizeLimit, pepsico_material, allFileIds, result, totalUsed, files, files_1, files_1_1, file, e_1_1;
    var e_1, _a;
    var _b;
    return tslib_1.__generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                user = ctx.meta.user;
                return [4, ctx.getObject('pepsico_material_approval').findOne(approvalId)];
            case 1:
                approval = _c.sent();
                if (user.userId != approval.owner) {
                    throw new Error('只有创建者才能添加素材');
                }
                materialsQuantity = approval.materials_quantity || 0;
                quantityLimit = _.includes(const_1.DCO_TYPES, approval.classification) ? 300 : 50;
                if (materialsQuantity >= quantityLimit) {
                    throw new Error("\u7D20\u6750\u6570\u91CF\uFF1A\u6700\u591A".concat(quantityLimit, "\u4E2A"));
                }
                if (materialsQuantity + fileIds.length > quantityLimit) {
                    throw new Error("\u7D20\u6750\u6570\u91CF\uFF1A\u6700\u591A".concat(quantityLimit, "\u4E2A. \u60A8\u672C\u6B21\u6DFB\u52A0\u4E86").concat(fileIds.length, "\u4E2A\u7D20\u6750"));
                }
                sizeLimit = _.includes(const_1.DCO_TYPES, approval.classification) ? 10 * 1024 * 1024 * 1024 : 1 * 1024 * 1024 * 1024;
                return [4, ctx.getObject('pepsico_material').find({ filters: ['pepsico_material_approval', '=', approval._id], fields: ['material'] })];
            case 2:
                pepsico_material = _c.sent();
                allFileIds = _.concat(fileIds, _.map(pepsico_material, 'material'));
                return [4, ctx.getObject("cfs_files_filerecord").aggregate({}, [
                        {
                            $match: {
                                _id: { $in: allFileIds }
                            }
                        },
                        {
                            $group: {
                                _id: null,
                                totalSize: { $sum: "$copies.files.size" }
                            }
                        }
                    ])];
            case 3:
                result = _c.sent();
                totalUsed = ((_b = result[0]) === null || _b === void 0 ? void 0 : _b.totalSize) || 0;
                if (totalUsed > sizeLimit) {
                    throw new Error("附件总大小超过 10GB，禁止添加素材");
                }
                return [4, ctx.getObject("cfs_files_filerecord").find({
                        filters: ['_id', '=', fileIds]
                    })];
            case 4:
                files = _c.sent();
                if (!(approval.current_step == consts_1.Step.draft || approval.current_step == consts_1.Step.submitter_revisions)) return [3, 12];
                _c.label = 5;
            case 5:
                _c.trys.push([5, 10, 11, 12]);
                files_1 = tslib_1.__values(files), files_1_1 = files_1.next();
                _c.label = 6;
            case 6:
                if (!!files_1_1.done) return [3, 9];
                file = files_1_1.value;
                return [4, ctx.getObject('pepsico_material').insert({
                        pepsico_material_approval: approval._id,
                        product: _.first(_.split(approval.product, '-')),
                        shop_tag: approval.shop_tag,
                        material: file._id,
                        material_original: file._id,
                        md5: file.original.md5,
                        name: file.original.name,
                        classification: approval.classification,
                        extension_type: (0, mime_types_1.extension)(file.original.type),
                        material_type: approval.material_type,
                        social_media: approval.social_media,
                        followers: approval.followers,
                        kol_classification: approval.kol_classification,
                        owner_department: approval.owner_department,
                        brief_flow: approval.brief_flow,
                        owner: approval.owner,
                        space: approval.space,
                        created: new Date(),
                        created_by: user.userId,
                        modified: new Date(),
                        modified_by: user.userId
                    })];
            case 7:
                _c.sent();
                _c.label = 8;
            case 8:
                files_1_1 = files_1.next();
                return [3, 6];
            case 9: return [3, 12];
            case 10:
                e_1_1 = _c.sent();
                e_1 = { error: e_1_1 };
                return [3, 12];
            case 11:
                try {
                    if (files_1_1 && !files_1_1.done && (_a = files_1.return)) _a.call(files_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7];
            case 12: return [2, {}];
        }
    });
}); };
exports.addBulkMaterials = addBulkMaterials;
var submitMaterial = function (ctx, materialId, approvalStatus) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var _a;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    console.log("submitMaterial:", materialId, approvalStatus);
                    _a = approvalStatus;
                    switch (_a) {
                        case consts_1.ApprovalStatus.approved: return [3, 1];
                        case consts_1.ApprovalStatus.rejected: return [3, 3];
                    }
                    return [3, 5];
                case 1: return [4, approveMaterial.call(this, ctx, materialId)];
                case 2: return [2, _b.sent()];
                case 3: return [4, rejectMaterial.call(this, ctx, materialId)];
                case 4: return [2, _b.sent()];
                case 5: return [2, {}];
            }
        });
    });
};
exports.submitMaterial = submitMaterial;
var getApproverField = function (ctx, approval, material, userId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var fieldName, process, process_1;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                fieldName = '';
                console.log("[getApproverField]", JSON.stringify({
                    userId: userId,
                    ca_reviewer: approval.ca_reviewer,
                    sra_reviewer: approval.sra_reviewer,
                    ns_reviewer: approval.ns_reviewer,
                    legal_reviewer: approval.legal_reviewer,
                    reviewer: approval.reviewer
                }));
                if (approval.current_step == consts_1.Step.departmental_review) {
                    if (_.includes(approval.ca_reviewer, userId) || _.includes(approval.handler_ca, userId)) {
                        fieldName = 'ca_approval_status';
                    }
                    else if (_.includes(approval.sra_reviewer, userId) || _.includes(approval.handler_sra, userId)) {
                        fieldName = 'sra_approval_status';
                    }
                    else if (_.includes(approval.ns_reviewer, userId) || _.includes(approval.handler_ns, userId)) {
                        fieldName = 'ns_approval_status';
                    }
                    else if (_.includes(approval.legal_reviewer, userId) || _.includes(approval.handler_legal, userId)) {
                        fieldName = 'legal_approval_status';
                    }
                }
                if (approval.current_step == consts_1.Step.personnel_review) {
                    if ((_.includes(approval.reviewer, userId) || _.includes(approval.handler_guding, userId)) && material.approval_status != true) {
                        fieldName = 'approval_status';
                    }
                }
                return [4, ctx.getObject("pepsico_approval_process").find({
                        filters: [
                            ["owner", "=", userId],
                            ["pepsico_material_approval", "=", approval._id],
                            ["current_step", "=", approval.current_step],
                            ["space", "=", approval.space],
                            ["approved", "=", 'progess']
                        ],
                        top: 1,
                        sort: "modified asc"
                    })];
            case 1:
                process = _a.sent();
                if (process.length > 0 && process[0].type === 'Kids') {
                    fieldName = 'kids_approval_status';
                }
                if (approval.child_files == 'yes') {
                    if ((approval.kids_approval_status !== true && approval.kids_approval_status !== false) && (_.includes(approval.kids_reviewer, userId) || _.includes(approval.handler_kids, userId))) {
                        fieldName = 'kids_approval_status';
                    }
                }
                if (!!fieldName) return [3, 3];
                return [4, ctx.getObject("pepsico_approval_process").find({
                        filters: [
                            ["owner", "=", userId],
                            ["pepsico_material_approval", "=", approval._id],
                            ["current_step", "=", approval.current_step],
                            ["space", "=", approval.space],
                            ["approved", "=", 'progess']
                        ],
                        top: 1,
                        sort: "modified desc"
                    })];
            case 2:
                process_1 = _a.sent();
                if (process_1 && process_1.length > 0) {
                    fieldName = (0, exports.getApproverFieldByType)(process_1[0].type);
                }
                _a.label = 3;
            case 3:
                console.log('[getApproverField] fieldName:', fieldName);
                return [2, fieldName];
        }
    });
}); };
exports.getApproverField = getApproverField;
var getApproverFieldByType = function (type) {
    var fieldName = '';
    switch (type) {
        case consts_1.ProcessApprovalType.CA:
            fieldName = 'ca_approval_status';
            break;
        case consts_1.ProcessApprovalType.Legal:
            fieldName = 'legal_approval_status';
            break;
        case consts_1.ProcessApprovalType.NS:
            fieldName = 'ns_approval_status';
            break;
        case consts_1.ProcessApprovalType.SRA:
            fieldName = 'sra_approval_status';
            break;
        case consts_1.ProcessApprovalType.Kids:
            fieldName = 'kids_approval_status';
            break;
        case consts_1.ProcessApprovalType.guding:
            fieldName = 'approval_status';
            break;
        default:
            break;
    }
    return fieldName;
};
exports.getApproverFieldByType = getApproverFieldByType;
var approveMaterial = function (ctx, materialId) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, material, approval, approveField, materialStatus;
        var _a;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material').findOne(materialId)];
                case 1:
                    material = _b.sent();
                    return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                case 2:
                    approval = _b.sent();
                    return [4, (0, exports.getApproverField)(ctx, approval, material, user.userId)];
                case 3:
                    approveField = _b.sent();
                    if (!approveField) {
                        return [2];
                    }
                    return [4, ctx.getObject('pepsico_material').update(materialId, (_a = {},
                            _a[approveField] = true,
                            _a))];
                case 4:
                    _b.sent();
                    if (approveField && approveField === 'kids_approval_status') {
                        return [2, {}];
                    }
                    console.log('[approveMaterial] approveField', approveField);
                    return [4, (0, exports.getUserReviewedAllMaterialsStatus)(ctx, approval._id, approveField)];
                case 5:
                    materialStatus = _b.sent();
                    console.log('[approveMaterial] materialStatus', materialStatus);
                    if (!(materialStatus != consts_1.ApprovalStatus.pending)) return [3, 9];
                    if (!(materialStatus == consts_1.ApprovalStatus.approved)) return [3, 7];
                    return [4, this.approvalContent(ctx, approval._id, { approveField: approveField, materialStatus: materialStatus })];
                case 6:
                    _b.sent();
                    return [3, 9];
                case 7:
                    if (!(materialStatus == consts_1.ApprovalStatus.rejected)) return [3, 9];
                    return [4, this.rejectContent(ctx, approval._id, { approveField: approveField, materialStatus: materialStatus })];
                case 8:
                    _b.sent();
                    _b.label = 9;
                case 9: return [2];
            }
        });
    });
};
var rejectMaterial = function (ctx, materialId) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, material, approval, approveField, materialStatus;
        var _a;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material').findOne(materialId)];
                case 1:
                    material = _b.sent();
                    return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                case 2:
                    approval = _b.sent();
                    return [4, (0, exports.getApproverField)(ctx, approval, material, user.userId)];
                case 3:
                    approveField = _b.sent();
                    if (!approveField) {
                        return [2];
                    }
                    return [4, ctx.getObject('pepsico_material').update(materialId, (_a = {},
                            _a[approveField] = false,
                            _a))];
                case 4:
                    _b.sent();
                    return [4, (0, exports.getUserReviewedAllMaterialsStatus)(ctx, approval._id, approveField)];
                case 5:
                    materialStatus = _b.sent();
                    if (!(materialStatus != consts_1.ApprovalStatus.pending)) return [3, 7];
                    return [4, this.rejectContent(ctx, approval._id, { approveField: approveField, materialStatus: materialStatus })];
                case 6:
                    _b.sent();
                    _b.label = 7;
                case 7: return [2];
            }
        });
    });
};
var getUserReviewedAllMaterialsStatus = function (ctx, approvalId, approveField) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var records, pendingRecords, hasPending, hasFalse;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_material').find({
                    filters: [
                        ['pepsico_material_approval', '=', approvalId],
                        ['void_material', '!=', true]
                    ]
                })];
            case 1:
                records = _a.sent();
                pendingRecords = _.filter(records, function (record) {
                    return record[approveField] === null || !_.has(record, approveField) || record[approveField] === '' || record[approveField] === undefined;
                });
                hasPending = pendingRecords.length > 0;
                console.log('getUserReviewedAllMaterialsStatus:', approvalId, "\u672A\u4F5C\u5E9F\u7684\u7D20\u6750\u6570\u91CF\u4E3A:", records.length, 'hasPending:', hasPending, approveField, pendingRecords);
                if (hasPending) {
                    return [2, consts_1.ApprovalStatus.pending];
                }
                hasFalse = _.filter(records, function (record) {
                    return record[approveField] === false;
                }).length > 0;
                if (hasFalse) {
                    return [2, consts_1.ApprovalStatus.rejected];
                }
                return [2, consts_1.ApprovalStatus.approved];
        }
    });
}); };
exports.getUserReviewedAllMaterialsStatus = getUserReviewedAllMaterialsStatus;
var uploadDocToOneDrive = function (ctx, material) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var _a, fileInfo, viewSharedLink, editSharedLink, error_1;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _b.trys.push([0, 4, , 7]);
                return [4, ctx.broker.call('content-version-bridge.material_uploadDocToOneDrive', { material: material })];
            case 1:
                _a = _b.sent(), fileInfo = _a.item, viewSharedLink = _a.viewSharedLink, editSharedLink = _a.editSharedLink;
                return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                        uploaded_to_onedrive: true,
                        onedrive_item: fileInfo,
                        onedrive_shared_link_view: viewSharedLink,
                        onedrive_shared_link_edit: editSharedLink
                    })];
            case 2:
                _b.sent();
                return [4, ctx.logger.info("".concat(material.pepsico_material_approval, "-").concat(material._id, "-[\u7D20\u6750\u4E0A\u4F20\u5230oneDrive\u6210\u529F]"), { objectName: 'pepsico_material', _id: material._id, pepsico_material_approval: material.pepsico_material_approval, fileInfo: fileInfo, viewSharedLink: viewSharedLink, editSharedLink: editSharedLink })];
            case 3:
                _b.sent();
                return [2, true];
            case 4:
                error_1 = _b.sent();
                return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                        uploaded_to_onedrive: false
                    })];
            case 5:
                _b.sent();
                return [4, ctx.logger.error("".concat(material.pepsico_material_approval, "-").concat(material._id, "-[\u7D20\u6750\u4E0A\u4F20\u5230oneDrive\u5931\u8D25]:").concat(error_1.message), { objectName: 'pepsico_material', _id: material._id, pepsico_material_approval: material.pepsico_material_approval })];
            case 6:
                _b.sent();
                console.log('uploadDocToOneDrive error:', error_1);
                return [2, false];
            case 7: return [2];
        }
    });
}); };
exports.uploadDocToOneDrive = uploadDocToOneDrive;
var getPendingUploadsToOneDriveMaterials = function (ctx, approvalId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var materials;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject("pepsico_material").find({
                    filters: [['pepsico_material_approval', '=', approvalId], ['extension_type', 'in', ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']], ['void_material', '!=', true], ['uploaded_to_onedrive', '!=', true]]
                })];
            case 1:
                materials = _a.sent();
                return [2, materials];
        }
    });
}); };
exports.getPendingUploadsToOneDriveMaterials = getPendingUploadsToOneDriveMaterials;
var getOneDriveMaterials = function (ctx, approvalId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var materials;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject("pepsico_material").find({
                    filters: [['pepsico_material_approval', '=', approvalId], ['extension_type', 'in', ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']], ['void_material', '!=', true]]
                })];
            case 1:
                materials = _a.sent();
                return [2, materials];
        }
    });
}); };
exports.getOneDriveMaterials = getOneDriveMaterials;
var uploadBulkDocToOneDrive = function (ctx, approvalId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var materials, allTrue, materials_1, materials_1_1, material, success, e_2_1;
    var e_2, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4, (0, exports.getPendingUploadsToOneDriveMaterials)(ctx, approvalId)];
            case 1:
                materials = _b.sent();
                allTrue = true;
                _b.label = 2;
            case 2:
                _b.trys.push([2, 7, 8, 9]);
                materials_1 = tslib_1.__values(materials), materials_1_1 = materials_1.next();
                _b.label = 3;
            case 3:
                if (!!materials_1_1.done) return [3, 6];
                material = materials_1_1.value;
                return [4, (0, exports.uploadDocToOneDrive)(ctx, material)];
            case 4:
                success = _b.sent();
                if (success === false) {
                    allTrue = false;
                }
                _b.label = 5;
            case 5:
                materials_1_1 = materials_1.next();
                return [3, 3];
            case 6: return [3, 9];
            case 7:
                e_2_1 = _b.sent();
                e_2 = { error: e_2_1 };
                return [3, 9];
            case 8:
                try {
                    if (materials_1_1 && !materials_1_1.done && (_a = materials_1.return)) _a.call(materials_1);
                }
                finally { if (e_2) throw e_2.error; }
                return [7];
            case 9:
                if (!(allTrue == true)) return [3, 11];
                return [4, ctx.getObject("pepsico_material_approval").directUpdate(approvalId, {
                        materials_uploaded_to_onedrive_status: 'completed'
                    })];
            case 10:
                _b.sent();
                return [3, 13];
            case 11: return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalId, {
                    materials_uploaded_to_onedrive_status: 'failed',
                    $inc: {
                        materials_uploaded_to_onedrive_failed_count: 1
                    }
                })];
            case 12:
                _b.sent();
                _b.label = 13;
            case 13:
                ;
                return [2, allTrue];
        }
    });
}); };
exports.uploadBulkDocToOneDrive = uploadBulkDocToOneDrive;
var deleteBulkDocOneDriveShareLink = function (ctx, approvalId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var allTrue, materials, materials_2, materials_2_1, material, success, e_3_1;
    var e_3, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                allTrue = true;
                return [4, ctx.getObject("pepsico_material").find({
                        filters: [['pepsico_material_approval', '=', approvalId], ['extension_type', 'in', ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']]]
                    })];
            case 1:
                materials = _b.sent();
                _b.label = 2;
            case 2:
                _b.trys.push([2, 7, 8, 9]);
                materials_2 = tslib_1.__values(materials), materials_2_1 = materials_2.next();
                _b.label = 3;
            case 3:
                if (!!materials_2_1.done) return [3, 6];
                material = materials_2_1.value;
                return [4, (0, exports.deleteDocOneDriveShareLink)(ctx, material)];
            case 4:
                success = _b.sent();
                if (success === false) {
                    allTrue = false;
                }
                _b.label = 5;
            case 5:
                materials_2_1 = materials_2.next();
                return [3, 3];
            case 6: return [3, 9];
            case 7:
                e_3_1 = _b.sent();
                e_3 = { error: e_3_1 };
                return [3, 9];
            case 8:
                try {
                    if (materials_2_1 && !materials_2_1.done && (_a = materials_2.return)) _a.call(materials_2);
                }
                finally { if (e_3) throw e_3.error; }
                return [7];
            case 9:
                if (!(allTrue == true)) return [3, 11];
                return [4, ctx.getObject("pepsico_material_approval").directUpdate(approvalId, {
                        materials_remove_share_link_from_onedrive_status: 'completed'
                    })];
            case 10:
                _b.sent();
                return [3, 13];
            case 11: return [4, ctx.getObject("pepsico_material_approval").directUpdate(approvalId, {
                    materials_remove_share_link_from_onedrive_status: 'failed',
                    $inc: {
                        materials_remove_share_link_from_onedrive_failed_count: 1
                    }
                })];
            case 12:
                _b.sent();
                _b.label = 13;
            case 13:
                ;
                return [2, allTrue];
        }
    });
}); };
exports.deleteBulkDocOneDriveShareLink = deleteBulkDocOneDriveShareLink;
var deleteDocOneDriveShareLink = function (ctx, material) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var error_2;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 4, 7, 9]);
                console.log('deleteDocOneDriveShareLink', material.onedrive_item.id, material._id);
                return [4, ctx.broker.call('content-version-bridge.material_deleteDocOneDriveShareLink', { material: material })];
            case 1:
                _a.sent();
                return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                        remove_share_link_from_onedrive: true
                    })];
            case 2:
                _a.sent();
                return [4, ctx.logger.info("".concat(material.pepsico_material_approval, "-").concat(material._id, "-[\u4ECEoneDrive\u5220\u9664\u5171\u4EAB\u8FDE\u63A5\u6210\u529F]"), { objectName: 'pepsico_material', _id: material._id, pepsico_material_approval: material.pepsico_material_approval })];
            case 3:
                _a.sent();
                return [2, true];
            case 4:
                error_2 = _a.sent();
                return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                        remove_share_link_from_onedrive: false
                    })];
            case 5:
                _a.sent();
                return [4, ctx.logger.error("".concat(material.pepsico_material_approval, "-").concat(material._id, "-[\u4ECEoneDrive\u5220\u9664\u5171\u4EAB\u8FDE\u63A5\u5931\u8D25]:").concat(error_2.message), { objectName: 'pepsico_material', _id: material._id, pepsico_material_approval: material.pepsico_material_approval })];
            case 6:
                _a.sent();
                console.log('deleteDocOneDriveShareLink error:', error_2);
                return [2, false];
            case 7: return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                    onedrive_shared_link_edit: null
                })];
            case 8:
                _a.sent();
                return [7];
            case 9: return [2];
        }
    });
}); };
exports.deleteDocOneDriveShareLink = deleteDocOneDriveShareLink;
var downloadBulkFromOneDriveDoc = function (ctx, approvalId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var materials, allTrue, materials_3, materials_3_1, material, success, e_4_1;
    var e_4, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4, ctx.getObject("pepsico_material").find({
                    filters: [['pepsico_material_approval', '=', approvalId], ['extension_type', 'in', ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']], ['void_material', '!=', true], ['download_from_onedrive', '!=', true]]
                })];
            case 1:
                materials = _b.sent();
                allTrue = true;
                _b.label = 2;
            case 2:
                _b.trys.push([2, 7, 8, 9]);
                materials_3 = tslib_1.__values(materials), materials_3_1 = materials_3.next();
                _b.label = 3;
            case 3:
                if (!!materials_3_1.done) return [3, 6];
                material = materials_3_1.value;
                return [4, (0, exports.downloadDocFromOneDriveDoc)(ctx, material)];
            case 4:
                success = _b.sent();
                if (success === false) {
                    allTrue = false;
                }
                _b.label = 5;
            case 5:
                materials_3_1 = materials_3.next();
                return [3, 3];
            case 6: return [3, 9];
            case 7:
                e_4_1 = _b.sent();
                e_4 = { error: e_4_1 };
                return [3, 9];
            case 8:
                try {
                    if (materials_3_1 && !materials_3_1.done && (_a = materials_3.return)) _a.call(materials_3);
                }
                finally { if (e_4) throw e_4.error; }
                return [7];
            case 9:
                if (!(allTrue == true)) return [3, 11];
                return [4, ctx.getObject("pepsico_material_approval").directUpdate(approvalId, {
                        materials_download_from_onedrive_status: 'completed'
                    })];
            case 10:
                _b.sent();
                return [3, 13];
            case 11: return [4, ctx.getObject("pepsico_material_approval").directUpdate(approvalId, {
                    materials_download_from_onedrive_status: 'failed',
                    $inc: {
                        materials_download_from_onedrive_failed_count: 1
                    }
                })];
            case 12:
                _b.sent();
                _b.label = 13;
            case 13:
                ;
                return [2, allTrue];
        }
    });
}); };
exports.downloadBulkFromOneDriveDoc = downloadBulkFromOneDriveDoc;
var downloadDocFromOneDriveDoc = function (ctx, material) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var st, fileDoc, error_3;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                st = new Date().getTime();
                _a.label = 1;
            case 1:
                _a.trys.push([1, 5, , 8]);
                return [4, ctx.broker.call('content-version-bridge.material_downloadDocFromOneDriveDoc', { material: material })];
            case 2:
                fileDoc = _a.sent();
                console.log("downloadDocFromOneDriveDoc-".concat(material._id), fileDoc._id, fileDoc);
                return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                        material: fileDoc._id,
                        $push: {
                            material_one_drive_history: fileDoc._id
                        },
                        download_from_onedrive: true
                    })];
            case 3:
                _a.sent();
                return [4, ctx.logger.info("".concat(material.pepsico_material_approval, "-").concat(material._id, "-[\u4ECEoneDrive\u4E0B\u8F7D\u7D20\u6750\u6210\u529F]"), { objectName: 'pepsico_material', _id: material._id, pepsico_material_approval: material.pepsico_material_approval, time: (new Date().getTime()) - st })];
            case 4:
                _a.sent();
                return [2, true];
            case 5:
                error_3 = _a.sent();
                return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                        download_from_onedrive: false
                    })];
            case 6:
                _a.sent();
                return [4, ctx.logger.error("".concat(material.pepsico_material_approval, "-").concat(material._id, "-[\u4ECEoneDrive\u4E0B\u8F7D\u7D20\u6750\u5931\u8D25]:").concat(error_3.message), { objectName: 'pepsico_material', _id: material._id, pepsico_material_approval: material.pepsico_material_approval, time: (new Date().getTime()) - st })];
            case 7:
                _a.sent();
                console.log('downloadDocFromOneDriveDoc error:', error_3);
                return [2, false];
            case 8: return [2];
        }
    });
}); };
exports.downloadDocFromOneDriveDoc = downloadDocFromOneDriveDoc;
//# sourceMappingURL=material.js.map