"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dashboardSyncData = void 0;
var tslib_1 = require("tslib");
var _ = require('lodash');
var moment = require('moment');
var getProductName = function (ctx, productIdStr) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var products, pLists, pRecords_1, pNames_1;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                products = _.split(productIdStr, '-');
                return [4, ctx.getObject('picklists').find({ filters: ["code", "=", "223321001114213"] })];
            case 1:
                pLists = _a.sent();
                if (!(products.length > 0 && pLists.length > 0)) return [3, 3];
                return [4, ctx.getObject('picklist_options').find({
                        filters: [
                            ["picklist", "=", pLists[0]._id],
                            ["value", "=", _.first(products)]
                        ]
                    })];
            case 2:
                pRecords_1 = _a.sent();
                pNames_1 = [];
                _.each(products, function (pId) {
                    var pRecord = _.find(pRecords_1, { value: pId });
                    if (pRecord) {
                        pNames_1.push(pRecord.name);
                    }
                });
                return [2, _.join(pNames_1, '-')];
            case 3: return [2, ''];
        }
    });
}); };
var getSubmitterReview = function (ctx, approverId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var process;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_approval_process').directFind({
                    filters: [['pepsico_material_approval', '=', approverId], ['approved', '!=', 'progess'], ['current_step', '=', 'submitter_revisions']]
                })];
            case 1:
                process = _a.sent();
                return [2, process.length > 0];
        }
    });
}); };
var getCountValue = function (count) {
    if (count == 0) {
        return null;
    }
    else if (count === 1) {
        return 'v1';
    }
    else if (count > 1) {
        return 'v3';
    }
};
var getReviewCount = function (ctx, approverId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var process;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_approval_process').directFind({
                    filters: [['pepsico_material_approval', '=', approverId], ['approved', 'in', ['approved', 'rejected', 'submit']], ['type', 'in', ['NS', 'Legal', 'SRA', 'CA', 'Kids', 'guding']]]
                })];
            case 1:
                process = _a.sent();
                return [2, {
                        NS: getCountValue(_.size(_.filter(process, { type: 'NS' }))),
                        Legal: getCountValue(_.size(_.filter(process, { type: 'Legal' }))),
                        SRA: getCountValue(_.size(_.filter(process, { type: 'SRA' }))),
                        CA: getCountValue(_.size(_.filter(process, { type: 'CA' }))),
                        Kids: getCountValue(_.size(_.filter(process, { type: 'Kids' }))),
                        guding: getCountValue(_.size(_.filter(process, { type: 'guding' })))
                    }];
        }
    });
}); };
var getClassName = function (ctx, classification) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var cLists, classIds, cRecords;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('picklists').find({ filters: ["code", "=", "classification"] })];
            case 1:
                cLists = _a.sent();
                classIds = _.split(classification, '-');
                if (!(classification && cLists.length > 0)) return [3, 3];
                return [4, ctx.getObject('picklist_options').find({
                        filters: [
                            ["picklist", "=", cLists[0]._id],
                            ["value", "=", _.last(classIds)]
                        ]
                    })];
            case 2:
                cRecords = _a.sent();
                return [2, cRecords.length > 0 ? cRecords[0].name : ''];
            case 3: return [2];
        }
    });
}); };
var getFinishDate = function (ctx, approverId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var process, conclusionProcess;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_approval_process').directFind({
                    filters: [['pepsico_material_approval', '=', approverId], ['current_step', '=', 'awaiting_deployment']]
                })];
            case 1:
                process = _a.sent();
                if (!(process.length > 0)) return [3, 2];
                return [2, process[0].created];
            case 2: return [4, ctx.getObject('pepsico_approval_process').directFind({
                    filters: [['pepsico_material_approval', '=', approverId], ['current_step', '=', 'conclusion']]
                })];
            case 3:
                conclusionProcess = _a.sent();
                return [2, conclusionProcess.length > 0 ? conclusionProcess[0].created : null];
        }
    });
}); };
var getMType = function (extension_type) {
    var validImageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'tif', 'svg', 'webp', 'ico', 'heif', 'heic'];
    if (_.includes(validImageTypes, extension_type)) {
        return 'v1';
    }
    if (_.includes(['mp4', 'm4v', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'mpeg', 'mpg', '3gp', 'm4v', 'qt'], extension_type)) {
        return 'v2';
    }
    if (_.includes(['ppt', 'pptx'], extension_type)) {
        return 'v3';
    }
    if (_.includes(['doc', 'docx'], extension_type)) {
        return 'v4';
    }
    return extension_type;
};
var SYNCING = false;
var dashboardSyncData = function (ctx) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var result, filters, approvalRecords, approvalRecords_1, approvalRecords_1_1, approvalRecord, productName, classifyName, ownerDepartment, hasSubmitterReview, reviewCount, finishDate, termination, passCount, record, materialRecords, materialRecords_1, materialRecords_1_1, materialRecord, e_1_1, error_1, e_2_1, error_2;
    var e_2, _a, e_1, _b;
    return tslib_1.__generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                if (SYNCING === true) {
                    throw new Error('同步中, 请勿重复调用...');
                }
                SYNCING = true;
                result = {
                    success: 0,
                    fail: 0
                };
                _c.label = 1;
            case 1:
                _c.trys.push([1, 30, , 32]);
                filters = [
                    ['current_step', 'in', ['conclusion', 'awaiting_deployment']],
                    ['synced', '!=', true],
                    ['is_skip_approver', '!=', true]
                ];
                return [4, ctx.getObject('pepsico_material_approval').directFind({
                        filters: filters
                    })];
            case 2:
                approvalRecords = _c.sent();
                if (!(approvalRecords.length > 0)) return [3, 29];
                _c.label = 3;
            case 3:
                _c.trys.push([3, 27, 28, 29]);
                approvalRecords_1 = tslib_1.__values(approvalRecords), approvalRecords_1_1 = approvalRecords_1.next();
                _c.label = 4;
            case 4:
                if (!!approvalRecords_1_1.done) return [3, 26];
                approvalRecord = approvalRecords_1_1.value;
                _c.label = 5;
            case 5:
                _c.trys.push([5, 23, , 25]);
                return [4, getProductName(ctx, approvalRecord.product)];
            case 6:
                productName = _c.sent();
                return [4, getClassName(ctx, approvalRecord.classification)];
            case 7:
                classifyName = _c.sent();
                return [4, ctx.getObject('organizations').findOne(approvalRecord.owner_department)];
            case 8:
                ownerDepartment = _c.sent();
                return [4, getSubmitterReview(ctx, approvalRecord._id)];
            case 9:
                hasSubmitterReview = _c.sent();
                return [4, getReviewCount(ctx, approvalRecord._id)];
            case 10:
                reviewCount = _c.sent();
                return [4, getFinishDate(ctx, approvalRecord._id)];
            case 11:
                finishDate = _c.sent();
                termination = '';
                if (approvalRecord.termination_type === '发起人中止') {
                    termination = 'v1';
                }
                else if (approvalRecord.termination_type === '审批人中止') {
                    termination = 'v2';
                }
                passCount = hasSubmitterReview ? 'v2' : 'v1';
                if (termination) {
                    passCount = '';
                }
                return [4, ctx.getObject('pepsico_material_approval_data').directInsert({
                        name: approvalRecord.name,
                        pepsico_material_approval: approvalRecord._id,
                        approve_users: approvalRecord.person_approved,
                        current_step: approvalRecord.current_step,
                        material_approve_org: approvalRecord.approval_type == 'personnel_review' ? 'guding' : 'four',
                        peoduct: productName,
                        classify: classifyName,
                        flow_pass_times: passCount,
                        approve_status: approvalRecord.review_status === 'terminated' ? 'v3' : 'v2',
                        termination: termination || null,
                        type: approvalRecord.internal_collaborator ? '外部' : '内部',
                        submit_org: (ownerDepartment === null || ownerDepartment === void 0 ? void 0 : ownerDepartment.name) || null,
                        submit_time: approvalRecord.draft_submitted || null,
                        approve_finish_time: finishDate || null,
                        end_time: approvalRecord.termination_date || null,
                        review_time: finishDate && approvalRecord.draft_submitted ? parseFloat(moment.duration(moment(finishDate).diff(approvalRecord.draft_submitted)).asHours().toFixed(2)) : null,
                        ca_pass: approvalRecord.ca_approval_status || null,
                        ca_approve_times: reviewCount.CA || null,
                        legal_pass: approvalRecord.legal_approval_status || null,
                        approve_org: reviewCount.Legal || null,
                        sra_pass: approvalRecord.sra_approval_status || null,
                        sra_approve_times: reviewCount.SRA || null,
                        ns_pass: approvalRecord.ns_approval_status || null,
                        ns_approve_times: reviewCount.NS || null,
                        guding_pass: approvalRecord.approval_status == 'approved' ? true : (approvalRecord.approval_status || null),
                        guding_approve_times: reviewCount.guding || null,
                        kids: approvalRecord.kids_approval_status || null,
                        kids_approve_times: reviewCount.Kids || null,
                        owner: approvalRecord.owner,
                        space: approvalRecord.space,
                        created: new Date(),
                        modified: new Date(),
                    })];
            case 12:
                record = _c.sent();
                if (!!termination) return [3, 21];
                return [4, ctx.getObject('pepsico_material').directFind({
                        filters: [
                            ['pepsico_material_approval', '=', approvalRecord._id]
                        ]
                    })];
            case 13:
                materialRecords = _c.sent();
                if (!(materialRecords.length > 0)) return [3, 21];
                _c.label = 14;
            case 14:
                _c.trys.push([14, 19, 20, 21]);
                materialRecords_1 = (e_1 = void 0, tslib_1.__values(materialRecords)), materialRecords_1_1 = materialRecords_1.next();
                _c.label = 15;
            case 15:
                if (!!materialRecords_1_1.done) return [3, 18];
                materialRecord = materialRecords_1_1.value;
                return [4, ctx.getObject('pepsico_material_data').directInsert({
                        pepsico_material_approval: approvalRecord._id,
                        approve_users: approvalRecord.person_approved,
                        classify: classifyName,
                        material_void: materialRecord.void_material || false,
                        material_type: getMType(materialRecord.extension_type),
                        brand: productName,
                        submit_org: ownerDepartment === null || ownerDepartment === void 0 ? void 0 : ownerDepartment.name,
                        submit_time: approvalRecord.draft_submitted,
                        name: materialRecord.name,
                        material_approve_org: approvalRecord.approval_type == 'personnel_review' ? 'v2' : 'v1',
                        ns_pass: materialRecord.ns_approval_status || null,
                        legal_pass: materialRecord.legal_approval_status || null,
                        ca_pass: materialRecord.ca_approval_status || null,
                        sra_pass: materialRecord.sra_approval_status || null,
                        guding_pass: materialRecord.approval_status || null,
                        kids_pass: materialRecord.kids_approval_status || null,
                        pepsico_material_approval_data: record._id,
                        pepsico_material: materialRecord._id,
                        owner: approvalRecord.owner,
                        space: approvalRecord.space,
                        created: new Date(),
                        modified: new Date(),
                    })];
            case 16:
                _c.sent();
                _c.label = 17;
            case 17:
                materialRecords_1_1 = materialRecords_1.next();
                return [3, 15];
            case 18: return [3, 21];
            case 19:
                e_1_1 = _c.sent();
                e_1 = { error: e_1_1 };
                return [3, 21];
            case 20:
                try {
                    if (materialRecords_1_1 && !materialRecords_1_1.done && (_b = materialRecords_1.return)) _b.call(materialRecords_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7];
            case 21: return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalRecord._id, {
                    synced: true
                })];
            case 22:
                _c.sent();
                result.success++;
                return [3, 25];
            case 23:
                error_1 = _c.sent();
                return [4, ctx.logger.error("[Dashboard\u540C\u6B65Data]", {
                        pepsico_material_approval: approvalRecord._id,
                        error: error_1.message
                    })];
            case 24:
                _c.sent();
                result.fail++;
                return [3, 25];
            case 25:
                approvalRecords_1_1 = approvalRecords_1.next();
                return [3, 4];
            case 26: return [3, 29];
            case 27:
                e_2_1 = _c.sent();
                e_2 = { error: e_2_1 };
                return [3, 29];
            case 28:
                try {
                    if (approvalRecords_1_1 && !approvalRecords_1_1.done && (_a = approvalRecords_1.return)) _a.call(approvalRecords_1);
                }
                finally { if (e_2) throw e_2.error; }
                return [7];
            case 29:
                SYNCING = false;
                return [2, result];
            case 30:
                error_2 = _c.sent();
                SYNCING = false;
                console.log("[Dashboard\u540C\u6B65Data]", {
                    error: error_2.message
                });
                return [4, ctx.logger.error("[Dashboard\u540C\u6B65Data]", {
                        error: error_2.message
                    })];
            case 31:
                _c.sent();
                return [3, 32];
            case 32: return [2];
        }
    });
}); };
exports.dashboardSyncData = dashboardSyncData;
//# sourceMappingURL=dashboard_sync_data.js.map