"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clickReportSpotEmail = exports.sendMonthlySpotCheckReport = exports.clickSpotEmail = exports.spotCheckMaterial = void 0;
var tslib_1 = require("tslib");
var lodash_1 = require("lodash");
var const_1 = require("../const");
var _ = require("lodash");
var content_hub_1 = require("../methods/content_hub");
var axios_1 = require("axios");
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();
                console.log('sendEmail===>', "".concat(process.env.LOCAL_ROOT_URL || process.env.ROOT_URL, "/api/v6/email/send"), {
                    from: from,
                    to: to.email,
                    subject: subject,
                    text: text,
                    html: html
                }, {
                    headers: {
                        'Authorization': "Bearer apikey,".concat(process.env.STEEDOS_API_KEY)
                    }
                }, result);
                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, existingRecord, spaceUser, department, allRecords, spotCheckers, spotCheckDepartments, materialApproval, 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 e_1, _b, e_2, _c;
            return tslib_1.__generator(this, function (_d) {
                switch (_d.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 = _d.sent();
                        ctx.logger = logger;
                        if (!mid) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_material').findOne(mid)];
                    case 2:
                        material = _d.sent();
                        if (!material) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材标识",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('pepsico_material_spot_check_record').findOne({
                                filters: [
                                    ['pepsico_material', '=', mid],
                                    ['spot_checker', '=', user.userId]
                                ]
                            })];
                    case 3:
                        existingRecord = _d.sent();
                        if (existingRecord) {
                            return [2, {
                                    status: 500,
                                    msg: "您已经抽查过此素材, 请勿重复操作!",
                                    data: {}
                                }];
                        }
                        return [4, ctx.getObject('space_users').findOne({
                                filters: ['user', '=', user.userId]
                            })];
                    case 4:
                        spaceUser = _d.sent();
                        department = (spaceUser === null || spaceUser === void 0 ? void 0 : spaceUser.organization) || '';
                        return [4, ctx.getObject('pepsico_material_spot_check_record').insert({
                                pepsico_material: mid,
                                spot_checker: user.userId,
                                spot_check_department: department,
                                spot_check_time: new Date(),
                                spot_check_status: pepsico_spot_check_status,
                                spot_check_opinion: description,
                                space: material.space
                            }, user)];
                    case 5:
                        _d.sent();
                        return [4, ctx.getObject('pepsico_material_spot_check_record').find({
                                filters: ['pepsico_material', '=', mid]
                            })];
                    case 6:
                        allRecords = _d.sent();
                        spotCheckers = (0, lodash_1.uniq)(allRecords.map(function (r) { return r.spot_checker; }));
                        spotCheckDepartments = (0, lodash_1.uniq)((0, lodash_1.compact)(allRecords.map(function (r) { return r.spot_check_department; })));
                        return [4, ctx.getObject('pepsico_material').directUpdate(mid, {
                                spot_checked: true,
                                spot_check_time: new Date(),
                                pepsico_spot_check: user.userId,
                                spot_description: description,
                                pepsico_spot_check_status: pepsico_spot_check_status,
                                spot_checkers: spotCheckers,
                                spot_check_departments: spotCheckDepartments,
                                spot_check_overall_status: 'checked'
                            })];
                    case 7:
                        _d.sent();
                        return [4, ctx.getObject('pepsico_material_approval').findOne(material.pepsico_material_approval)];
                    case 8:
                        materialApproval = _d.sent();
                        if (!materialApproval) {
                            return [2, {
                                    status: 500,
                                    msg: "无效的素材审批标识",
                                    data: {}
                                }];
                        }
                        if (!(pepsico_spot_check_status === true && _.includes(const_1.DCO_TYPES, materialApproval.classification))) return [3, 10];
                        return [4, (0, content_hub_1.sendByMaterial)(ctx, mid)];
                    case 9:
                        _d.sent();
                        _d.label = 10;
                    case 10:
                        users = (0, lodash_1.uniq)((0, lodash_1.compact)([materialApproval.owner, materialApproval.created_by]));
                        console.log('通知用户:', JSON.stringify(users));
                        _d.label = 11;
                    case 11:
                        _d.trys.push([11, 20, , 21]);
                        _d.label = 12;
                    case 12:
                        _d.trys.push([12, 17, 18, 19]);
                        users_1 = tslib_1.__values(users), users_1_1 = users_1.next();
                        _d.label = 13;
                    case 13:
                        if (!!users_1_1.done) return [3, 16];
                        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 14:
                        _d.sent();
                        _d.label = 15;
                    case 15:
                        users_1_1 = users_1.next();
                        return [3, 13];
                    case 16: return [3, 19];
                    case 17:
                        e_1_1 = _d.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 19];
                    case 18:
                        try {
                            if (users_1_1 && !users_1_1.done && (_b = users_1.return)) _b.call(users_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 19: return [3, 21];
                    case 20:
                        error_1 = _d.sent();
                        console.log(error_1);
                        return [3, 21];
                    case 21:
                        _d.trys.push([21, 33, , 34]);
                        return [4, ctx.getObject('space_users').find({
                                filters: ['user', 'in', users]
                            })];
                    case 22:
                        spaceUsers = _d.sent();
                        subject = '【系统通知】素材抽检结果通知';
                        _d.label = 23;
                    case 23:
                        _d.trys.push([23, 30, 31, 32]);
                        spaceUsers_1 = tslib_1.__values(spaceUsers), spaceUsers_1_1 = spaceUsers_1.next();
                        _d.label = 24;
                    case 24:
                        if (!!spaceUsers_1_1.done) return [3, 29];
                        u = spaceUsers_1_1.value;
                        return [4, ctx.getObject('pepsico_mail_send_log')._makeNewID()];
                    case 25:
                        lid = _d.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 26:
                        result = _d.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: material.space
                            }, user)];
                    case 27:
                        _d.sent();
                        _d.label = 28;
                    case 28:
                        spaceUsers_1_1 = spaceUsers_1.next();
                        return [3, 24];
                    case 29: return [3, 32];
                    case 30:
                        e_2_1 = _d.sent();
                        e_2 = { error: e_2_1 };
                        return [3, 32];
                    case 31:
                        try {
                            if (spaceUsers_1_1 && !spaceUsers_1_1.done && (_c = spaceUsers_1.return)) _c.call(spaceUsers_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                        return [7];
                    case 32: return [3, 34];
                    case 33:
                        error_2 = _d.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, 34];
                    case 34: 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 = "/accounts/a/#/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: '16541517620111040' },
                            { label: '奇多', value: '1654151762046893' },
                            { label: 'Doritos/多力多滋', value: '16541517620141606' },
                            { label: 'Popcorners', value: '166686519900' },
                            { label: '一口阳光', value: '1654151762018542' },
                            { label: '妙脆角', value: '165788230400' },
                            { label: '桂格', value: '16541517620103133' },
                            { label: '百事食品', value: '1654151762014792' }
                        ];
                        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', '=', true], ['product', '=', brandLeader.name], ['classification', '=', brandLeader.classification], ['spot_check_time', '>=', monthStart], ['spot_check_time', '<=', monthEnd]]
                                        })];
                                    case 1:
                                        list = _d.sent();
                                        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 = _.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, _.join(_.map(toUsers, 'email'), ';'), subject, '', html, _.join(_.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 = "/accounts/a/#/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];
                }
            });
        });
    }
};
//# sourceMappingURL=spotCheckMaterial.js.map