const { reject } = require("bluebird");
const db = require("../dbconn");
const Log = require('../helper/log');
const Info = require('../helper/info')
var serverModel = function (obj) { };
const path = require("path");
const moment = require('moment');
const timestamp = require('console-timestamp');

const templateArray = {
    mail: [
        {
            '##ticket_id##': 'ticket_id',
            '##ticket_unique_id##': 'ticket_unique_id',
            '##email_message##': 'email_message',
            '##agent_name##': 'agent_name',
            '##agent_mobile_number##': 'agent_mobile_number',
            '##cc_email##': 'cc_email',
            '##remarks##': 'remarks',
            '##mobile_no##': 'mobile_no',
            '##signature##': 'signature',
            '##last_updated_on##': 'last_updated_on',
            '##person_name##': 'person_name',
            '##subject##': 'subject',
            '##to_email##': 'to_email',
            '##from_email##': 'from_email',
            '##happy_code##': 'happy_code',
            '##duration##': 'duration',
            '##ticket_link##': 'ticket_link',
        },
    ],
    customer_wp: [
        {
            '##ticket_id##': 'ticket_id',
            '##ticket_unique_id##': 'ticket_unique_id',
            '##email_message##': 'email_message',
            '##agent_name##': 'agent_name',
            '##agent_mobile_number##': 'agent_mobile_number',
            '##cc_email##': 'cc_email',
            '##remarks##': 'remarks',
            '##mobile_no##': 'mobile_no',
            '##signature##': 'signature',
            '##last_updated_on##': 'last_updated_on',
            '##person_name##': 'person_name',
            '##subject##': 'subject',
            '##to_email##': 'to_email',
            '##from_email##': 'from_email',
            '##happy_code##': 'happy_code',
            '##duration##': 'duration',
            '##ticket_link##': 'ticket_link',
        }
    ],
    user_mail: [
        {
            '##ticket_id##': 'ticket_id',
            '##ticket_unique_id##': 'ticket_unique_id',
            '##email_Message##': 'email_message',
            '##agent_name##': 'agent_name',
            '##agent_mobile_number##': 'agent_mobile_number',
            '##cc_email##': 'cc_email',
            '##remarks##': 'remarks',
            '##mobile_no##': 'mobile_no',
            '#signature##': 'signature',
            '##last_updated_on##': 'last_updated_on',
            '##person_name##': 'person_name',
            '##subject##': 'subject',
            '##to_email##': 'to_email',
            '##from_email##': 'from_email',
            '##happy_code##': 'happy_code',
            '##duration##': 'duration',
            '##ticket_link##': 'ticket_link',
        }
    ],
    user_sms: [
        {
            '##ticket_id##': 'ticket_id',
            '##ticket_unique_id##': 'ticket_unique_id',
            '##email_message##': 'email_message',
            '##agent_name##': 'agent_name',
            '##agent_mobile_number##': 'agent_mobile_number',
            '##cc_email##': 'cc_email',
            '##remarks##': 'remarks',
            '##mobile_no##': 'mobile_no',
            '#signature##': 'signature',
            '##last_updated_on##': 'last_updated_on',
            '##person_name##': 'person_name',
            '##subject##': 'subject',
            '##to_email##': 'to_email',
            '##from_email##': 'from_email',
            '##happy_code##': 'happy_code',
            '##duration##': 'duration',
            '##ticket_link##': 'ticket_link',
        }
    ],
    agent_escalation_mail: [
        {
            '##ticket_id##': 'ticket_id',
            '##ticket_unique_id##': 'ticket_unique_id',
            '##email_Message##': 'email_message',
            '##agent_name##': 'agent_name',
            '##agent_mobile_number##': 'agent_mobile_number',
            '##cc_email##': 'cc_email',
            '##remarks##': 'remarks',
            '##mobile_no##': 'mobile_no',
            '#signature##': 'signature',
            '##last_updated_on##': 'last_updated_on',
            '##person_name##': 'person_name',
            '##subject##': 'subject',
            '##to_email##': 'to_email',
            '##from_email##': 'from_email',
            '##happy_code##': 'happy_code',
            '##duration##': 'duration',
            '##ticket_link##': 'ticket_link',
        }
    ],
    // customer_sms: [
    //     {
    //         '##ticket_id##': 'ticket_id',
    //         '##ticket_unique_id##': 'ticket_unique_id',
    //         '##Email_Message##': 'Email_Message',
    //         '##Agent_Name##': 'Agent_Name',
    //         '##cc_email##': 'cc_email',
    //         '##remarks##': 'remarks',
    //         '##mobile_no##': 'mobile_no',
    //         '##signature##': 'signature',
    //         '##last_updated_on##': 'last_updated_on',
    //         '##person_name##': 'person_name',
    //         '##subject##': 'subject',
    //         '##to_email##': 'to_email',
    //         '##Queue_EmailId##': 'Queue_EmailId',
    //         '##happy_code##': 'happy_code'
    //     },
    // ],
};

serverModel.getData = () => {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t2.tenant_id,t2.client_secret,t2.client_oauth2_id,t2.is_auth_enable,t2.token,t2.refresh_token,t2.id,t2.server_type,t2.email,t2.display_name,t2.exchange_service,t2.incoming_user_name,t2.incoming_password,t2.outgoing_user_name,t2.outgoing_password,t2.incoming_mail_server,t2.incoming_mail_server_port,t2.incoming_enable_SSL,t2.stop_incoming_email,t2.outgoing_mail_server,t2.outgoing_mail_server_port,t2.outgoing_enable_SSL,t2.stop_outgoing_email,t2.security_protocol,t1.queue_id,t3.reopen_after,DATE_FORMAT(t3.dont_read_mail_before,'%Y-%m-%d') AS dont_read_mail_before,t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,t3.reopen_to_same_agent,t2.forwarded_mail,t3.ticket_prefix,t3.dont_read_unread_mail,t3.last_read_date
            FROM tms_queue_email t1 
            LEFT JOIN tms_email_account t2 ON t1.incoming_email_account = t2.id
            LEFT JOIN tms_queue_master t3 ON t1.queue_id  =t3.id 
            WHERE t2.stop_incoming_email = 0 and t2.status = 1 and t3.status = 1`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).catch(function (error) {
                    Log.errorLog({ error: error.err });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getTicketId = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = ` select  ifnull(max(cast(ticket_unique_id as signed)),0)+1 ticketNo from tms_ticket_master_${queue_id}`;
            db.runSqlRow(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getTicketSeries = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlstr = `select ticket_prefix from tms_queue_master where id = ${queue_id}`;
            db.runSqlRow(sqlstr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getQueueData = async function (queue_id) {
    try {
        let sqlStr = `select * from tms_queue_master where id = ${queue_id}`;
        let defstatus = `SELECT * FROM tms_queue_status_${queue_id} WHERE is_default = 1`
        let defpriority = `SELECT priority_id FROM tms_queue_priority_${queue_id} WHERE is_default = 1`
        let defclose = `SELECT t1.status_id FROM tms_queue_status_${queue_id} t1 WHERE t1.is_close_status = 1`
        let queueIncMailStatus = `SELECT t1.status_id FROM tms_queue_status_${queue_id} t1
        WHERE t1.incomming_mail_status = 1`
        let defCatAndSubCat = `SELECT * FROM tms_queue_category_${queue_id} t1 LEFT JOIN tms_queue_sub_category_${queue_id} t2 ON t1.category_id = t2.category_id AND t2.default = 1 WHERE t1.default = 1 AND t1.status = 1`
        const response = await db.runSqlRow(sqlStr);

        if (response.status !== true) {
            Log.errorLog({ error: response.err });
            return { status: false, err: response.err };
        }

        const defStatusResponse = await db.runSqlRow(defstatus);

        if (!defStatusResponse.status) {
            Log.errorLog({ error: defStatusResponse.err });
            return { status: false, err: defStatusResponse.err`${defstatus}` };
        }

        const defPriorityResponse = await db.runSqlRow(defpriority);

        if (!defPriorityResponse.status) {
            Log.errorLog({ error: defPriorityResponse.err });
            return { status: false, err: defPriorityResponse.err`${defpriority}` };
        }

        const defCloseResponse = await db.runSql(defclose);

        if (!defCloseResponse.status) {
            Log.errorLog({ error: defCloseResponse.err });
            return { status: false, err: defCloseResponse.err`${defclose}` };
        }

        const queueIncMailStatusResponse = await db.runSqlRow(queueIncMailStatus);
        if (!queueIncMailStatusResponse.status) {
            Log.errorLog({ error: queueIncMailStatusResponse.err });
            return { status: false, err: queueIncMailStatusResponse.err };
        }

        const queueCatAndSubCatResponse = await db.runSqlRow(defCatAndSubCat);
        if (!queueCatAndSubCatResponse.status) {
            Log.errorLog({ error: queueCatAndSubCatResponse.err });
            return { status: false, err: queueCatAndSubCatResponse.err };
        }
        return {
            status: true,
            data: response.data,
            defstatus: defStatusResponse.data,
            defpriority: defPriorityResponse.data.priority_id,
            defclose: defCloseResponse.data.map(item => item.status_id).join(','),
            queueIncMailStatus: queueIncMailStatusResponse.data.status_id,
            queueCatAndSubCat: queueCatAndSubCatResponse.data
        };
    } catch (err) {
        Log.errorLog({ error: err });
        return { status: false, data: null, err };
    }
};

serverModel.ticketData = function (emailAccData, mailData, prefixArr, queueData, defStatus, defPriority, conversationType, categoryAndSubCategory) {
    return new Promise((resolve, reject) => {
        try {
            // to email addresses
            let toemailAddresses = "";
            for (let i = 0; i < mailData.headerData.to.value.length; i++) {
                const email = mailData.headerData.to.value[i].address;
                toemailAddresses += email + ", ";
            }
            toemailAddresses = toemailAddresses.slice(0, -2);
            // cc email addresses
            var ccemailAddresses = ""
            if (mailData.headerData.cc) {
                for (let i = 0; i < mailData.headerData.cc.value.length; i++) {
                    const ccemail = mailData.headerData.cc.value[i].address;
                    ccemailAddresses += ccemail + ", ";
                }
                ccemailAddresses = ccemailAddresses.slice(0, -2);
            }

            const fromText = mailData.headerData.from.text;
            const matches = fromText.match(/([^<]+)<([^>]+)>/);
            if (matches && matches.length === 3) {
                var person_name = matches[1].trim();
            }

            var masterTable = `tms_ticket_master_${queueData.id}`;
            var conversationTable = `tms_conversation_master_${queueData.id}`;
            var attachmentTable = `tms_conversation_attachements_${queueData.id}`;

            let masterData = {
                // 'ticket_prefix': prefixArr.ticket_prefix,
                // 'ticket_unique_id': prefixArr.ticket_no,
                // 'ticket_id': prefixArr.ticket_series,
                'subject': mailData.headerData.subject !== undefined
                    ? mailData.headerData.subject
                    : null,
                'from_email': mailData.headerData.from['value'][0].address,
                'to_email': toemailAddresses,
                'cc_email': ccemailAddresses,
                'person_name': person_name,
                'status_id': defStatus,
                'priority_id': (categoryAndSubCategory && categoryAndSubCategory.priority !== undefined && categoryAndSubCategory.priority !== 0)
                    ? categoryAndSubCategory.priority
                    : defPriority,
                'queue_id': queueData.id,
                'is_assigned': (emailAccData.reopen_to_same_agent === 1 && mailData.replyTicketDataList && mailData.replyTicketDataList.is_assigned !== 0) ? mailData.replyTicketDataList[0].is_assigned : '0',
                'assigned_to': (emailAccData.reopen_to_same_agent === 1 && mailData.replyTicketDataList && mailData.replyTicketDataList.assigned_to !== 0) ? mailData.replyTicketDataList[0].assigned_to : '0',
                'happy_code': (queueData.is_happycode == 1) ? Math.floor(1000 + Math.random() * 9000) : 0,
                'incoming_mail_id': emailAccData.incoming_user_name,
                'mail_date': mailData.headerData.date,
                'is_auto': 1,
                'start_mode': (conversationType != "") ? conversationType : null,
                'is_new': 1,
                'category_id': (categoryAndSubCategory && categoryAndSubCategory.category_id !== undefined && categoryAndSubCategory.category_id !== '')
                    ? categoryAndSubCategory.category_id
                    : null,
                'subcategory_id': (categoryAndSubCategory && categoryAndSubCategory.sub_category_id !== undefined && categoryAndSubCategory.sub_category_id !== '')
                    ? categoryAndSubCategory.sub_category_id
                    : null,
            }
            console.log("masterTable", masterData)
            db.insertData(masterTable, masterData).
                then(function (response) {


                    console.log("resp", response, generateDateFormat())
                    if (response.status = true) {
                        const ticketNo = response.insertId;
                        let ticketSeries = emailAccData.ticket_prefix;
                        let ticket_prefix = [ticketSeries.substring(0, ticketSeries.indexOf('[')), ticketSeries.substring(ticketSeries.indexOf('['))];
                        var series = generateSeries(ticketSeries, ticketNo);
                        var series = series.data
                        const prefixArr = {
                            "ticket_prefix": ticket_prefix[0],
                            "ticket_series": series,
                            "ticket_no": ticketNo
                        }
                        // update ticket_id  or ticket_prefix in master table 
                        db.updateData(masterTable, { ticket_id: prefixArr.ticket_series, ticket_prefix: prefixArr.ticket_prefix }, { ticket_unique_id: response.insertId }).
                            then(function (updateResponse) {

                                Log.incErrorLog({ message: "Ticket ID updated successfully", data: updateResponse, time: generateDateFormat() });




                                let conversationData = {
                                    'conversation_date': mailData.headerData.date,
                                    'conversation_type': 'incomming mail',
                                    'ticket_unique_id': response.insertId,
                                    'ticket_id': prefixArr.ticket_series,
                                    'account_id': emailAccData.id,
                                    'from_email': mailData.headerData.from['value'][0].address,
                                    'to_email': toemailAddresses,
                                    'cc_email': ccemailAddresses,
                                    'person_name': person_name,
                                    'subject': mailData.headerData.subject !== undefined
                                        ? mailData.headerData.subject
                                        : null,
                                    'status_id': defStatus,
                                    'email_status': 'None',
                                    'priority_id': (categoryAndSubCategory && categoryAndSubCategory.priority !== undefined && categoryAndSubCategory.priority !== 0)
                                        ? categoryAndSubCategory.priority
                                        : defPriority,
                                    'queue_id': queueData.id,
                                    'queue_id': queueData.id,
                                    'email_message_id': mailData.headerData['message-id'],
                                    'json_file_name': mailData.msgId + ".json",
                                    'category_id': (categoryAndSubCategory && categoryAndSubCategory.category_id !== undefined && categoryAndSubCategory.category_id !== '')
                                        ? categoryAndSubCategory.category_id
                                        : null,
                                    'subcategory_id': (categoryAndSubCategory && categoryAndSubCategory.sub_category_id !== undefined && categoryAndSubCategory.sub_category_id !== '')
                                        ? categoryAndSubCategory.sub_category_id
                                        : null,
                                    'max_try': 3,
                                    'sms_max_try': 3,
                                    'uid': mailData.uid
                                }
                                db.insertData(conversationTable, conversationData)
                                    .then(function (conversationresponse) {
                                        console.log("conversationresponse", conversationresponse, generateDateFormat())
                                        if (conversationresponse.status == true) {
                                            if (mailData.attachmentData) {
                                                var attachmentData = [];
                                                for (const attachment of mailData.attachmentData) {
                                                    let filePath = mailData.fileFolderPath;
                                                    let fileName = path.basename(filePath, '.json');
                                                    // console.log("filename", fileName);

                                                    let finalUrl = path.join(path.dirname(filePath), fileName, attachment.filename);
                                                    // console.log("final url", finalUrl);
                                                    attachmentData.push({
                                                        'ticket_id': '"' + prefixArr.ticket_series + '"',
                                                        'ticket_unique_id': '"' + response.insertId + '"',
                                                        'conversation_id': '"' + conversationresponse.insertId + '"',
                                                        'attachement_name': '"' + attachment.filename + '"',
                                                        'content_type': '"' + attachment.contentType + '"',
                                                        'attachement_filepath': '"' + finalUrl + '"'
                                                    });
                                                }
                                            }
                                            if (attachmentData.length > 0) {
                                                db.insertDataBatch(attachmentTable, attachmentData)
                                                    .then(function (attachmentresponse) {
                                                        console.log("attachmentresponse", attachmentresponse, generateDateFormat())
                                                        if (attachmentresponse.status == true) {
                                                            resolve({ status: true, data: response.insertId });
                                                        }
                                                    }).catch(function (error) {
                                                        Log.errorLog({ error: error });
                                                        Log.errorLog({ error: attachmentData });
                                                        reject({ status: false, data: null, err: error });
                                                    });
                                            } else {
                                                resolve({ status: true, data: response.insertId, conversationdata: conversationresponse.insertId });
                                            }

                                        } else {
                                            Log.errorLog({ error: conversationresponse.err });
                                            reject({ status: false, data: null, err: conversationresponse.err });
                                        }
                                    })
                                    .catch(function (error) {
                                        Log.errorLog({ error: error });
                                        reject({ status: false, data: null, err: error });
                                    });

                                const fromEmail = mailData.headerData.from && mailData.headerData.from['value'] && mailData.headerData.from['value'][0] ? mailData.headerData.from['value'][0].address : '';
                                const toEmails = toemailAddresses ? toemailAddresses.split(',').map(email => email.trim()) : [];
                                const ccEmails = ccemailAddresses ? ccemailAddresses.split(',').map(email => email.trim()) : [];
                                const allEmails = [fromEmail, ...toEmails, ...ccEmails];
                                saveDataInAddressBook(allEmails, queueData.id).then((response) => {
                                })
                            })

                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getConversationType = function () {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `select id from tms_conversation_type_master t1 where t1.is_default = 1 and status = 1`;
            db.runSqlRow(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getQueueId = function () {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `select id,auto_assign_setting from tms_queue_master where status = 1`;
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getRuleMasterData = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t1.rule_id,t1.rule_name,t1.order_no,t1.match FROM tms_queue_rule_master_${queue_id} t1 ORDER BY t1.order_no asc`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getRuleCondition = function (queue_id, rule_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t1.* FROM tms_queue_rule_condition_1 t1
            WHERE rule_id = ${rule_id}`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.autoMailAssign = function (queue_id, auto_assign_setting) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `call autoMailAssign('${queue_id}','','${auto_assign_setting}')`
            console.log("sqlStr", sqlStr)
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        response.data = response.data.length > 0 ? response.data[0] : '';
                        resolve({ status: true, data: response.data });
                        // resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getTicketDetails = function (ticket_unique_id, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t1.* ,t1.from_email,t1.to_email,t1.cc_email,t1.subject,t1.priority_id,t2.user_name AS agent_name,t2.signature,t2.mobile_no as agent_mobile_number,t2.email as agent_email_id FROM tms_ticket_master_${queue_id} t1 left join tms_user_master t2 on t1.assigned_to = t2.user_id where t1.ticket_unique_id = ${ticket_unique_id}`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getRulesAction = function (queue_id, RuleId) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t1.action,t1.action_value FROM tms_queue_rule_action_${queue_id} t1 where t1.rule_id = ${RuleId}`;
            // console.log("sqlStr", sqlStr)
            db.runSqlRow(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        // console.log("response", response.data)
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.callRuleAction = function (queue_id, ticket_id, rule_id, action_name, action_value, acc_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = ` call performRulesAction('${action_name}','${queue_id}','${ticket_id}','${action_value}','${acc_id}')`;
            // console.log("sqlstr", sqlStr)
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getTemplateData = function (template_id, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t1.template_id,t1.template,t1.customer_email_subject,t1.user_email_subject,t1.customer_email_template,t1.user_email_template,t1.customer_sms_template,t1.customer_wp_template,t1.user_sms_template,t1.user_wp_template FROM tms_queue_template_${queue_id} t1
            WHERE t1.status = 1 and t1.template_id = ${template_id}`;
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.setEmailSmsTemplate = function (tempType, templateData = '', ticketDetails = '', mailData = '', emailidData = '', dynamic_master_name) {
    return new Promise(async (resolve, reject) => {
        try {
            if (tempType == "mail") {
                try {
                    const { headerData, bodyData } = mailData;
                    if (typeof bodyData == 'string') {
                        var conversation = Buffer.from(bodyData, 'base64').toString('utf-8');
                        // conversation = conversation.replace(/\n/g, '<br>')
                    } else {
                        var conversation = '';
                    }
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    const createdDate = moment(ticketDetails[0].created_date);
                    const currentTime = moment();
                    const duration = moment.duration(currentTime.diff(createdDate));
                    const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
                    let dataArray = {
                        ticket_id: ticketDetails[0].ticket_id,
                        ticket_unique_id: ticketDetails[0].ticket_unique_id,
                        email_message: conversation,
                        agent_name: ticketDetails[0].agent_name,
                        agent_mobile_number: ticketDetails[0].agent_mobile_number,
                        signature: ticketDetails[0].signature,
                        cc_email: ticketDetails[0].cc_email,
                        mobile_no: ticketDetails[0].mobile_no,
                        last_updated_on: generateDateFormat(ticketDetails[0].last_updated_on),
                        person_name: ticketDetails[0].person_name,
                        subject: headerData.subject,
                        to_email: headerData.to.text,
                        from_email: headerData.from.text,
                        happy_code: ticketDetails[0].happy_code,
                        duration: durationFormatted,
                        ticket_link: ticketDetails[0].ticket_link
                    };
                    // const baseStringKeys = Object.keys(templateArray[tempType][0]);
                    let dynData = [];
                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (ticketDetails[0].fieldName) {
                                const dynamicField = {};
                                dynamicField[fieldName] = ticketDetails[0].fieldName;
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };
                    var baseStringKeys = Object.keys(templateArray[tempType][0]);

                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replacvalue = [];
                    baseStringKeys.forEach((baseKey) => {
                        const key = baseKey.replace(/##/g, '').trim();
                        replacvalue.push(dataArray[key] || '');
                    });
                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';
                    templateData.forEach((temp) => {
                        emailSubject = temp.customer_email_subject.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => replacvalue[baseStringKeys.indexOf(match)]);
                        emailBody = temp.customer_email_template.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                            const index = baseStringKeys.indexOf(match);
                            const replacementValue = index !== -1 ? replacvalue[index] : '';
                            return replacementValue !== undefined ? replacementValue : '';
                        });

                    });
                    resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });
                } catch (error) {
                    console.error(error);
                }
            } else if (tempType == "user_mail") {
                try {
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    const createdDate = moment(templateData.created_date);
                    const currentTime = moment();
                    const duration = moment.duration(currentTime.diff(createdDate));
                    const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
                    let dataArray = {
                        ticket_id: templateData.ticket_id,
                        ticket_unique_id: templateData.ticket_unique_id,
                        email_message: '',
                        agent_name: templateData.user_name,
                        signature: templateData.signature.replace(/\n/g, '<br>'),
                        cc_email: templateData.cc_email,
                        mobile_no: templateData.mobile_no,
                        last_updated_on: templateData.last_updated_on,
                        person_name: templateData.person_name,
                        subject: templateData.subject,
                        to_email: templateData.to_email,
                        from_email: templateData.from_email,
                        happy_code: templateData.happy_code,
                        duration: durationFormatted,
                        ticket_link: templateData.ticket_link
                    };

                    let dynData = [];
                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (templateData[fieldName]) {
                                const dynamicField = {};
                                dynamicField[fieldName] = templateData[fieldName];
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };
                    var baseStringKeys = Object.keys(templateArray[tempType][0]);

                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replacvalue = [];
                    baseStringKeys.forEach((baseKey) => {
                        const key = baseKey.replace(/##/g, '').trim();
                        replacvalue.push(dataArray[key] || '');
                    });
                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';
                    emailSubject = templateData.user_email_subject.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => replacvalue[baseStringKeys.indexOf(match)]);
                    emailBody = templateData.user_email_template.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                        const index = baseStringKeys.indexOf(match);
                        const replacementValue = index !== -1 ? replacvalue[index] : '';
                        return replacementValue !== undefined ? replacementValue : '';
                    });
                    resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });

                } catch (error) {
                    console.error(error);
                }
            } else if (tempType == "user_sms") {
                try {
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    const createdDate = moment(templateData.created_date);
                    const currentTime = moment();
                    const duration = moment.duration(currentTime.diff(createdDate));
                    const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
                    let dataArray = {
                        ticket_id: templateData.ticket_id,
                        ticket_unique_id: templateData.ticket_unique_id,
                        email_message: '',
                        agent_name: templateData.user_name,
                        signature: templateData.signature.replace(/\n/g, '<br>'),
                        cc_email: templateData.cc_email,
                        mobile_no: templateData.mobile_no,
                        last_updated_on: generateDateFormat(templateData.last_updated_on),
                        person_name: templateData.person_name,
                        subject: templateData.subject,
                        to_email: templateData.to_email,
                        from_email: templateData.from_email,
                        happy_code: templateData.happy_code,
                        duration: durationFormatted,
                        ticket_link: templateData.ticket_link
                    };

                    let dynData = [];
                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (templateData[fieldName]) {
                                const dynamicField = {};
                                dynamicField[fieldName] = templateData[fieldName];
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };

                    var baseStringKeys = Object.keys(templateArray[tempType][0]);

                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replacvalue = [];
                    baseStringKeys.forEach((baseKey) => {
                        const key = baseKey.replace(/##/g, '').trim();
                        replacvalue.push(dataArray[key] || '');
                    });
                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';

                    smsBody = templateData.user_sms_template.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                        const index = baseStringKeys.indexOf(match);
                        const replacementValue = index !== -1 ? replacvalue[index] : '';
                        return replacementValue !== undefined ? replacementValue : '';
                    });
                    resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });

                } catch (error) {
                    console.error(error);
                }
            } else if (tempType == "agent_escalation_mail") {
                try {
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    const createdDate = moment(templateData.created_date);
                    const currentTime = moment();
                    const duration = moment.duration(currentTime.diff(createdDate));
                    const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
                    let dataArray = {
                        ticket_id: templateData.ticket_id,
                        ticket_unique_id: templateData.ticket_unique_id,
                        email_message: '',
                        agent_name: templateData.user_name,
                        signature: templateData.signature.replace(/\n/g, '<br>'),
                        cc_email: templateData.cc_email,
                        mobile_no: templateData.mobile_no,
                        last_updated_on: generateDateFormat(templateData.last_updated_on),
                        person_name: templateData.person_name,
                        subject: templateData.subject,
                        to_email: templateData.to_email,
                        from_email: templateData.from_email,
                        happy_code: templateData.happy_code,
                        duration: durationFormatted,
                        ticket_link: templateData.ticket_link
                    };

                    let dynData = [];
                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (templateData[fieldName]) {
                                const dynamicField = {};
                                dynamicField[fieldName] = templateData[fieldName];
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };

                    var baseStringKeys = Object.keys(templateArray[tempType][0]);

                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replacvalue = [];
                    baseStringKeys.forEach((baseKey) => {
                        const key = baseKey.replace(/##/g, '').trim();
                        replacvalue.push(dataArray[key] || '');
                    });
                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';

                    emailSubject = templateData.agent_email_subject.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => replacvalue[baseStringKeys.indexOf(match)]);
                    emailBody = templateData.agent_email_template.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                        const index = baseStringKeys.indexOf(match);
                        const replacementValue = index !== -1 ? replacvalue[index] : '';
                        return replacementValue !== undefined ? replacementValue : '';
                    });
                    resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });

                } catch (error) {
                    console.error(error);
                }
            } else if (tempType == "customer_wp") {
                try {
                    const { headerData, bodyData } = mailData;
                    if (typeof bodyData == 'string') {
                        var conversation = Buffer.from(bodyData, 'base64').toString('utf-8');
                    } else {
                        var conversation = '';
                    }
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    const createdDate = moment(ticketDetails[0].created_date);
                    const currentTime = moment();
                    const duration = moment.duration(currentTime.diff(createdDate));
                    const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
                    let dataArray = {
                        ticket_id: ticketDetails[0].ticket_id,
                        ticket_unique_id: ticketDetails[0].ticket_unique_id,
                        email_message: conversation,
                        agent_name: ticketDetails[0].agent_name,
                        agent_mobile_number: ticketDetails[0].agent_mobile_number,
                        signature: ticketDetails[0].signature,
                        cc_email: ticketDetails[0].cc_email,
                        mobile_no: ticketDetails[0].mobile_no,
                        last_updated_on: generateDateFormat(ticketDetails[0].last_updated_on),
                        person_name: ticketDetails[0].person_name,
                        subject: headerData.subject,
                        to_email: headerData.to.text,
                        from_email: headerData.from.text,
                        happy_code: ticketDetails[0].happy_code,
                        duration: durationFormatted,
                        ticket_link: ticketDetails[0].ticket_link
                    };

                    let dynData = [];
                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (templateData[fieldName]) {
                                const dynamicField = {};
                                dynamicField[fieldName] = templateData[fieldName];
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };

                    var baseStringKeys = Object.keys(templateArray[tempType][0]);

                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replacvalue = [];
                    baseStringKeys.forEach((baseKey) => {
                        const key = baseKey.replace(/##/g, '').trim();
                        replacvalue.push(dataArray[key] || '');
                    });
                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';

                    smsBody = templateData.customer_wp_template.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                        const index = baseStringKeys.indexOf(match);
                        const replacementValue = index !== -1 ? replacvalue[index] : '';
                        return replacementValue !== undefined ? replacementValue : '';
                    });
                    console.log("smsBody", smsBody)
                    resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });

                } catch (error) {
                    console.error(error);
                }
            } else if (tempType == "customer_sms") {
                try {
                    const { headerData, bodyData } = mailData;
                    if (typeof bodyData == 'string') {
                        var conversation = Buffer.from(bodyData, 'base64').toString('utf-8');
                        conversation = conversation.replace(/\n/g, '<br>')
                    } else {
                        var conversation = '';
                    }
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    const createdDate = moment(ticketDetails[0].created_date);
                    const currentTime = moment();
                    const duration = moment.duration(currentTime.diff(createdDate));
                    const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');
                    let dataArray = {
                        ticket_id: ticketDetails[0].ticket_id,
                        ticket_unique_id: ticketDetails[0].ticket_unique_id,
                        Email_Message: conversation,
                        Agent_Name: '',
                        signature: '',
                        cc_email: ticketDetails[0].cc_email,
                        mobile_no: ticketDetails[0].mobile_no,
                        last_updated_on: generateDateFormat(ticketDetails[0].last_updated_on),
                        person_name: ticketDetails[0].person_name,
                        subject: headerData.subject,
                        to_email: headerData.to.text,
                        Queue_EmailId: headerData.from.text,
                        duration: durationFormatted,
                        happy_code: ticketDetails[0].happy_code
                    };

                    let dynData = [];
                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (templateData[fieldName]) {
                                const dynamicField = {};
                                dynamicField[fieldName] = templateData[fieldName];
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };
                    var baseStringKeys = Object.keys(templateArray[tempType][0]);
                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replacvalue = [];
                    baseStringKeys.forEach((baseKey) => {
                        const key = baseKey.replace(/##/g, '').trim();
                        replacvalue.push(dataArray[key] || '');
                    });
                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';
                    templateData.forEach((temp) => {
                        smsBody = temp.customer_sms_template.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                            const index = baseStringKeys.indexOf(match);
                            const replacementValue = index !== -1 ? replacvalue[index] : '';
                            return replacementValue !== undefined ? replacementValue : '';
                        });

                    });
                    resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });

                } catch (error) {
                    console.error(error);
                }
            }
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }

    })
}

serverModel.setEmailSmsTemplateBulkEscalation = function (tempType, templateData = '', dynamic_master_name, bulkTemplate, bulkTemplateSubject) {
    return new Promise(async (resolve, reject) => {
        try {
            if (tempType == "user_mail") {
                try {
                    const dynamicFormData = await getdynamicFormData(dynamic_master_name);
                    let dataArray = { ...templateData }
                    Object.values(dataArray).forEach(data => {

                        const createdDate = moment(data.created_date);
                        const currentTime = moment();
                        const duration = moment.duration(currentTime.diff(createdDate));
                        const durationFormatted = moment.utc(duration.asMilliseconds()).format('HH:mm:ss');

                        data.agent_name = data.user_name;
                        data.duration = durationFormatted
                    });
                    let dynData = [];

                    if (dynamicFormData.data.length > 0) {
                        for (let i = 0; i < dynamicFormData.data.length; i++) {
                            const val = dynamicFormData.data[i];
                            const fieldName = val.field_name;
                            if (templateData[fieldName]) {
                                const dynamicField = {};
                                dynamicField[fieldName] = templateData[fieldName];
                                dynData.push(dynamicField);
                            }
                        }
                    }
                    dataArray = { ...dataArray, ...Object.assign({}, ...dynData) };
                    baseStringKeys = Object.keys(templateArray[tempType][0]);
                    if (dynamicFormData.status === true) {
                        const dynamicFieldNames = dynamicFormData.data.map((data) => "##" + data.field_name + "##");
                        baseStringKeys.push(...dynamicFieldNames);
                    }
                    const replaceValues = [];
                    Object.values(dataArray).forEach(data => {
                        baseStringKeys.forEach(baseKey => {
                            const key = baseKey.replace(/##/g, '').trim();
                            const value = data[key] || '';
                            replaceValues.push(value);
                        });
                    });

                    var emailSubject = '';
                    var emailBody = '';
                    var smsBody = '';
                    emailSubject = bulkTemplateSubject.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => replaceValues[baseStringKeys.indexOf(match)]);

                    // emailBody = bulkTemplate.replace(new RegExp(baseStringKeys.join('|'), 'g'), (match) => {
                    //     const key = match.replace(/##/g, '').trim();
                    //     const replacementValues = replaceValues[key];
                    //     return replacementValues ? replacementValues.join(', ') : '';
                    // });
                    this.BulKDataTemplate(bulkTemplate, dataArray).then((res) => {
                        emailBody = res.content
                        resolve({ status: true, emailSubject: emailSubject, emailBody: emailBody, smsBody: smsBody });
                    })


                } catch (error) {
                    console.error(error);
                }
            }
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.BulKDataTemplate = function (bulkTemplate, dataList) {
    console.log("bulkTemplate", bulkTemplate)
    console.log("dataList", dataList)
    return new Promise((resolve, reject) => {
        try {
            let contentAr = bulkTemplate.split("\n");
            let i = 0;
            let stread = 0;
            let itemloop = {};
            let itemReplace = {};

            contentAr.forEach((line) => {
                if (line.includes('**MULTIPLESCALATIONEND**')) {
                    stread = 0;
                }
                if (stread === 1) {
                    if (!itemloop[i]) {
                        itemloop[i] = '';
                    }
                    itemloop[i] += line;
                }
                if (line.includes('**MULTIPLESCALATIONSTART**')) {
                    i += 1;
                    stread = 1;
                }
            });
            const dataListArray = Object.values(dataList);
            let itemKeys = Object.keys(dataListArray[0] || {});
            let itemKeysN = itemKeys.map((itemK) => "##" + itemK + "##");
            Object.keys(itemloop).forEach((key) => {
                itemReplace[key] = '';
                Object.values(dataList).forEach((item) => {
                    let replaceValue = itemKeysN.reduce((acc, curr) => {
                        let key = curr.slice(2, -2);
                        return acc.replace(new RegExp(curr, 'g'), item[key]);
                    }, itemloop[key]);
                    itemReplace[key] += replaceValue;
                });
            });

            let cnt = '';
            let j = 1;
            let stopread = 0;
            contentAr.forEach((line) => {
                if (line.includes('**MULTIPLESCALATIONSTART**')) {
                    cnt += (itemReplace[j] ? itemReplace[j] : '');
                    stopread = 1;
                    j++;
                } else if (line.includes('**MULTIPLESCALATIONEND**')) {
                    stopread = 0;
                } else if (stopread === 0) {
                    cnt += line + "\r\n";
                }
            });
            resolve({ "content": cnt });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.insertBulkTicketData = function (masterName, insertData) {
    return new Promise((resolve, reject) => {
        try {
            db.insertData(masterName, insertData)
                .then(function (response) {
                    if (response.status == true) {
                        resolve({ status: true, data: response.insertId });
                    } else {
                        Log.errorLog(`error while saving mailData`);
                    }
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.saveMailData = function (type, conversationData, ticket_id, ticket_unq_id) {
    return new Promise((resolve, reject) => {
        try {
            var conversationTable = `tms_conversation_master_${conversationData.queue_id}`;
            let masterData = {
                'conversation_date': generateDateFormat(),
                'conversation_type': type,
                'ticket_unique_id': ticket_unq_id,
                'ticket_id': ticket_id,
                'from_email': conversationData.from_email,
                'person_name': conversationData.person_name,
                'mobile_no': conversationData.mobile_no,
                'to_email': conversationData.to_email,
                'cc_email': conversationData.cc_email,
                'subcategory_id': conversationData.subcategory_id,
                'category_id': conversationData.category_id,
                'account_id': conversationData.account_id,
                'email_status': conversationData.email_status,
                'whatsapp_status': conversationData.whatsapp_status,
                'subject': conversationData.subject !== undefined
                    ? conversationData.subject
                    : null,
                'status_id': conversationData.status_id,
                'priority_id': conversationData.priority_id,
                'queue_id': conversationData.queue_id,
                'email_message_id': conversationData.uuid,
                'json_file_name': conversationData.msg_id + ".json",
                'max_try': 3,
                'sms_max_try': 3,
                // 'uid':mailData.uid || 0
            };
            db.insertData(conversationTable, masterData)
                .then(function (conversationresponse) {
                    if (conversationresponse.status == true) {
                        resolve({ status: true, data: conversationresponse.insertId });
                    } else {
                        Log.errorLog(`error while saving mailData`);
                    }
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.outgoingMailData = function (queue_id, incomming_mail_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `SELECT t2.id,t2.server_type,t2.email,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,t2.outgoing_enable_SSL,t2.stop_outgoing_email,t1.queue_id FROM tms_queue_email t1
            LEFT JOIN tms_email_account t2 ON t1.outgoing_email_account = t2.id WHERE t2.stop_outgoing_email = 0 AND queue_id = ${queue_id} AND t1.incoming_email_account = ${incomming_mail_id}`;
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });

                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    Log.errorLog({ error: queue_id });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getNewEmailStatusData = function name(queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queue_id}`
            let ticketTblName = `tms_ticket_master_${queue_id}`;
            let sqlStr = `select t1.no_of_try,t1.footer_url,t3.footer_name,t3.footer_image_width,DATE_FORMAT(t1.conversation_date,'%Y-%m-%d') as folderdate,t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,
                          t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,
                          t1.queue_id,t1.conversation_id,t1.conversation_date,
                          t1.conversation_type,t1.ticket_unique_id,t1.ticket_id,t1.from_email,t1.to_email,t1.cc_email,t1.bcc_email,t1.account_id,t2.server_type,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email,
                          t1.subject,t1.email_status,t1.email_message_id,group_concat(t4.email_message_id SEPARATOR ' ')refrence_id,t1.json_file_name,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email,t2.is_aws,t2.user_for_aws,t2.outgoing_is_auth_enable,t2.outgoing_client_oauth2_id,t2.outgoing_client_secret,t2.outgoing_tenant_id,t2.outgoing_token,t2.outgoing_refresh_token from ${masterName} t1 
                          LEFT JOIN tms_email_account t2 ON t1.account_id = t2.id 
                          LEFT JOIN tms_queue_master  t3 ON t1.queue_id = t3.id
                          LEFT JOIN ${masterName} t4  ON t1.ticket_unique_id=t4.ticket_unique_id and t1.conversation_id>=t4.conversation_id AND t4.email_status != 'none' AND t4.email_message_id!=t1.email_message_id and t4.conversation_type != 'new ticket'
                          LEFT JOIN ${ticketTblName} t5 ON t1.ticket_unique_id = t5.ticket_unique_id
                          where t1.email_status = 'New' and t1.conversation_type != 'auto reply sms'  AND t5.is_junk = 0 AND t5.is_deleted_ticket = 0 AND (t1.no_of_try IS NULL OR t1.no_of_try <= t1.max_try)
                          GROUP BY DATE_FORMAT(t1.conversation_date,'%Y-%m-%d'),t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,
                          t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,
                          t1.queue_id,t1.conversation_date,
                          t1.conversation_type,t1.conversation_id,t1.ticket_unique_id,t1.ticket_id,t1.from_email,t1.to_email,t1.cc_email,t1.bcc_email,t1.account_id,t2.server_type,
                          t1.subject,t1.email_status,t1.json_file_name,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email
                          ORDER BY t1.conversation_id asc limit 50`;
            db.runSql(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getNewSMSStatusData = function name(queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queue_id}`
            let ticketTblName = `tms_ticket_master_${queue_id}`;
            let sqlStr = `select t1.sms_no_of_try,t3.sms_api_method,t3.sms_api_headers,t3.sms_api_body,t3.wp_api,t3.sms_api,t1.footer_url,t3.footer_name,t3.footer_image_width,DATE_FORMAT(t1.conversation_date,'%Y-%m-%d') as folderdate,t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,
                          t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,
                          t1.queue_id,t1.conversation_id,t1.mobile_no,t1.conversation_date,
                          t1.conversation_type,t1.ticket_unique_id,t1.ticket_id,t1.from_email,t1.to_email,t1.cc_email,t1.bcc_email,t1.account_id,t2.server_type,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email,
                          t1.subject,t1.email_status,t1.email_message_id,group_concat(t4.email_message_id SEPARATOR ' ')refrence_id,t1.json_file_name,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email from ${masterName} t1 
                          LEFT JOIN tms_email_account t2 ON t1.account_id = t2.id 
                          LEFT JOIN tms_queue_master  t3 ON t1.queue_id = t3.id
                          LEFT JOIN ${masterName} t4  ON t1.ticket_unique_id=t4.ticket_unique_id and t1.conversation_id>=t4.conversation_id AND t4.email_status != 'none' AND t4.email_message_id!=t1.email_message_id and t4.conversation_type != 'new ticket'
                           LEFT JOIN ${ticketTblName} t5 ON t1.ticket_unique_id = t5.ticket_unique_id
                          where t1.sms_status = 'New' and (t1.conversation_type = 'auto reply sms' or t1.conversation_type = 'escalation matrix') AND t5.is_junk = 0 AND t5.is_deleted_ticket = 0 AND (t1.sms_no_of_try IS NULL OR t1.sms_no_of_try <= t1.sms_max_try)
                          GROUP BY DATE_FORMAT(t1.conversation_date,'%Y-%m-%d'),t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,
                          t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,
                          t1.queue_id,t1.conversation_date,
                          t1.conversation_type,t1.conversation_id,t1.ticket_unique_id,t1.ticket_id,t1.from_email,t1.to_email,t1.cc_email,t1.bcc_email,t1.account_id,t2.server_type,
                          t1.subject,t1.email_status,t1.json_file_name,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email
                          ORDER BY t1.conversation_id asc`;
            db.runSql(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getNewWhatsappStatusData = function name(queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queue_id}`
            let ticketTblName = `tms_ticket_master_${queue_id}`;
            let sqlStr = `select t1.sms_no_of_try,t3.sms_api,t3.wp_api,t1.footer_url,t3.footer_name,t3.footer_image_width,DATE_FORMAT(t1.conversation_date,'%Y-%m-%d') as folderdate,t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,
                          t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,
                          t1.queue_id,t1.conversation_id,t1.mobile_no,t1.conversation_date,
                          t1.conversation_type,t1.ticket_unique_id,t1.ticket_id,t1.from_email,t1.to_email,t1.cc_email,t1.bcc_email,t1.account_id,t2.server_type,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email,
                          t1.subject,t1.email_status,t1.email_message_id,group_concat(t4.email_message_id SEPARATOR ' ')refrence_id,t1.json_file_name,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email from ${masterName} t1 
                          LEFT JOIN tms_email_account t2 ON t1.account_id = t2.id 
                          LEFT JOIN tms_queue_master  t3 ON t1.queue_id = t3.id
                          LEFT JOIN ${masterName} t4  ON t1.ticket_unique_id=t4.ticket_unique_id and t1.conversation_id>=t4.conversation_id AND t4.email_status != 'none' AND t4.email_message_id!=t1.email_message_id and t4.conversation_type != 'new ticket'
                          LEFT JOIN ${ticketTblName} t5 ON t1.ticket_unique_id = t5.ticket_unique_id
                          where t1.whatsapp_status = 'New' and t1.conversation_type = 'auto reply whatsapp' AND t5.is_junk = 0 AND t5.is_deleted_ticket = 0  AND (t1.sms_no_of_try IS NULL OR t1.sms_no_of_try <= t1.sms_max_try)
                          GROUP BY DATE_FORMAT(t1.conversation_date,'%Y-%m-%d'),t3.block_email_for_ticket_generate,t3.block_email_for_auto_reply,
                          t3.block_domains_for_ticket_generate,t3.block_domains_for_auto_reply,
                          t1.queue_id,t1.conversation_date,
                          t1.conversation_type,t1.conversation_id,t1.ticket_unique_id,t1.ticket_id,t1.from_email,t1.to_email,t1.cc_email,t1.bcc_email,t1.account_id,t2.server_type,
                          t1.subject,t1.email_status,t1.json_file_name,t2.outgoing_user_name,t2.outgoing_password,t2.outgoing_mail_server,t2.outgoing_mail_server_port,
                          t2.outgoing_enable_SSL,t2.stop_outgoing_email
                          ORDER BY t1.conversation_id asc`;
            db.runSql(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getReferenceData = function (reply_to, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queue_id}`
            let TicketMasterName = `tms_ticket_master_${queue_id}`
            // let replyToValues = reply_to.map(value => `'${value}'`).join(',');
            let replyToValues;
            if (Array.isArray(reply_to)) {
                replyToValues = reply_to.map(value => `'${value}'`).join(',');
            } else {
                replyToValues = `'${reply_to}'`;
            }
            let sqlStr = `SELECT t1.ticket_unique_id FROM ${masterName} t1 
            LEFT JOIN ${TicketMasterName} t2 ON t1.ticket_unique_id = t2.ticket_unique_id
            WHERE t1.email_message_id in (${replyToValues}) order by conversation_id desc`;
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getTicketIdRefrenceData = function (queue_id, ticketUnqId) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queue_id}`
            let TicketMasterName = `tms_ticket_master_${queue_id}`
            let sqlStr = `SELECT t1.ticket_unique_id,t1.status_id, DATE_FORMAT(t1.conversation_date,'%Y-%m-%d %h:%i:%s') AS conversation_date,conversation_id,t2.assigned_to,t2.is_assigned 
            FROM ${masterName} t1 
            LEFT JOIN ${TicketMasterName} t2 ON t1.ticket_unique_id = t2.ticket_unique_id
            WHERE t1.ticket_unique_id = ${ticketUnqId}
            ORDER BY conversation_id DESC LIMIT 1`;
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.getQueueCloseStatus = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterTble = `tms_queue_status_${queue_id}`;
            let sqlStr = `SELECT t1.status_id FROM ${masterTble} t1
            WHERE t1.is_close_status = 1`;
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getConversationData = function (conversation_id, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterTble = `tms_conversation_master_${queue_id}`;
            let sqlStr = `SELECT * FROM ${masterTble} t1
            WHERE t1.conversation_id = ${conversation_id}`;
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.saveReplyToMialData = function (conversationData, mailData, emailIdData, ticketUnqId, status_id = '') {
    return new Promise((resolve, reject) => {
        try {
            // to email addresses
            let toemailAddresses = "";
            for (let i = 0; i < mailData.headerData.to.value.length; i++) {
                const email = mailData.headerData.to.value[i].address;
                toemailAddresses += email + ", ";
            }
            toemailAddresses = toemailAddresses.slice(0, -2);

            // cc email addresses
            var ccemailAddresses = ""
            if (mailData.headerData.cc) {
                for (let i = 0; i < mailData.headerData.cc.value.length; i++) {
                    const ccemail = mailData.headerData.cc.value[i].address;
                    ccemailAddresses += ccemail + ", ";
                }
                ccemailAddresses = ccemailAddresses.slice(0, -2);
            }
            var conversationTable = `tms_conversation_master_${emailIdData.queue_id}`;
            var attachmentTable = `tms_conversation_attachements_${emailIdData.queue_id}`;
            let conversationTableData = {
                'conversation_date': mailData.headerData.date,
                'conversation_type': 'incomming mail',
                'ticket_unique_id': ticketUnqId,
                'ticket_id': conversationData.ticket_id,
                'mobile_no': conversationData.mobile_no,
                'email_uid': conversationData.email_uid,
                'account_id': emailIdData.id,
                'from_email': mailData.headerData.from['value'][0].address,
                'to_email': toemailAddresses,
                'cc_email': ccemailAddresses,
                'bcc_email': conversationData.bcc_email,
                'subject': mailData.headerData.subject !== undefined
                    ? mailData.headerData.subject
                    : null,
                'status_id': (status_id != "") ? status_id : conversationData.status_id,
                'category_id': conversationData.category_id,
                'subcategory_id': conversationData.subcategory_id,
                'email_status': 'None',
                'priority_id': conversationData.priority_id,
                'queue_id': emailIdData.queue_id,
                'email_message_id': mailData.headerData['message-id'],
                'json_file_name': mailData.msgId + ".json",
            }
            db.insertData(conversationTable, conversationTableData)
                .then(function (conversationresponse) {
                    if (conversationresponse.status == true) {
                        if (mailData.attachmentData) {
                            var attachmentData = [];
                            for (const attachment of mailData.attachmentData) {
                                let filePath = mailData.fileFolderPath;
                                let fileName = path.basename(filePath, '.json');
                                let finalUrl = path.join(path.dirname(filePath), fileName, attachment.filename);
                                attachmentData.push({
                                    'ticket_id': '"' + conversationData.ticket_id + '"',
                                    'ticket_unique_id': '"' + ticketUnqId + '"',
                                    'conversation_id': '"' + conversationresponse.insertId + '"',
                                    'attachement_name': '"' + attachment.filename + '"',
                                    'content_type': '"' + attachment.contentType + '"',
                                    'attachement_filepath': '"' + finalUrl + '"'
                                });
                            }
                        }
                        if (attachmentData.length > 0) {
                            db.insertDataBatch(attachmentTable, attachmentData)
                                .then(function (attachmentresponse) {
                                    if (attachmentresponse.status == true) {
                                        resolve({ status: true, data: conversationresponse.insertId });
                                    }
                                }).catch(function (error) {
                                    Log.errorLog({ error: error });
                                    reject({ status: false, data: null, err: error });
                                });
                        } else {
                            resolve({ status: true });
                        }

                    } else {
                        Log.errorLog({ error: conversationresponse.err });
                        reject({ status: false, data: null, err: conversationresponse.err });
                    }
                })
                .catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getQueueIncommingMailStatus = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterTble = `tms_queue_status_${queue_id}`;
            let sqlStr = `SELECT t1.status_id FROM ${masterTble} t1
            WHERE t1.incomming_mail_status = 1`;
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.updateMailStatusAfterClose = function (queue_id, status_id, ticketUnqId, reopenDate) {
    return new Promise((resolve, reject) => {
        try {
            let mstTblName = `tms_ticket_master_${queue_id}`;

            let updArr = {
                'status_id': `${status_id}`,
                'reopen_date': `${reopenDate}`,
                'is_new': 1
            };

            let whArr = {
                'ticket_unique_id': `${ticketUnqId}`
            };

            db.updateData(`${mstTblName}`, updArr, whArr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true });
                    } else {
                        Log.outErrorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.outErrorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.updateNewStatus = function (ticketUnqId, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let mstTblName = `tms_ticket_master_${queue_id}`;

            let updArr = {
                'is_new': 1
            };

            let whArr = {
                'ticket_unique_id': `${ticketUnqId}`
            };
            db.updateData(`${mstTblName}`, updArr, whArr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true });
                    } else {
                        Log.outErrorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.outErrorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}


serverModel.updateTicketEscalation = function (ticketUnqId, escalationLevel, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let mstTblName = `tms_ticket_master_${queue_id}`;

            let updArr = {
                'escalation_id': escalationLevel,
                'last_escalation_on': generateDateFormat()
            };

            let whArr = {
                'ticket_unique_id': `${ticketUnqId}`
            };
            db.updateData(`${mstTblName}`, updArr, whArr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true });
                    } else {
                        Log.outErrorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.outErrorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.escalationProcess = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `call emailEscalation('${queue_id}')`
            db.runSql(sqlStr).
                then(function (response) {
                    console.log("response", response)
                    if (response.status = true) {
                        response.data = response.data.length > 0 ? response.data[0] : '';
                        resolve({ status: true, data: response.data });
                        // resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

function getdynamicFormData(masterName) {
    return new Promise((resolve, reject) => {
        try {
            let sqlStr = `select field_name from ${masterName}`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

function saveDataInAddressBook(data, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            const dataStr = `'${data.join(',')}'`;
            let sqlStr = `call Split_string('${queue_id}',${dataStr})`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        response.data = response.data.length > 0 ? response.data[0] : '';
                        resolve({ status: true });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });

        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getStatusData = function (queueIncMailStatus, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_queue_status_${queue_id}`
            let templateTblNmae = `tms_queue_template_${queue_id}`
            let sqlStr = `select * from ${masterName} t1 left join ${templateTblNmae} t2 on t1.template_id = t2.template_id where t1.status_id = ${queueIncMailStatus}`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getBulkEscaltionTemplateData = function (tempId, queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_queue_template_${queue_id}`
            let sqlStr = `select * from ${masterName} where template_id = ${tempId}`
            db.runSql(sqlStr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true, data: response.data });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getStatusName = function (status_id, queueId) {
    let masterName = `tms_queue_status_${queueId}`
    return new Promise((resolve, reject) => {
        let sqlStr = `select status_name from ${masterName} where status_id = ${status_id}`
        db.runSqlRow(sqlStr).
            then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false });
                }
            }).
            catch(function (error) {
                Log.errorLog({ error: error });
                reject({ status: false, err: error });
            });
        try {
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });

}

serverModel.getTokenByUsername = function (incoming_user_name) {
    return new Promise((resolve, reject) => {
        try {
            let mstTblName = `tms_email_account`;

            let selectFields = ['token', 'refresh_token'];
            let whArr = {
                'incoming_user_name': `${incoming_user_name}`
            };

            db.selectData(mstTblName, selectFields, whArr)
                .then(function (response) {
                    if (response.status === true && response.data && response.data.length > 0) {
                        resolve({
                            status: true,
                            data: response.data[0] // assuming only one record per user
                        });
                    } else {
                        resolve({
                            status: false,
                            data: null,
                            message: "No data found"
                        });
                    }
                })
                .catch(function (error) {
                    Log.outErrorLog({ error: error });
                    reject({
                        status: false,
                        err: error
                    });
                });
        } catch (err) {
            Log.outErrorLog({ error: err });
            reject({
                status: false,
                err: err
            });
        }
    });
}


serverModel.saveToken = function (rf_token, access_token, incoming_user_name) {
    return new Promise((resolve, reject) => {
        try {
            let mstTblName = `tms_email_account`;

            let updArr = {
                'token': access_token,
                'refresh_token': rf_token
            };

            let whArr = {
                'incoming_user_name': `${incoming_user_name}`
            };
            db.updateData(`${mstTblName}`, updArr, whArr).
                then(function (response) {
                    if (response.status = true) {
                        resolve({ status: true });
                    } else {
                        Log.outErrorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.outErrorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.insertAttachmentData = function (data, queueId) {
    let masterName = `tms_conversation_attachements_${queueId}`
    return new Promise((resolve, reject) => {
        db.insertDataBatch(masterName, data).
            then(function (response) {
                if (response.status = true) {
                    resolve({ status: true, data: response.insertId });
                }
            }).catch(function (error) {
                reject({ status: false, data: null, err: error });
            });

    })
}

function generateDateFormat(dateVal) {
    if (dateVal == undefined) {
        // const now = new Date();
        // console.log("time",timestamp('DD-MM-YYYY hh:mm:ss:iii'))
        // const year = now.getUTCFullYear();
        // const month = ('0' + (now.getUTCMonth() + 1)).slice(-2);
        // const day = ('0' + now.getUTCDate()).slice(-2);
        // const hours = ('0' + now.getUTCHours()).slice(-2);
        // const minutes = ('0' + now.getUTCMinutes()).slice(-2);
        // const seconds = ('0' + now.getUTCSeconds()).slice(-2);
        // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        return timestamp('YYYY-MM-DD hh:mm:ss');
    } else {
        const dateString = dateVal;
        const date = new Date(dateString);
        const year = date.getUTCFullYear();
        const month = ('0' + (date.getUTCMonth() + 1)).slice(-2);
        const day = ('0' + date.getUTCDate()).slice(-2);
        const hours = ('0' + date.getUTCHours()).slice(-2);
        const minutes = ('0' + date.getUTCMinutes()).slice(-2);
        const seconds = ('0' + date.getUTCSeconds()).slice(-2);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

}

serverModel.updateSmsApiHeaders = function (sms_api_headers) {
    return new Promise((resolve, reject) => {
        try {
            let masterTable = `tms_queue_master`;

            let updArr = {
                'sms_api_headers': sms_api_headers
            };

            let whArr = {
                // 'id': queue_id
            };

            db.updateData(masterTable, updArr, whArr)
                .then(function (response) {
                    if (response.status === true) {
                        resolve({ status: true });
                    } else {
                        Log.errorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                })
                .catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
};


serverModel.getLastReadDate = function (queue_id) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_queue_master`
            let sqlStr = `select DATE_FORMAT(last_read_date,'%Y-%m-%d') as last_read_date from ${masterName} t1 where t1.id = ${queue_id}`
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status == true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    });
}

serverModel.getProcessedUIDs = function (queue_id, date) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queue_id}`
            let sqlStr = `SELECT t2.uid FROM ${masterName} t2 WHERE date(t2.conversation_date) = '${date}' AND t2.uid != 0`
            db.runSql(sqlStr).then(function (response) {
                if (response.status == true) {
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.updateLastReadDate = function (queue_id, date) {
    return new Promise((resolve, reject) => {
        try {
            let mstTblName = `tms_queue_master`;

            let updArr = {
                'last_read_date': `${date}`
            };

            let whArr = {
                'id': `${queue_id}`
            };

            db.updateData(`${mstTblName}`, updArr, whArr).
                then(function (response) {
                    if (response.status == true) {
                        resolve({ status: true });
                    } else {
                        Log.outErrorLog({ error: response.err });
                        reject({ status: false, data: null, err: response.err });
                    }
                }).
                catch(function (error) {
                    Log.outErrorLog({ error: error });
                    reject({ status: false, data: null, err: error });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}

serverModel.checkMessageIdInDb = function (msgId, queueId) {
    return new Promise((resolve, reject) => {
        try {
            let masterName = `tms_conversation_master_${queueId}`
            let sqlStr = `select 1 from ${masterName} where email_message_id = '${msgId}' and conversation_type = 'incomming mail'`
            Log.incErrorLog(`Query is ${sqlStr}`)
            db.runSqlRow(sqlStr).then(function (response) {
                if (response.status == true) {
                    Log.incErrorLog(`checkMessageIdindb response is ${response.data}`)
                    resolve({ status: true, data: response.data });
                } else {
                    Log.errorLog({ error: response.err });
                    reject({ status: false, err: response.err });
                }
            }).
                catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({ status: false, err: error });
                });
        } catch (e) {
            Log.errorLog({ error: err });
            reject({ status: false, data: null, err: err });
        }
    })
}


serverModel.getTokenByUsername = function (incoming_user_name) {
    return new Promise((resolve, reject) => {
        try {
            let tableName = `tms_email_account`;
            let sqlStr = `SELECT token, refresh_token FROM ${tableName} WHERE incoming_user_name = '${incoming_user_name}'`;

            // Log.incErrorLog(`getTokenByUsername SQL: ${sqlStr}`);

            db.runSql(sqlStr)
                .then(function (response) {
                    if (response.status === true && response.data && response.data.length > 0) {
                        resolve({
                            status: true,
                            data: response.data[0]  // return first matching record
                        });
                    } else {
                        resolve({
                            status: false,
                            data: null,
                            message: "No token found for this username"
                        });
                    }
                })
                .catch(function (error) {
                    Log.errorLog({ error: error });
                    reject({
                        status: false,
                        err: error
                    });
                });
        } catch (err) {
            Log.errorLog({ error: err });
            reject({
                status: false,
                data: null,
                err: err
            });
        }
    });
}

var generateSeries = function (ticketSeries, ticketNo) {
    var res = '';
    res = ticketSeries.replace('[M]', new Date().toLocaleString('default', { month: 'short' }).toUpperCase());
    res = res.replace('[m]', (new Date().getMonth() + 1).toString().padStart(2, '0'));
    res = res.replace('[d]', new Date().getDate().toString().padStart(2, '0'));
    res = res.replace('[D]', new Date().toLocaleString('default', { weekday: 'short' }));
    res = res.replace('[Y]', new Date().getFullYear().toString());
    res = res.replace('[y]', new Date().getFullYear().toString().substr(-2));
    res = res.replace('[Y+1]', (new Date().getFullYear() + 1).toString());
    res = res.replace('[y+1]', (new Date().getFullYear() + 1).toString().substr(-2));
    var finalTicketSeries = res + ticketNo;
    if (finalTicketSeries.length > 20) {
        res = '0';
        ticketNo = '0';
        Log.errorLog("Ticket Prefix should not be greter than 20 characters");
        console.log(err, "Ticket Prefix should not be greter than 20 characters")
        return { status: false, err: "Ticket Prefix should not be greter than 20 characters" }
    } else {
        return { status: true, data: finalTicketSeries }
    }
}



module.exports = serverModel;