"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendByMaterial = exports.inventoryApprovalMaterial = void 0;
var tslib_1 = require("tslib");
var axios_1 = require("axios");
var lodash_1 = require("lodash");
var const_1 = require("../const");
var _ = require("lodash");
var dayjs = require('dayjs');
var workspaceId = process.env.PEPSICO_CONTENT_HUB_WORKSPACE_ID;
var appId = process.env.PEPSICO_CONTENT_HUB_APP_ID;
var appSecret = process.env.PEPSICO_CONTENT_HUB_APP_SECRET;
var baseUrl = process.env.PEPSICO_CONTENT_HUB_BASE_URL;
var getToken = function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var result;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, axios_1.default.post("".concat(baseUrl, "/creativeSaas/auth/v1/tenantAccessToken/internal"), {
                    appId: appId,
                    appSecret: appSecret
                })];
            case 1:
                result = _a.sent();
                return [2, result.data.data.tenantAccessToken];
        }
    });
}); };
var getTagValIdList = function (list) {
    var idList = list.map(function (item) {
        var parts = item.split('-');
        return (0, lodash_1.last)(parts);
    }).filter(function (child) { return child !== null; });
    return (0, lodash_1.compact)(idList);
};
var getTagList = function (approvalNew) {
    var tagList = [];
    tagList.push({
        "tagId": '2233305195300844',
        "tagValIdList": getTagValIdList((0, lodash_1.concat)([], approvalNew.product || []))
    });
    tagList.push({
        "tagId": '2233305195301571',
        "tagValIdList": getTagValIdList((0, lodash_1.concat)([], approvalNew.available_channels || []))
    });
    tagList.push({
        "tagId": '2233305195300858',
        "tagValIdList": getTagValIdList((0, lodash_1.concat)([], approvalNew.material_type || []))
    });
    tagList.push({
        "tagId": '2233305205340708',
        "tagValIdList": getTagValIdList((0, lodash_1.concat)([], approvalNew.content_rule || []))
    });
    tagList.push({
        "tagId": '2233305195301693',
        "value": approvalNew.expiry_date ? dayjs(approvalNew.expiry_date).format('YYYY-MM-DD') : ""
    });
    tagList.push({
        "tagId": '22334050712762302',
        "value": approvalNew.effective_date ? dayjs(approvalNew.effective_date).format('YYYY-MM-DD') : ""
    });
    return tagList;
};
var inventoryApprovalMaterial = function (ctx, approvalId, materialId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var materialList, approvalNew, owner, tagList, materialGroupIdList, mFilters, materials, materials_1, materials_1_1, material, allow, files, files_1, files_1_1, file, allow_1, e_1_1, token, result, data, error_1;
    var e_1, _a, e_2, _b;
    var _c, _d;
    return tslib_1.__generator(this, function (_e) {
        switch (_e.label) {
            case 0:
                materialList = [];
                _e.label = 1;
            case 1:
                _e.trys.push([1, 15, , 17]);
                return [4, ctx.getObject('pepsico_material_approval').findOne(approvalId)];
            case 2:
                approvalNew = _e.sent();
                if (!approvalNew) {
                    throw new Error('无效的approvalId:' + approvalId);
                }
                if (approvalNew.is_skip_approver && !_.includes(const_1.DCO_TYPES, approvalNew.classification)) {
                    return [2, {
                            msg: '不需要推送到Content Hub'
                        }];
                }
                if (approvalNew.ch_upload === 'no') {
                    return [2, {
                            msg: '不需要推送到Content Hub'
                        }];
                }
                owner = process.env.PEPSICO_CONTENT_HUB_TEST_OWNER || approvalNew.material_owner;
                tagList = getTagList(approvalNew);
                materialGroupIdList = [];
                mFilters = [['pepsico_material_approval', '=', approvalId], ['void_material', '!=', true]];
                if (materialId) {
                    mFilters.push(['_id', '=', materialId]);
                }
                return [4, ctx.getObject("pepsico_material").find({
                        filters: mFilters
                    })];
            case 3:
                materials = _e.sent();
                _e.label = 4;
            case 4:
                _e.trys.push([4, 9, 10, 11]);
                materials_1 = tslib_1.__values(materials), materials_1_1 = materials_1.next();
                _e.label = 5;
            case 5:
                if (!!materials_1_1.done) return [3, 8];
                material = materials_1_1.value;
                allow = true;
                if (allow) {
                    materialList.push({
                        workspaceId: +workspaceId,
                        name: material.name,
                        owner: owner,
                        url: "".concat(process.env.ROOT_URL, "/api/v6/files/cfs.files.filerecord/").concat(material.material, "/").concat(material.name),
                        materialGroupIdList: materialGroupIdList,
                        tagList: tagList
                    });
                }
                if (!(material.supplement_materials && (0, lodash_1.isEmpty)(material.supplement_materials) === false && (0, lodash_1.isArray)(material.supplement_materials))) return [3, 7];
                return [4, ctx.getObject("cfs_files_filerecord").find({
                        filters: ['_id', 'in', material.supplement_materials]
                    })];
            case 6:
                files = _e.sent();
                try {
                    for (files_1 = (e_2 = void 0, tslib_1.__values(files)), files_1_1 = files_1.next(); !files_1_1.done; files_1_1 = files_1.next()) {
                        file = files_1_1.value;
                        try {
                            allow_1 = true;
                            if (allow_1) {
                                materialList.push({
                                    workspaceId: +workspaceId,
                                    name: file.original.name,
                                    owner: owner,
                                    url: "".concat(process.env.ROOT_URL, "/api/v6/files/cfs.files.filerecord/").concat(file._id, "/").concat(file.original.name),
                                    materialGroupIdList: materialGroupIdList,
                                    tagList: tagList
                                });
                            }
                        }
                        catch (error) {
                            console.log(error);
                        }
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (files_1_1 && !files_1_1.done && (_b = files_1.return)) _b.call(files_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                _e.label = 7;
            case 7:
                materials_1_1 = materials_1.next();
                return [3, 5];
            case 8: return [3, 11];
            case 9:
                e_1_1 = _e.sent();
                e_1 = { error: e_1_1 };
                return [3, 11];
            case 10:
                try {
                    if (materials_1_1 && !materials_1_1.done && (_a = materials_1.return)) _a.call(materials_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7];
            case 11: return [4, getToken()];
            case 12:
                token = _e.sent();
                return [4, axios_1.default.post("".concat(baseUrl, "/creativeSaas/v1/material/inbound_url"), {
                        requestId: approvalId,
                        materialList: materialList
                    }, {
                        headers: {
                            "tenant-access-token": token
                        }
                    })];
            case 13:
                result = _e.sent();
                data = result.data;
                return [4, ((_c = ctx.logger) === null || _c === void 0 ? void 0 : _c.info("[\u8C03\u7528 content hub API]-".concat(approvalId), {
                        result: data,
                        materialList: materialList
                    }))];
            case 14:
                _e.sent();
                return [2, data];
            case 15:
                error_1 = _e.sent();
                return [4, ((_d = ctx.logger) === null || _d === void 0 ? void 0 : _d.error("[\u8C03\u7528 content hub API]-".concat(approvalId), {
                        error: error_1.message,
                        materialList: materialList
                    }))];
            case 16:
                _e.sent();
                return [2, error_1.message];
            case 17: return [2];
        }
    });
}); };
exports.inventoryApprovalMaterial = inventoryApprovalMaterial;
var sendByMaterial = function (ctx, materialId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var material;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_material').findOne(materialId)];
            case 1:
                material = _a.sent();
                return [4, (0, exports.inventoryApprovalMaterial)(ctx, material.pepsico_material_approval, materialId)];
            case 2: return [2, _a.sent()];
        }
    });
}); };
exports.sendByMaterial = sendByMaterial;
//# sourceMappingURL=content_hub.js.map