"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateSpotCheckPool = exports.clickPoolSpotEmail = exports.clickReportSpotEmail = exports.sendMonthlySpotCheckReport = exports.clickSpotEmail = exports.spotCheckMaterial = void 0;
var tslib_1 = require("tslib");
var lodash_1 = require("lodash");
var axios_1 = require("axios");
var collection_1 = require("./collection");
var moment = require('moment');
var sendEmail = function (from, to, subject, text, html, cc) { 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(process.env.LOCAL_ROOT_URL || process.env.ROOT_URL, "/api/v6/email/send"), {
                    from: from,
                    to: to,
                    cc: cc,
                    subject: subject,
                    text: text,
                    html: html
                }, {
                    headers: {
                        'Authorization': "Bearer apikey,".concat(process.env.STEEDOS_API_KEY)
                    }
                })];
            case 1:
                result = _a.sent();
                return [2, JSON.stringify(result.data)];
        }
    });
}); };
var sendMailToUsers = function (from, toUsers, ccUsers, subject, text, html) { 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(process.env.LOCAL_ROOT_URL || process.env.ROOT_URL, "/api/v6/email/sendMailToUsers"), {
                    from: from,
                    toUserIds: toUsers,
                    ccUserIds: ccUsers,
                    subject: subject,
                    text: text,
                    html: html
                }, {
                    headers: {
                        'Authorization': "Bearer apikey,".concat(process.env.STEEDOS_API_KEY)
                    }
                })];
            case 1:
                result = _a.sent();
                console.log('sendMailToUsers====>', "".concat(process.env.LOCAL_ROOT_URL || process.env.ROOT_URL, "/api/v6/email/sendMailToUsers"), {
                    from: from,
                    toUserIds: toUsers,
                    ccUserIds: ccUsers,
                    subject: subject,
                    text: text,
                    html: html
                }, {
                    headers: {
                        'Authorization': "Bearer apikey,".concat(process.env.STEEDOS_API_KEY)
                    }
                }, result);
                return [2, result.data];
        }
    });
}); };
exports.spotCheckMaterial = {
    rest: {
        method: 'POST',
        fullPath: '/api/pepsico-content/material/spot-check/:mid'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, _a, mid, description, pepsico_spot_check_status, logger, material, checkRole, checkField, checkUsers, spot_checked_done, spot_checked_done_time, now, materialNew_1, materialApproval, materialNew, canSendMessage, users, users_1, users_1_1, to, e_1_1, error_1, spaceUsers, subject, spaceUsers_1, spaceUsers_1_1, u, lid, html, result, e_2_1, error_2;
            var _b, _c, e_1, _d, e_2, _e;
            return tslib_1.__generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        user = ctx.meta.user;
                        _a = ctx.params, mid = _a.mid, description = _a.description, pepsico_spot_check_status = _a.pepsico_spot_check_status;
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _f.sent();
                        ctx.logger = logger;
                        if (!mid) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_material').findOne(mid)];
                    case 2:
                        material = _f.sent();
                        if (!material) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材标识",
                                    data: {}
                                }];
                        }
                        if (material.spot_checked_done) {
                            return [2, {
                                    status: 500,
                                    msg: "已抽查, 请勿重复操作!",
                                    data: {}
                                }];
                        }
                        checkRole = '';
                        checkField = '';
                        checkUsers = '';
                        spot_checked_done = false;
                        spot_checked_done_time = null;
                        if (!(material.spot_check_type === '审核专员抽查' || material.spot_check_type === '四部门抽查')) return [3, 8];
                        if (material.spot_check_type === '审核专员抽查') {
                            if (material.guding_spot_check != true && (0, lodash_1.includes)(material.guding_spot_check_user, user.userId)) {
                                checkRole = '审核专员';
                                checkField = 'guding_spot_check';
                                checkUsers = 'guding_spot_check_user';
                                spot_checked_done = true;
                                spot_checked_done_time = new Date();
                            }
                        }
                        else if (material.spot_check_type === '四部门抽查') {
                            if (material.legal_spot_check != true && (0, lodash_1.includes)(material.legal_spot_check_user, user.userId)) {
                                checkRole = 'Legal';
                                checkField = 'legal_spot_check';
                                checkUsers = 'legal_spot_check_user';
                            }
                            else if (material.sra_spot_check != true && (0, lodash_1.includes)(material.sra_spot_check_user, user.userId)) {
                                checkRole = 'SRA';
                                checkField = 'sra_spot_check';
                                checkUsers = 'sra_spot_check_user';
                            }
                            else if (material.ca_spot_check != true && (0, lodash_1.includes)(material.ca_spot_check_user, user.userId)) {
                                checkRole = 'CA';
                                checkField = 'ca_spot_check';
                                checkUsers = 'ca_spot_check_user';
                            }
                            else if (material.ns_spot_check != true && (0, lodash_1.includes)(material.ns_spot_check_user, user.userId)) {
                                checkRole = 'NS';
                                checkField = 'ns_spot_check';
                                checkUsers = 'ns_spot_check_user';
                            }
                        }
                        if (!checkRole) {
                            return [2, {
                                    status: 500,
                                    msg: "已抽查或无抽查权限!",
                                    data: {}
                                }];
                        }
                        now = new Date();
                        return [4, ctx.getObject('pepsico_material_spot_check').insert({
                                name: checkRole,
                                owner: user.userId,
                                pepsico_spot_check: user.userId,
                                role: checkRole,
                                pepsico_spot_check_status: pepsico_spot_check_status,
                                spot_check_time: now,
                                spot_description: description,
                                pepsico_material: mid,
                                pepsico_material_approval: material.pepsico_material_approval,
                                space: material.space,
                                created: now,
                                created_by: user.userId,
                                modified: now,
                                modified_by: user.userId
                            })];
                    case 3:
                        _f.sent();
                        return [4, ctx.getObject('pepsico_material').directUpdate(mid, (_b = {
                                    spot_checked_done: spot_checked_done,
                                    spot_checked_done_time: spot_checked_done_time
                                },
                                _b[checkField] = true,
                                _b.$pull = (_c = {},
                                    _c[checkUsers] = user.userId,
                                    _c),
                                _b))];
                    case 4:
                        _f.sent();
                        if (!(material.spot_check_type === '四部门抽查')) return [3, 7];
                        return [4, ctx.getObject('pepsico_material').findOne(mid)];
                    case 5:
                        materialNew_1 = _f.sent();
                        if (!(materialNew_1.legal_spot_check && materialNew_1.sra_spot_check && materialNew_1.ca_spot_check && materialNew_1.ns_spot_check)) return [3, 7];
                        return [4, ctx.getObject('pepsico_material').directUpdate(mid, {
                                spot_checked_done: true,
                                spot_checked_done_time: new Date()
                            })];
                    case 6:
                        _f.sent();
                        _f.label = 7;
                    case 7: return [3, 9];
                    case 8: return [2, {
                            status: 500,
                            msg: "此素材不需要抽查",
                            data: {}
                        }];
                    case 9: return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                    case 10:
                        materialApproval = _f.sent();
                        if (!materialApproval) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材审批标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_material').findOne(mid)];
                    case 11:
                        materialNew = _f.sent();
                        canSendMessage = false;
                        if (materialNew.spot_checked_done) {
                            canSendMessage = true;
                        }
                        if (!canSendMessage) return [3, 35];
                        users = (0, lodash_1.uniq)((0, lodash_1.compact)([materialApproval.owner, materialApproval.created_by]));
                        console.log('通知用户:', JSON.stringify(users));
                        _f.label = 12;
                    case 12:
                        _f.trys.push([12, 21, , 22]);
                        _f.label = 13;
                    case 13:
                        _f.trys.push([13, 18, 19, 20]);
                        users_1 = tslib_1.__values(users), users_1_1 = users_1.next();
                        _f.label = 14;
                    case 14:
                        if (!!users_1_1.done) return [3, 17];
                        to = users_1_1.value;
                        console.log('站内通知用户:', to);
                        return [4, ctx.broker.call('notifications.add', {
                                message: {
                                    name: "\u7D20\u6750\u62BD\u68C0\u7ED3\u679C\u901A\u77E5: ".concat(material.name),
                                    body: "\u8BF7\u70B9\u51FB\u7D20\u6750\u8FDB\u884C\u67E5\u770B",
                                    related_to: {
                                        o: "pepsico_material_approval",
                                        ids: [materialApproval._id]
                                    },
                                    related_name: materialApproval.name,
                                    from: user.userId,
                                    space: materialApproval.space
                                },
                                from: user.userId,
                                to: to
                            })];
                    case 15:
                        _f.sent();
                        _f.label = 16;
                    case 16:
                        users_1_1 = users_1.next();
                        return [3, 14];
                    case 17: return [3, 20];
                    case 18:
                        e_1_1 = _f.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 20];
                    case 19:
                        try {
                            if (users_1_1 && !users_1_1.done && (_d = users_1.return)) _d.call(users_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 20: return [3, 22];
                    case 21:
                        error_1 = _f.sent();
                        console.log(error_1);
                        return [3, 22];
                    case 22:
                        _f.trys.push([22, 34, , 35]);
                        return [4, ctx.getObject('space_users').find({
                                filters: ['user', 'in', users]
                            })];
                    case 23:
                        spaceUsers = _f.sent();
                        subject = '【系统通知】素材抽检结果通知';
                        _f.label = 24;
                    case 24:
                        _f.trys.push([24, 31, 32, 33]);
                        spaceUsers_1 = tslib_1.__values(spaceUsers), spaceUsers_1_1 = spaceUsers_1.next();
                        _f.label = 25;
                    case 25:
                        if (!!spaceUsers_1_1.done) return [3, 30];
                        u = spaceUsers_1_1.value;
                        return [4, ctx.getObject('pepsico_mail_send_log')._makeNewID()];
                    case 26:
                        lid = _f.sent();
                        html = "\n                        <p>\u60A8\u63D0\u4EA4\u7684\u7D20\u6750\u5DF2\u7ECF\u88AB\u62BD\u67E5\u3002\u8BF7\u70B9\u51FB\u4E0B\u9762\u7684\u94FE\u63A5\u767B\u5F55\u7CFB\u7EDF\u67E5\u770B\u62BD\u67E5\u610F\u89C1\uFF1A</p>\n                        <a href=\"".concat(process.env.ROOT_URL, "/api/pepsico-content/material/click/spot-check/").concat(mid, "/").concat(lid, "\">").concat(materialApproval.name, ":").concat(material.name, "</a>\n                    ");
                        return [4, sendEmail(process.env.B6_EMAIL_FROM, u.email, subject, '', html, '')];
                    case 27:
                        result = _f.sent();
                        return [4, ctx.getObject('pepsico_mail_send_log').insert({
                                _id: lid,
                                name: subject,
                                created: new Date(),
                                content: html,
                                type: '素材抽查',
                                to: [u.user],
                                pepsico_material: material._id,
                                result: result,
                                space: materialNew.space
                            }, user)];
                    case 28:
                        _f.sent();
                        _f.label = 29;
                    case 29:
                        spaceUsers_1_1 = spaceUsers_1.next();
                        return [3, 25];
                    case 30: return [3, 33];
                    case 31:
                        e_2_1 = _f.sent();
                        e_2 = { error: e_2_1 };
                        return [3, 33];
                    case 32:
                        try {
                            if (spaceUsers_1_1 && !spaceUsers_1_1.done && (_e = spaceUsers_1.return)) _e.call(spaceUsers_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                        return [7];
                    case 33: return [3, 35];
                    case 34:
                        error_2 = _f.sent();
                        console.log(error_2);
                        logger === null || logger === void 0 ? void 0 : logger.error("[\u7D20\u6750\u62BD\u67E5]-".concat(mid), { error: error_2.message });
                        return [3, 35];
                    case 35: return [2, {
                            status: 0,
                            data: {}
                        }];
                }
            });
        });
    }
};
exports.clickSpotEmail = {
    rest: {
        method: 'GET',
        authorization: false,
        fullPath: '/api/pepsico-content/material/click/spot-check/:mid/:lid'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, _a, mid, lid, logger, material, materialApproval;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        user = ctx.meta.user;
                        _a = ctx.params, mid = _a.mid, lid = _a.lid;
                        if (!user) {
                            ctx.meta.$statusCode = 302;
                            ctx.meta.$location = "/login?redirect_uri=" + encodeURIComponent("/api/pepsico-content/material/click/spot-check/".concat(mid, "/").concat(lid));
                            return [2];
                        }
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _b.sent();
                        ctx.logger = logger;
                        if (!mid) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_material').findOne(mid)];
                    case 2:
                        material = _b.sent();
                        if (!material) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                    case 3:
                        materialApproval = _b.sent();
                        if (!materialApproval) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材审批标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_mail_visit_log').insert({
                                owner: user.userId,
                                created: new Date(),
                                type: '素材抽查',
                                pepsico_material_approval: material.pepsico_material_approval,
                                pepsico_material: material._id,
                                pepsico_mail_send_log: lid,
                                space: material.space
                            }, user)];
                    case 4:
                        _b.sent();
                        ctx.meta.$statusCode = 302;
                        ctx.meta.$location = "/app/pepsico_content_review/pepsico_material_approval/view/".concat(materialApproval._id, "?side_object=pepsico_material_approval");
                        return [2];
                }
            });
        });
    }
};
function getMonthStartEndDate(year, month) {
    if (typeof year !== 'number' || typeof month !== 'number') {
        throw new Error('年份和月份必须是数字');
    }
    if (month < 1 || month > 12) {
        throw new Error('月份必须在1-12之间');
    }
    var date = moment([year, month - 1]);
    if (!date.isValid()) {
        throw new Error('无效的年份或月份');
    }
    var monthStart = date.startOf('month').toDate();
    var monthEnd = date.endOf('month').toDate();
    return {
        monthStart: monthStart,
        monthEnd: monthEnd
    };
}
exports.sendMonthlySpotCheckReport = {
    rest: {
        method: 'GET',
        fullPath: '/api/pepsico-content/material/send-report/spot-check/:rid'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, rid, logger, report, yearMonth, data, _a, monthStart, monthEnd, brandList, brandLeaderList, _loop_1, brandLeaderList_1, brandLeaderList_1_1, brandLeader, e_3_1;
            var e_3, _b;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        user = ctx.meta.user;
                        rid = ctx.params.rid;
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _c.sent();
                        ctx.logger = logger;
                        return [4, ctx.getObject('pepsico_spot_check_report').findOne(rid)];
                    case 2:
                        report = _c.sent();
                        if (!report) {
                            throw new Error('无效的id');
                        }
                        yearMonth = report.year_month;
                        data = yearMonth.split('-');
                        _a = getMonthStartEndDate(Number(data[0]), Number(data[1])), monthStart = _a.monthStart, monthEnd = _a.monthEnd;
                        brandList = [
                            { label: '百事可乐', value: '1654151762098375' },
                            { label: '美年达', value: '16541517620125532' },
                            { label: '7UP', value: '16541517620100467' },
                            { label: '佳得乐', value: '1654151762089415' },
                            { label: '新品牌', value: '168895721414' },
                            { label: '新业务', value: '168895721415' },
                            { label: 'Sales', value: '168895721416' }
                        ];
                        return [4, ctx.getObject('pepsico_brand_leader').directFind({ filters: [] })];
                    case 3:
                        brandLeaderList = _c.sent();
                        _loop_1 = function (brandLeader) {
                            var list, subject, brand, lid, html, toUsers, error_3, ccUsers, error_4, result;
                            return tslib_1.__generator(this, function (_d) {
                                switch (_d.label) {
                                    case 0: return [4, ctx.getObject('pepsico_material').directFind({
                                            filters: [['spot_checked_done', '=', true], ['product', '=', brandLeader.name], ['classification', '=', brandLeader.classification], ['spot_checked_done_time', '>=', monthStart], ['spot_checked_done_time', '<=', monthEnd]]
                                        })];
                                    case 1:
                                        list = _d.sent();
                                        console.log('sendMonthlySpotCheckReport find', brandLeader.name, list.length, JSON.stringify({
                                            filters: [['spot_checked_done', '=', true], ['product', '=', brandLeader.name], ['classification', '=', brandLeader.classification], ['spot_checked_done_time', '>=', monthStart], ['spot_checked_done_time', '<=', monthEnd]]
                                        }));
                                        if (!(list.length > 0)) return [3, 13];
                                        subject = "\u3010\u7CFB\u7EDF\u901A\u77E5\u3011".concat(brandLeader.remark, "\u6708\u5EA6\u62BD\u67E5\u62A5\u544A[").concat(yearMonth, "]");
                                        brand = (0, lodash_1.find)(brandList, function (item) { return item.value === brandLeader.name; });
                                        if (!brandLeader) return [3, 13];
                                        return [4, ctx.getObject('pepsico_mail_send_log')._makeNewID()];
                                    case 2:
                                        lid = _d.sent();
                                        html = "\n                        <p>\u4EB2\u7231\u7684\u7528\u6237\uFF0C</p>\n                        <p>\u672C\u6708".concat(brand.label, "\u62BD\u67E5\u7D20\u6750\u62A5\u544A\u5DF2\u751F\u6210\u3002 \u8BF7\u70B9\u51FB\u4E0B\u9762\u94FE\u63A5\u67E5\u770B").concat(brand.label, "\u6708\u5EA6\u62BD\u67E5\u62A5\u544A\uFF0C\u5EFA\u8BAE\u5206\u4EAB\u7ED9\u56E2\u961F\u6210\u5458\u8FDB\u884C\u5B66\u4E60\u3002</p>\n                        <a href=\"").concat(process.env.ROOT_URL, "/api/pepsico-content/material/click/spot-report/").concat(rid, "/").concat(lid, "\">").concat(brandLeader.remark, "\uFF1A").concat(yearMonth, "</a>\n                        <p>\u6709\u4EFB\u4F55\u7591\u95EE\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\u3002</p>\n                        <p>\u8C22\u8C22\uFF01</p>\n                    ");
                                        toUsers = [];
                                        if (!brandLeader.to) return [3, 6];
                                        _d.label = 3;
                                    case 3:
                                        _d.trys.push([3, 5, , 6]);
                                        return [4, ctx.getObject('space_users').find({ filters: ['user', 'in', brandLeader.to] })];
                                    case 4:
                                        toUsers = _d.sent();
                                        return [3, 6];
                                    case 5:
                                        error_3 = _d.sent();
                                        console.log(error_3);
                                        return [3, 6];
                                    case 6:
                                        ccUsers = [];
                                        if (!brandLeader.cc) return [3, 10];
                                        _d.label = 7;
                                    case 7:
                                        _d.trys.push([7, 9, , 10]);
                                        return [4, ctx.getObject('space_users').find({ filters: ['user', 'in', brandLeader.cc] })];
                                    case 8:
                                        ccUsers = _d.sent();
                                        return [3, 10];
                                    case 9:
                                        error_4 = _d.sent();
                                        console.log(error_4);
                                        return [3, 10];
                                    case 10: return [4, sendEmail(process.env.B6_EMAIL_FROM, (0, lodash_1.join)((0, lodash_1.map)(toUsers, 'email'), ';'), subject, '', html, (0, lodash_1.join)((0, lodash_1.map)(ccUsers, 'email'), ';'))];
                                    case 11:
                                        result = _d.sent();
                                        return [4, ctx.getObject('pepsico_mail_send_log').insert({
                                                _id: lid,
                                                name: subject,
                                                created: new Date(),
                                                content: html,
                                                type: '月度抽查报告',
                                                to: brandLeader.to,
                                                cc: brandLeader.cc,
                                                product: brand.value,
                                                classification: brandLeader.classification,
                                                pepsico_spot_check_report: rid,
                                                result: result,
                                                space: report.space
                                            }, user)];
                                    case 12:
                                        _d.sent();
                                        _d.label = 13;
                                    case 13: return [2];
                                }
                            });
                        };
                        _c.label = 4;
                    case 4:
                        _c.trys.push([4, 9, 10, 11]);
                        brandLeaderList_1 = tslib_1.__values(brandLeaderList), brandLeaderList_1_1 = brandLeaderList_1.next();
                        _c.label = 5;
                    case 5:
                        if (!!brandLeaderList_1_1.done) return [3, 8];
                        brandLeader = brandLeaderList_1_1.value;
                        return [5, _loop_1(brandLeader)];
                    case 6:
                        _c.sent();
                        _c.label = 7;
                    case 7:
                        brandLeaderList_1_1 = brandLeaderList_1.next();
                        return [3, 5];
                    case 8: return [3, 11];
                    case 9:
                        e_3_1 = _c.sent();
                        e_3 = { error: e_3_1 };
                        return [3, 11];
                    case 10:
                        try {
                            if (brandLeaderList_1_1 && !brandLeaderList_1_1.done && (_b = brandLeaderList_1.return)) _b.call(brandLeaderList_1);
                        }
                        finally { if (e_3) throw e_3.error; }
                        return [7];
                    case 11: return [4, ctx.getObject('pepsico_spot_check_report').directUpdate(rid, {
                            mail_send: true,
                            mail_send_date: new Date()
                        })];
                    case 12:
                        _c.sent();
                        return [2];
                }
            });
        });
    }
};
exports.clickReportSpotEmail = {
    rest: {
        method: 'GET',
        authorization: false,
        fullPath: '/api/pepsico-content/material/click/spot-report/:rid/:lid'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, _a, rid, lid, logger, report;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        user = ctx.meta.user;
                        _a = ctx.params, rid = _a.rid, lid = _a.lid;
                        if (!user) {
                            ctx.meta.$statusCode = 302;
                            ctx.meta.$location = "/login?redirect_uri=" + encodeURIComponent("/api/pepsico-content/material/click/spot-report/".concat(rid, "/").concat(lid));
                            return [2];
                        }
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _b.sent();
                        ctx.logger = logger;
                        if (!rid) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_spot_check_report').findOne(rid)];
                    case 2:
                        report = _b.sent();
                        if (!report) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_mail_visit_log').insert({
                                owner: user.userId,
                                created: new Date(),
                                type: '月度抽查报告',
                                pepsico_mail_send_log: lid,
                                space: report.space
                            }, user)];
                    case 3:
                        _b.sent();
                        ctx.meta.$statusCode = 302;
                        ctx.meta.$location = "/app/pepsico_content_review/page/pepsico_spot_check_report?rid=".concat(rid, "&lid=").concat(lid);
                        return [2];
                }
            });
        });
    }
};
exports.clickPoolSpotEmail = {
    rest: {
        method: 'GET',
        authorization: false,
        fullPath: '/api/pepsico-content/material/click/spot-pool/:pid'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, pid, logger, pool;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = ctx.meta.user;
                        pid = ctx.params.pid;
                        if (!user) {
                            ctx.meta.$statusCode = 302;
                            ctx.meta.$location = "/login?redirect_uri=" + encodeURIComponent("/api/pepsico-content/material/click/spot-pool/".concat(pid));
                            return [2];
                        }
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _a.sent();
                        ctx.logger = logger;
                        if (!pid) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_spot_check_pool').findOne(pid)];
                    case 2:
                        pool = _a.sent();
                        if (!pool) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的标识",
                                    data: {}
                                }];
                        }
                        ctx.meta.$statusCode = 302;
                        ctx.meta.$location = "/app/pepsico_content_review/page/pepsico_spot_check?pid=".concat(pid);
                        return [2];
                }
            });
        });
    }
};
var BRAND_MAPPING = {
    '1654151762098375': '百事可乐',
    '16541517620125532': '美年达',
    '16541517620100467': '7UP',
    '1654151762089415': '佳得乐',
    '168895721414': '新品牌',
    '168895721415': '新业务',
    '168895721416': 'Sales'
};
function getSpotCheckPool(yearMonth) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var client, collection, startDate, endDate, query, materials, groupedData_1, samplingPools, error_5;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, 4, 7]);
                    return [4, (0, collection_1.getCollection)('pepsico_material')];
                case 1:
                    collection = _a.sent();
                    startDate = new Date("".concat(yearMonth, "-01"));
                    endDate = new Date(startDate);
                    endDate.setMonth(endDate.getMonth() + 1);
                    query = {
                        approved_time: {
                            $gte: startDate,
                            $lt: endDate
                        },
                        void_material: {
                            $ne: true
                        }
                    };
                    return [4, collection.find(query).toArray()];
                case 2:
                    materials = _a.sent();
                    console.log("[".concat(yearMonth, "] \u627E\u5230 ").concat(materials.length, " \u4E2A\u5BA1\u6279\u5B8C\u6210\u7684\u7D20\u6750"));
                    groupedData_1 = {
                        'Mid-tier': {},
                        'Micro': {}
                    };
                    materials.forEach(function (material) {
                        var classification = material.kol_classification;
                        var product = material.product;
                        if (groupedData_1[classification] && BRAND_MAPPING[product]) {
                            if (!groupedData_1[classification][product]) {
                                groupedData_1[classification][product] = [];
                            }
                            groupedData_1[classification][product].push(material);
                        }
                        else {
                            console.log("\u4E0D\u7B26\u5408\u9884\u671F\u7684kol\u5206\u7C7B\u6216\u54C1\u724C", classification, product);
                        }
                    });
                    samplingPools = {
                        'Mid-tier': generateClassificationSpotCheckPool(groupedData_1['Mid-tier']),
                        'Micro': generateClassificationSpotCheckPool(groupedData_1['Micro']),
                        count: materials.length
                    };
                    return [2, samplingPools];
                case 3:
                    error_5 = _a.sent();
                    console.error('Error generating sampling pool:', error_5);
                    throw error_5;
                case 4:
                    if (!client) return [3, 6];
                    return [4, client.close()];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6: return [7];
                case 7: return [2];
            }
        });
    });
}
function generateClassificationSpotCheckPool(brandMaterials) {
    var e_4, _a;
    var result = {
        samplingPool: [],
        statistics: {
            total: 0,
            byBrand: {}
        }
    };
    var totalMaterials = 0;
    var brandCounts = {};
    Object.keys(brandMaterials).forEach(function (brandId) {
        var count = brandMaterials[brandId].length;
        brandCounts[brandId] = count;
        totalMaterials += count;
        result.statistics.byBrand[BRAND_MAPPING[brandId]] = {
            total: count,
            sampled: 0
        };
    });
    result.statistics.total = totalMaterials;
    if (totalMaterials === 0) {
        return result;
    }
    var targetSampleCount = Math.max(1, Math.floor(totalMaterials * 0.1));
    var targetBrandSamples = {};
    var remainingSamples = targetSampleCount;
    var pepsiTarget = Math.floor(totalMaterials * 0.04);
    if (brandCounts['1654151762098375']) {
        targetBrandSamples['1654151762098375'] = Math.min(pepsiTarget, brandCounts['1654151762098375']);
        remainingSamples -= targetBrandSamples['1654151762098375'];
    }
    var gatoradeTarget = Math.floor(totalMaterials * 0.03);
    if (brandCounts['1654151762089415']) {
        targetBrandSamples['1654151762089415'] = Math.min(gatoradeTarget, brandCounts['1654151762089415']);
        remainingSamples -= targetBrandSamples['1654151762089415'];
    }
    var otherBrandsTarget = Math.floor(totalMaterials * 0.03);
    var otherBrands = Object.keys(brandCounts).filter(function (brandId) {
        return brandId !== '1654151762098375' && brandId !== '1654151762089415';
    });
    if (otherBrands.length > 0 && remainingSamples > 0) {
        var otherBrandsTotal_1 = otherBrands.reduce(function (sum, brandId) { return sum + brandCounts[brandId]; }, 0);
        otherBrands.forEach(function (brandId) {
            var proportion = brandCounts[brandId] / otherBrandsTotal_1;
            targetBrandSamples[brandId] = Math.min(Math.floor(otherBrandsTarget * proportion), brandCounts[brandId]);
            remainingSamples -= targetBrandSamples[brandId];
        });
    }
    if (remainingSamples > 0) {
        var allBrands = Object.keys(brandCounts)
            .sort(function (a, b) { return brandCounts[b] - brandCounts[a]; });
        try {
            for (var allBrands_1 = tslib_1.__values(allBrands), allBrands_1_1 = allBrands_1.next(); !allBrands_1_1.done; allBrands_1_1 = allBrands_1.next()) {
                var brandId = allBrands_1_1.value;
                var currentSampled = targetBrandSamples[brandId] || 0;
                var available = brandCounts[brandId] - currentSampled;
                if (available > 0 && remainingSamples > 0) {
                    var addSamples = Math.min(available, remainingSamples);
                    targetBrandSamples[brandId] = (targetBrandSamples[brandId] || 0) + addSamples;
                    remainingSamples -= addSamples;
                }
                if (remainingSamples <= 0)
                    break;
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (allBrands_1_1 && !allBrands_1_1.done && (_a = allBrands_1.return)) _a.call(allBrands_1);
            }
            finally { if (e_4) throw e_4.error; }
        }
    }
    Object.keys(targetBrandSamples).forEach(function (brandId) {
        var _a;
        var samplesNeeded = targetBrandSamples[brandId];
        var materials = brandMaterials[brandId];
        if (samplesNeeded > 0 && materials.length > 0) {
            var sampled = shuffleArray(tslib_1.__spreadArray([], tslib_1.__read(materials), false)).slice(0, samplesNeeded);
            (_a = result.samplingPool).push.apply(_a, tslib_1.__spreadArray([], tslib_1.__read(sampled), false));
            result.statistics.byBrand[BRAND_MAPPING[brandId]].sampled = samplesNeeded;
        }
    });
    return result;
}
function shuffleArray(array) {
    var _a;
    var result = tslib_1.__spreadArray([], tslib_1.__read(array), false);
    for (var i = result.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        _a = tslib_1.__read([result[j], result[i]], 2), result[i] = _a[0], result[j] = _a[1];
    }
    return result;
}
exports.generateSpotCheckPool = {
    rest: {
        method: 'GET',
        authorization: false,
        fullPath: '/api/pepsico-content/material/generate/spot-check-pools/:pid'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, pid, logger, pool, yearMonth, pools, logs, _a, _b, material, approval, e_5_1, _c, _d, material, approval, e_6_1, subject, html, toUsers, users, error_6, ccUsers, result, error_7;
            var e_5, _e, e_6, _f;
            return tslib_1.__generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        user = ctx.meta.user;
                        pid = ctx.params.pid;
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _g.sent();
                        ctx.logger = logger;
                        if (user && !user.is_space_admin) {
                            throw new Error('无权限');
                        }
                        return [4, ctx.getObject('pepsico_spot_check_pool').findOne(pid)];
                    case 2:
                        pool = _g.sent();
                        if (!pool) {
                            throw new Error('无效的id');
                        }
                        yearMonth = pool.year_month;
                        _g.label = 3;
                    case 3:
                        _g.trys.push([3, 29, , 30]);
                        return [4, getSpotCheckPool(yearMonth)];
                    case 4:
                        pools = _g.sent();
                        console.log('=== 腰部(Mid-tier)抽查池子 ===');
                        console.log("\u603B\u62BD\u6837\u6570: ".concat(pools['Mid-tier'].samplingPool.length), (0, lodash_1.map)(pools['Mid-tier'].samplingPool, function (item) { return (0, lodash_1.pick)(item, ['_id', 'product']); }));
                        console.log('品牌统计:', pools['Mid-tier'].statistics.byBrand);
                        console.log('\n=== 尾部(Micro)抽查池子 ===');
                        console.log("\u603B\u62BD\u6837\u6570: ".concat(pools['Micro'].samplingPool.length), (0, lodash_1.map)(pools['Micro'].samplingPool, function (item) { return (0, lodash_1.pick)(item, ['_id', 'product']); }));
                        console.log('品牌统计:', pools['Micro'].statistics.byBrand);
                        logs = "\n            [".concat(yearMonth, "] \u627E\u5230 ").concat(pools.count, " \u4E2A\u5BA1\u6279\u5B8C\u6210\u7684\u7D20\u6750 \r\n\n            === \u8170\u90E8(Mid-tier)\u62BD\u67E5\u6C60\u5B50 === \r\n\n            \u603B\u62BD\u6837\u6570: ").concat(pools['Mid-tier'].samplingPool.length, ", ").concat(JSON.stringify((0, lodash_1.map)(pools['Mid-tier'].samplingPool, function (item) { return (0, lodash_1.pick)(item, ['_id', 'product']); })), " \r\n\n            \u54C1\u724C\u7EDF\u8BA1:, ").concat(JSON.stringify(pools['Mid-tier'].statistics.byBrand), " \r\n\n            \n=== \u5C3E\u90E8(Micro)\u62BD\u67E5\u6C60\u5B50 ===' \r\n\n            \u603B\u62BD\u6837\u6570: ").concat(pools['Micro'].samplingPool.length, ", ").concat(JSON.stringify((0, lodash_1.map)(pools['Micro'].samplingPool, function (item) { return (0, lodash_1.pick)(item, ['_id', 'product']); })), " \r\n\n            \u54C1\u724C\u7EDF\u8BA1:, ").concat(JSON.stringify(pools['Micro'].statistics.byBrand), " \r\n\n            ");
                        if (pools.count < 1) {
                            console.log('无可抽查素材. 不发送邮件.');
                            return [2];
                        }
                        _g.label = 5;
                    case 5:
                        _g.trys.push([5, 11, 12, 13]);
                        _a = tslib_1.__values(pools['Mid-tier'].samplingPool), _b = _a.next();
                        _g.label = 6;
                    case 6:
                        if (!!_b.done) return [3, 10];
                        material = _b.value;
                        return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                    case 7:
                        approval = _g.sent();
                        return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                                spot_check_pool_year_month: yearMonth,
                                spot_checked: true,
                                spot_check_type: '四部门抽查',
                                legal_spot_check_user: approval.legal_spot_check,
                                sra_spot_check_user: approval.sra_spot_check,
                                ns_spot_check_user: approval.ns_spot_check,
                                ca_spot_check_user: approval.ca_spot_check
                            })];
                    case 8:
                        _g.sent();
                        _g.label = 9;
                    case 9:
                        _b = _a.next();
                        return [3, 6];
                    case 10: return [3, 13];
                    case 11:
                        e_5_1 = _g.sent();
                        e_5 = { error: e_5_1 };
                        return [3, 13];
                    case 12:
                        try {
                            if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
                        }
                        finally { if (e_5) throw e_5.error; }
                        return [7];
                    case 13:
                        _g.trys.push([13, 19, 20, 21]);
                        _c = tslib_1.__values(pools['Micro'].samplingPool), _d = _c.next();
                        _g.label = 14;
                    case 14:
                        if (!!_d.done) return [3, 18];
                        material = _d.value;
                        return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                    case 15:
                        approval = _g.sent();
                        return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                                spot_check_pool_year_month: yearMonth,
                                spot_checked: true,
                                spot_check_type: '审核专员抽查',
                                guding_spot_check_user: approval.special_spot_check || []
                            })];
                    case 16:
                        _g.sent();
                        _g.label = 17;
                    case 17:
                        _d = _c.next();
                        return [3, 14];
                    case 18: return [3, 21];
                    case 19:
                        e_6_1 = _g.sent();
                        e_6 = { error: e_6_1 };
                        return [3, 21];
                    case 20:
                        try {
                            if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
                        }
                        finally { if (e_6) throw e_6.error; }
                        return [7];
                    case 21:
                        subject = '【系统通知】抽查素材通知';
                        html = "\n                <p>\u4EB2\u7231\u7684\u7528\u6237\uFF0C</p>\n                <p>\u3010".concat(yearMonth, "\u3011\u6708\u5EA6\u62BD\u67E5\u7D20\u6750\u6C60\u5DF2\u751F\u6210\uFF0C\u8BF7\u767B\u5F55Bev\u5185\u5BB9\u5BA1\u6838\u7CFB\u7EDF\u8FDB\u884C\u7D20\u6750\u62BD\u67E5\u3002</p>\n                <p>\u6709\u4EFB\u4F55\u7591\u95EE\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\u3002</p>\n                <p>\u8C22\u8C22\uFF01</p>\n            ");
                        toUsers = [];
                        return [4, ctx.getObject('permission_set').directFind({
                                filters: ['name', '=', 'pepsico_spot_check_users']
                            })];
                    case 22:
                        users = _g.sent();
                        if (!(users.length > 0)) return [3, 26];
                        _g.label = 23;
                    case 23:
                        _g.trys.push([23, 25, , 26]);
                        return [4, ctx.getObject('space_users').find({ filters: ['user', 'in', users[0].users || []] })];
                    case 24:
                        toUsers = _g.sent();
                        return [3, 26];
                    case 25:
                        error_6 = _g.sent();
                        console.log(error_6);
                        return [3, 26];
                    case 26:
                        ccUsers = [];
                        return [4, sendEmail(process.env.B6_EMAIL_FROM, (0, lodash_1.join)((0, lodash_1.map)(toUsers, 'email'), ';'), subject, '', html, (0, lodash_1.join)((0, lodash_1.map)(ccUsers, 'email'), ';'))];
                    case 27:
                        result = _g.sent();
                        return [4, ctx.getObject('pepsico_spot_check_pool').directUpdate(pid, {
                                mail_send: true,
                                mail_send_date: new Date(),
                                mid_tier_pepsico_material: (0, lodash_1.map)(pools['Mid-tier'].samplingPool, '_id'),
                                micro_pepsico_material: (0, lodash_1.map)(pools['Micro'].samplingPool, '_id'),
                                logs: logs + '\r\n' + "=== \u53D1\u9001\u90AE\u4EF6 === \r\n\n                \u90AE\u4EF6\u4E3B\u9898: ".concat(subject, "\r\n\n                \u6536\u4EF6\u4EBA: ").concat((0, lodash_1.join)((0, lodash_1.map)(toUsers, 'email'), ';'), "\r\n\n                \u6284\u9001: ").concat((0, lodash_1.join)((0, lodash_1.map)(ccUsers, 'email'), ';'), "\r\n\n                \u90AE\u4EF6\u5185\u5BB9: ").concat(html, "\r\n\n                \u90AE\u4EF6\u53D1\u9001\u7ED3\u679C: ").concat(result, "\n                ")
                            })];
                    case 28:
                        _g.sent();
                        return [3, 30];
                    case 29:
                        error_7 = _g.sent();
                        console.error('执行失败:', error_7);
                        return [3, 30];
                    case 30: return [2];
                }
            });
        });
    }
};
//# sourceMappingURL=spotCheckMaterial.js.map