"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.countApprovalMaterialTask = exports.countApprovalTask = exports.getMaterialStatus = exports.rejectTask = exports.approveTask = exports.submitMaterialTask = void 0;
var tslib_1 = require("tslib");
var _ = require("lodash");
var consts_1 = require("./consts");
var material_1 = require("./material");
var getApproverUsers = function (ctx, approveField, approval) {
    switch (approveField) {
        case 'ca_approval_status':
            return approval.handler_ca;
        case 'sra_approval_status':
            return approval.handler_sra;
        case 'ns_approval_status':
            return approval.handler_ns;
        case 'legal_approval_status':
            return approval.handler_legal;
        case 'approval_status':
            return approval.handler_guding;
        case 'kids_approval_status':
            return approval.handler_kids;
        default:
            break;
    }
};
var submitMaterialTask = function (ctx, materialId, approvalStatus) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, material, approval, approveField, approveUsers, skipSetDone, _tasks, _a, materialList, pendingMaterialList, tasks, pendingMaterialIds, taskMaterialIds, processed, filters, process_2, rejectedTask, approvalStatus_1, process_1, process_1_1, item, e_1_1, approvalLatest, updateDoc, pendingUsers, removeIndex, status;
        var e_1, _b;
        return tslib_1.__generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material').findOne(materialId)];
                case 1:
                    material = _c.sent();
                    return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                case 2:
                    approval = _c.sent();
                    return [4, (0, material_1.getApproverField)(ctx, approval, material, user.userId)];
                case 3:
                    approveField = _c.sent();
                    return [4, getApproverUsers(ctx, approveField, approval)];
                case 4:
                    approveUsers = _c.sent();
                    if (!approveField) {
                        return [2];
                    }
                    skipSetDone = false;
                    if (!(approveField != 'kids_approval_status')) return [3, 8];
                    return [4, ctx.getObject('pepsico_approval_task').find({
                            filters: [
                                ['pepsico_material_approval', '=', approval._id],
                                ['pepsico_material', '=', material._id],
                                ['approval_field', '=', approveField],
                                ['owner', '=', user.userId],
                                ['done', '!=', true],
                                ['done', '!=', 'archived']
                            ]
                        })];
                case 5:
                    _tasks = _c.sent();
                    if (!(_tasks.length > 0)) return [3, 7];
                    return [4, ctx.getObject('pepsico_approval_task').update(_tasks[0]._id, {
                            approval_status: approvalStatus === consts_1.ApprovalStatus.approved ? true : false,
                            approve_time: new Date(),
                            $inc: { count: 1 }
                        })];
                case 6:
                    _c.sent();
                    skipSetDone = true;
                    _c.label = 7;
                case 7: return [3, 15];
                case 8:
                    _a = approvalStatus;
                    switch (_a) {
                        case consts_1.ApprovalStatus.approved: return [3, 9];
                        case consts_1.ApprovalStatus.rejected: return [3, 11];
                    }
                    return [3, 13];
                case 9: return [4, (0, exports.approveTask)(ctx, approval, material, user, approveField)];
                case 10:
                    _c.sent();
                    return [3, 14];
                case 11: return [4, (0, exports.rejectTask)(ctx, approval, material, user, approveField)];
                case 12:
                    _c.sent();
                    return [3, 14];
                case 13: return [3, 14];
                case 14:
                    ;
                    _c.label = 15;
                case 15: return [4, ctx.getObject('pepsico_material').find({
                        filters: [
                            ['pepsico_material_approval', '=', approval._id],
                            ['void_material', '!=', true]
                        ]
                    })];
                case 16:
                    materialList = _c.sent();
                    pendingMaterialList = _.filter(materialList, function (record) {
                        return record[approveField] === null || !_.has(record, approveField) || record[approveField] === '' || record[approveField] === undefined;
                    });
                    return [4, ctx.getObject('pepsico_approval_task').find({
                            filters: [
                                ['pepsico_material_approval', '=', approval._id],
                                ['approval_field', '=', approveField],
                                ['pepsico_material', 'in', _.map(materialList, '_id')],
                                ['owner', '=', user.userId],
                                ['done', '!=', true],
                                ['done', '!=', 'archived']
                            ]
                        })];
                case 17:
                    tasks = _c.sent();
                    pendingMaterialIds = _.map(pendingMaterialList, '_id');
                    taskMaterialIds = _.uniq(_.map(tasks, 'pepsico_material'));
                    processed = _.intersection(pendingMaterialIds, taskMaterialIds);
                    console.log('submitMaterialTask: pendingMaterialIds', approval._id, pendingMaterialIds);
                    console.log('submitMaterialTask: taskMaterialIds', approval._id, taskMaterialIds);
                    console.log('submitMaterialTask', approval._id, processed.length, tasks.length, pendingMaterialList.length);
                    console.log('submitMaterialTask: tasks', approval._id, JSON.stringify(tasks));
                    if (!(processed.length == pendingMaterialList.length)) return [3, 31];
                    if (!(approveField != 'kids_approval_status')) return [3, 26];
                    filters = [
                        ["owner", "=", user.userId],
                        ["pepsico_material_approval", "=", approval._id],
                        ["current_step", "=", approval.current_step],
                        ["space", "=", approval.space],
                        ["approved", "=", 'progess']
                    ];
                    return [4, ctx.getObject("pepsico_approval_process").find({
                            filters: filters,
                            top: 1,
                            sort: "modified asc"
                        })];
                case 18:
                    process_2 = _c.sent();
                    rejectedTask = _.find(tasks, function (item) { return item.approval_status != true; });
                    approvalStatus_1 = rejectedTask ? consts_1.ApprovalStatus.rejected : consts_1.ApprovalStatus.approved;
                    console.log("approvalStatus: ", approval._id, approvalStatus_1, JSON.stringify(rejectedTask));
                    _c.label = 19;
                case 19:
                    _c.trys.push([19, 24, 25, 26]);
                    process_1 = tslib_1.__values(process_2), process_1_1 = process_1.next();
                    _c.label = 20;
                case 20:
                    if (!!process_1_1.done) return [3, 23];
                    item = process_1_1.value;
                    console.log("pepsico_approval_process update: ", approval._id, item._id, JSON.stringify({
                        submitted: new Date(),
                        modified: new Date(),
                        modified_by: user.userId,
                        approved: approvalStatus_1 || 'submit',
                        name: ctx.params.comment
                    }));
                    return [4, ctx.getObject("pepsico_approval_process").update(item._id, {
                            submitted: new Date(),
                            modified: new Date(),
                            modified_by: user.userId,
                            approved: approvalStatus_1 || 'submit',
                            name: ctx.params.comment
                        })];
                case 21:
                    _c.sent();
                    _c.label = 22;
                case 22:
                    process_1_1 = process_1.next();
                    return [3, 20];
                case 23: return [3, 26];
                case 24:
                    e_1_1 = _c.sent();
                    e_1 = { error: e_1_1 };
                    return [3, 26];
                case 25:
                    try {
                        if (process_1_1 && !process_1_1.done && (_b = process_1.return)) _b.call(process_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7];
                case 26:
                    if (!skipSetDone) return [3, 28];
                    return [4, ctx.getObject('pepsico_approval_task').directUpdateMany(['_id', '=', _.map(_.filter(tasks, function (item) {
                                return item.done != true;
                            }), '_id')], {
                            done: true,
                            done_time: new Date()
                        })];
                case 27:
                    _c.sent();
                    _c.label = 28;
                case 28: return [4, ctx.getObject('pepsico_material_approval').findOne(approval._id)];
                case 29:
                    approvalLatest = _c.sent();
                    updateDoc = {
                        $push: {
                            person_done: user.userId
                        }
                    };
                    if (approveField !== 'kids_approval_status') {
                        pendingUsers = Array.isArray(approvalLatest.person_pending_user) ? tslib_1.__spreadArray([], tslib_1.__read(approvalLatest.person_pending_user), false) : [];
                        removeIndex = pendingUsers.indexOf(user.userId);
                        if (removeIndex !== -1) {
                            pendingUsers.splice(removeIndex, 1);
                            updateDoc.person_pending_user = pendingUsers;
                        }
                    }
                    return [4, ctx.getObject('pepsico_material_approval').update(approval._id, updateDoc)];
                case 30:
                    _c.sent();
                    _c.label = 31;
                case 31: return [4, (0, exports.getMaterialStatus)(ctx, approval, approveUsers, approveField, materialId)];
                case 32:
                    status = _c.sent();
                    console.log("getMaterialStatus: ", approval._id, status);
                    if (status === consts_1.ApprovalStatus.pending) {
                        return [2];
                    }
                    return [4, this.submitMaterial.call(this, ctx, ctx.params.recordId, status)];
                case 33: return [2, _c.sent()];
            }
        });
    });
};
exports.submitMaterialTask = submitMaterialTask;
var approveTask = function (ctx, approval, material, userSession, approveField) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var tasks;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_approval_task').find({
                    filters: [
                        ['pepsico_material_approval', '=', approval._id],
                        ['pepsico_material', '=', material._id],
                        ['approval_field', '=', approveField],
                        ['owner', '=', userSession.userId],
                        ['done', '!=', true],
                        ['done', '!=', 'archived']
                    ]
                })];
            case 1:
                tasks = _a.sent();
                if (!(tasks.length > 0)) return [3, 3];
                return [4, ctx.getObject('pepsico_approval_task').update(tasks[0]._id, {
                        approval_status: true,
                        approve_time: new Date(),
                        $inc: { count: 1 }
                    })];
            case 2:
                _a.sent();
                return [3, 5];
            case 3: return [4, ctx.getObject('pepsico_approval_task').insert({
                    pepsico_material_approval: approval._id,
                    pepsico_material: material._id,
                    approval_field: approveField,
                    owner: userSession.userId,
                    approval_status: true,
                    created: new Date(),
                    modified: new Date(),
                    approve_time: new Date(),
                    space: approval.space,
                    count: 1
                })];
            case 4:
                _a.sent();
                _a.label = 5;
            case 5: return [2];
        }
    });
}); };
exports.approveTask = approveTask;
var rejectTask = function (ctx, approval, material, userSession, approveField) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var tasks;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_approval_task').find({
                    filters: [
                        ['pepsico_material_approval', '=', approval._id],
                        ['pepsico_material', '=', material._id],
                        ['approval_field', '=', approveField],
                        ['owner', '=', userSession.userId],
                        ['done', '!=', true],
                        ['done', '!=', 'archived']
                    ]
                })];
            case 1:
                tasks = _a.sent();
                if (!(tasks.length > 0)) return [3, 3];
                return [4, ctx.getObject('pepsico_approval_task').update(tasks[0]._id, {
                        approval_status: false,
                        approve_time: new Date(),
                        $inc: { count: 1 }
                    })];
            case 2:
                _a.sent();
                return [3, 5];
            case 3: return [4, ctx.getObject('pepsico_approval_task').insert({
                    pepsico_material_approval: approval._id,
                    pepsico_material: material._id,
                    approval_field: approveField,
                    owner: userSession.userId,
                    approval_status: false,
                    created: new Date(),
                    modified: new Date(),
                    approve_time: new Date(),
                    space: approval.space,
                    count: 1
                })];
            case 4:
                _a.sent();
                _a.label = 5;
            case 5: return [2];
        }
    });
}); };
exports.rejectTask = rejectTask;
var getMaterialStatus = function (ctx, approval, usersId, approveField, materialId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var tasks, _loop_1, usersId_1, usersId_1_1, userId, state_1;
    var e_2, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                console.log('getMaterialStatus: ', approval._id, usersId, approveField, materialId);
                return [4, ctx.getObject('pepsico_approval_task').find({
                        filters: [
                            ['pepsico_material_approval', '=', approval._id],
                            ['approval_field', '=', approveField],
                            ['pepsico_material', '=', materialId],
                            ['done', '!=', 'archived']
                        ]
                    })];
            case 1:
                tasks = _b.sent();
                console.log('getMaterialStatus: ', approval._id, materialId, 'tasks.length:', tasks.length);
                if (usersId.length > tasks.length) {
                    return [2, consts_1.ApprovalStatus.pending];
                }
                _loop_1 = function (userId) {
                    var userTasks = _.filter(tasks, function (item) { return item.owner == userId; });
                    console.log('userTasks', userId, JSON.stringify(userTasks));
                    if (!_.find(userTasks, function (item) { return item.approval_status == true; })) {
                        return { value: consts_1.ApprovalStatus.rejected };
                    }
                };
                try {
                    for (usersId_1 = tslib_1.__values(usersId), usersId_1_1 = usersId_1.next(); !usersId_1_1.done; usersId_1_1 = usersId_1.next()) {
                        userId = usersId_1_1.value;
                        state_1 = _loop_1(userId);
                        if (typeof state_1 === "object")
                            return [2, state_1.value];
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (usersId_1_1 && !usersId_1_1.done && (_a = usersId_1.return)) _a.call(usersId_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                return [2, consts_1.ApprovalStatus.approved];
        }
    });
}); };
exports.getMaterialStatus = getMaterialStatus;
var countApprovalTask = function () {
};
exports.countApprovalTask = countApprovalTask;
var countApprovalMaterialTask = function () {
};
exports.countApprovalMaterialTask = countApprovalMaterialTask;
//# sourceMappingURL=task.js.map