"use strict";
//relatorio
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTicksCountByStatusChatEnds = exports.reportServiceByQueue = exports.reportService = exports.reportOnQueue = exports.reportMessagesUserByDateStartDateEnd = exports.reportUserService = exports.reportUserByDateStartDateEnd = void 0;
const AppError_1 = __importDefault(require("../errors/AppError"));
const ShowTicketReport_1 = __importDefault(require("../services/TicketServices/ShowTicketReport"));
const ShowMessageReport_1 = __importDefault(require("../services/MessageServices/ShowMessageReport"));
const Queue_1 = __importDefault(require("../models/Queue"));
const format_1 = __importDefault(require("date-fns/format"));
const pt_BR_1 = __importDefault(require("date-fns/locale/pt-BR"));
const SplitDateTime_1 = require("../helpers/SplitDateTime");
const ListUsersOnlineOfflineService_1 = __importDefault(require("../services/UserServices/ListUsersOnlineOfflineService"));
const ListUserParamiterService_1 = __importDefault(require("../services/UserServices/ListUserParamiterService"));
const ShowUserServiceReport_1 = __importDefault(require("../services/UserServices/ShowUserServiceReport"));
const CountTicketsByUserQueue_1 = __importDefault(require("../services/UserServices/CountTicketsByUserQueue"));
const ShowQueuesByUser_1 = __importDefault(require("../services/UserServices/ShowQueuesByUser"));
const socket_1 = require("../libs/socket");
const ReportByNumberQueueService_1 = __importDefault(require("../services/ReportServices/ReportByNumberQueueService"));
const CountStatusChatEndService_1 = __importDefault(require("../services/StatusChatEndService/CountStatusChatEndService"));
const reportUserByDateStartDateEnd = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "master" &&
        req.user.profile !== "admin" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { userId, startDate, endDate, pageNumber, userQueues, createdOrUpdated, queueId } = req.query;
    const { tickets, count, hasMore } = yield ShowTicketReport_1.default({
        userId,
        startDate,
        endDate,
        pageNumber,
        createdOrUpdated,
        queueId,
    });
    const queues = yield Queue_1.default.findAll({ attributes: ["id", "name"] });
    return res.status(200).json({ tickets, count, hasMore, queues });
});
exports.reportUserByDateStartDateEnd = reportUserByDateStartDateEnd;
const reportUserService = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "master" &&
        req.user.profile !== "admin" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { userId, startDate, endDate, userQueues } = req.query;
    // let usersProfile = await ListUserParamiterService({ profile: 'user' })
    let usersProfile = yield ListUserParamiterService_1.default({
        profiles: ["user", "supervisor"],
        userQueues: userQueues ? userQueues : undefined,
        raw: true
    });
    const sumUserOlineTime = yield ShowUserServiceReport_1.default({
        startDate,
        endDate,
        userId
    });
    const closedByUser = yield ShowUserServiceReport_1.default({
        startDate,
        endDate,
        ticketStatus: "closed",
        userId
    });
    const openByUser = yield ShowUserServiceReport_1.default({
        startDate,
        endDate,
        ticketStatus: "open",
        userId
    });
    let dateTime = SplitDateTime_1.splitDateTime(new Date(format_1.default(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: pt_BR_1.default })));
    const onlineUsers = yield ListUsersOnlineOfflineService_1.default({ date: dateTime.fullDate });
    const openByUserOnQueue = yield CountTicketsByUserQueue_1.default({
        startDate: startDate,
        endDate: endDate,
        status: "open",
        clientChatStart: true
    });
    const openByUserOutQueue = yield CountTicketsByUserQueue_1.default({
        startDate: startDate,
        endDate: endDate,
        status: "open",
        clientChatStart: false
    });
    const closedByUserOnQueue = yield CountTicketsByUserQueue_1.default({
        startDate: startDate,
        endDate: endDate,
        status: "closed",
        clientChatStart: true
    });
    const closedUserOutQueue = yield CountTicketsByUserQueue_1.default({
        startDate: startDate,
        endDate: endDate,
        status: "closed",
        clientChatStart: false
    });
    // let openQueueInOut = openByUserOnQueue.concat(openByUserOutQueue)
    // let closedQueueInOut = closedByUserOnQueue.concat(closedUserOutQueue)
    const queuesByUser = yield ShowQueuesByUser_1.default({ profile: "user" });
    let openCloseOnQueue = openByUserOnQueue.concat(closedByUserOnQueue);
    let openCloseOutQueue = openByUserOutQueue.concat(closedUserOutQueue);
    // console.log('onlineUsers: ',JSON.parse(JSON.stringify(onlineUsers)))
    // console.log('sumUserOlineTime: ', JSON.parse(JSON.stringify(sumUserOlineTime)))
    for (let i = 0; i < queuesByUser.length; i++) {
        queuesByUser[i].countOpen = 0;
        queuesByUser[i].countClosed = 0;
        for (let x = 0; x < openCloseOnQueue.length; x++) {
            if (queuesByUser[i].userId == openCloseOnQueue[x].userId &&
                queuesByUser[i].queueId == openCloseOnQueue[x].queueId &&
                openCloseOnQueue[x].status == "open") {
                queuesByUser[i].countOpen = openCloseOnQueue[x].totAttendance;
            }
            else if (queuesByUser[i].userId == openCloseOnQueue[x].userId &&
                queuesByUser[i].queueId == openCloseOnQueue[x].queueId &&
                openCloseOnQueue[x].status == "closed") {
                queuesByUser[i].countClosed = openCloseOnQueue[x].totAttendance;
            }
        }
    }
    usersProfile.map((user) => {
        let index = sumUserOlineTime.findIndex((e) => e.userId == user.id);
        if (index != -1) {
            user.sumOnlineTime = sumUserOlineTime[index];
            // console.log('user.sumOlineTime: 'user.sumOnlineTime)
        }
        index = closedByUser.findIndex((e) => e.userId == user.id);
        if (index != -1) {
            user.sumClosed = closedByUser[index];
        }
        index = openByUser.findIndex((e) => e.userId == user.id);
        if (index != -1) {
            user.sumOpen = openByUser[index];
        }
        // OPEN, CLOSED TICKETS STARTED BY USERS
        let openClosedOutQueue = {};
        let open = openCloseOutQueue.filter(e => e.userId == user.id && e.status == "open");
        let closed = openCloseOutQueue.filter(e => e.userId == user.id && e.status == "closed");
        openClosedOutQueue = Object.assign(Object.assign({}, openClosedOutQueue), { userId: user.id, countOpen: open && open.length > 0 ? open[0].totAttendance : 0, countClosed: closed && closed.length > 0 ? closed[0].totAttendance : 0 });
        user.openClosedOutQueue = openClosedOutQueue;
        // OPEN, CLOSED TICKETS STARTED BY CLIENTS
        let openClosedInQueue = queuesByUser.filter(e => e.userId == user.id);
        if (openClosedInQueue && openClosedInQueue.length > 0) {
            user.openClosedInQueue = openClosedInQueue;
        }
        index = onlineUsers.findIndex((e) => e.userId == user.id);
        if (index != -1) {
            user.statusOnline = onlineUsers[index];
        }
        if (startDate.length > 0 && startDate.split("-").length == 3) {
            let date = startDate.split("-");
            user.startDate = `${date[2]}/${date[1]}/${date[0]}`;
        }
        if (endDate.length > 0 && endDate.split("-").length == 3) {
            let date = endDate.split("-");
            user.endDate = `${date[2]}/${date[1]}/${date[0]}`;
        }
    });
    return res.status(200).json({ usersProfile: usersProfile });
});
exports.reportUserService = reportUserService;
const reportMessagesUserByDateStartDateEnd = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "master" &&
        req.user.profile !== "admin" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { userId, startDate, endDate } = req.query;
    let data_query_messages = yield ShowMessageReport_1.default(userId, startDate, endDate);
    for (var i = 0; i < data_query_messages.length; i++) {
        if (data_query_messages[i].fromMe) {
            data_query_messages[i].fromMe = "Atendente";
        }
        else {
            data_query_messages[i].fromMe = "Cliente";
        }
        data_query_messages[i].id = i + 1;
    }
    return res.status(200).json(data_query_messages);
});
exports.reportMessagesUserByDateStartDateEnd = reportMessagesUserByDateStartDateEnd;
const reportOnQueue = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    // console.log(req.body)
    const { adminId, identifier, queueStatus, file } = req.body;
    const io = socket_1.getIO();
    io.emit("queryOnQueueStatus", {
        action: "update",
        queryOnQueue: {
            adminId: adminId,
            identifier: identifier,
            queueStatus: queueStatus,
            file: file
        }
    });
    return res.status(200).json({ message: "ok" });
});
exports.reportOnQueue = reportOnQueue;
const reportService = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "master" &&
        req.user.profile !== "admin" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { startDate, endDate, queueId, isRemote } = req.query;
    console.log(`startDate: ${startDate} | endDate: ${endDate} | queueId: ${queueId}`);
    console.log("IS REMOTE: ", isRemote);
    console.log("isRemote: ", isRemote && isRemote == "true" ? true : false);
    const reportService = yield ReportByNumberQueueService_1.default({
        startDate,
        endDate,
        isRemote: isRemote && isRemote == "true" ? true : false
    });
    return res.status(200).json({ reportService });
});
exports.reportService = reportService;
const reportServiceByQueue = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "master" &&
        req.user.profile !== "admin" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { startDate, endDate, queueId, isRemote } = req.query;
    const reportService = yield ReportByNumberQueueService_1.default({
        startDate,
        endDate,
        queue: true,
        isRemote: isRemote && isRemote == "true" ? true : false
    });
    return res.status(200).json({ reportService });
});
exports.reportServiceByQueue = reportServiceByQueue;
const reportTicksCountByStatusChatEnds = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "master" &&
        req.user.profile !== "admin" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { startDate, endDate, userQueues } = req.query;
    const dateToday = SplitDateTime_1.splitDateTime(new Date(format_1.default(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: pt_BR_1.default })));
    const queueIds = userQueues ? userQueues.map(queue => parseInt(queue)) : [];
    const reportStatusChatEnd = yield CountStatusChatEndService_1.default(startDate || dateToday.fullDate, endDate || dateToday.fullDate, queueIds);
    return res.status(200).json({ reportStatusChatEnd });
});
exports.reportTicksCountByStatusChatEnds = reportTicksCountByStatusChatEnds;
