/**
 * 消息统计。方便前端获取聊天的状态。
 */
"use strict";

var http = require('http');
var async = require('async');

var configFile = require('../include/commons').CONFIG_FILE;
var config = require('../resources/config/' + configFile);

var log = require('../util/log');
var wlyyRepo = require("./database/wlyy.db.js");
var imRepo = require("./database/im.db.js");

//--------------------About all chats--------------------
/**
 * 所有聊天列表。
 *
 * @param userId
 * @param handler
 */
exports.getChatList = function (userId, handler) {
    imRepo.execQuery({
        "sql": "SELECT uid,from_uid,from_gid,peer_uid,at_me,msg_type,last_content_type,last_content,new_msg_count,timestamp from msg_statistic WHERE uid = ?",
        "args": [userId],
        "handler": handler
    });
};

/**
 * 所有未读聊天记录数。
 *
 * @param userId
 * @param handler
 */
exports.getChatAllUnReadCount = function (userId, handler) {
    imRepo.execQuery({
        "sql": "SELECT new_msg_count from msg_statistic WHERE uid=? AND new_msg_count>0",
        "args": [userId],
        "handler": handler
    });
};

//--------------------About private chat summary--------------------
exports.updatePrivateChatSummary = function (userId, peerId, from, type, content, handler) {
    var uuid = userId + '_' + peerId;
    if (userId == from) {
        // 更新自身的统计信息
        var sql = "INSERT INTO msg_statistic (uid,uuid,from_uid,peer_uid,msg_type,last_content_type,last_content,new_msg_count) " +
            "VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE peer_uid=?,last_content_type=?,last_content=?";

        imRepo.execQuery({
            "sql": sql,
            "args": [userId, uuid, from, peerId, 1, type, content, 0, peerId, type, content],
            "handler": handler
        });
    } else {
        var sql = "INSERT INTO msg_statistic (uid,uuid,from_uid,peer_uid,msg_type,last_content_type,last_content,new_msg_count) " +
            "VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE peer_uid=?,last_content_type=?,last_content=?,new_msg_count=new_msg_count+1";
        // 更新对端的统计信息
        imRepo.execQuery({
            "sql": sql,
            "args": [userId, uuid, from, peerId, 1, type, content, 1, peerId, type, content],
            "handler": handler
        });
    }
};

exports.clearPrivateChatSummary = function (userId, peerId, handler) {
    var uuid = userId + '_' + peerId;
    imRepo.execQuery({
        "sql": "UPDATE msg_statistic SET new_msg_count='0' WHERE uuid=?",
        "args": [uuid],
        "handler": handler
    });
};

exports.getPrivateChatSummary = function (userId, peerId, handler) {
    var uuid = userId + '_' + peerId;
    imRepo.execQuery({
        "sql": "SELECT uid,from_uid,last_content_type,last_content,new_msg_count,timestamp from msg_statistic WHERE uuid = ?",
        "args": [uuid],
        "handler": handler
    });
};

exports.getPrivateChatAllUnReadCount = function (userId, handler) {
    imRepo.execQuery({
        "sql": "SELECT new_msg_count from msg_statistic WHERE uid = ? AND msg_type = 1 AND new_msg_count > 0",
        "args": [userId],
        "handler": handler
    });
};

/**
 * 最近聊天对象，如患者，医生与群等基本信息。
 *
 * @param userId
 * @param days
 * @param handler
 */
exports.getRecentChats = function (userId, days, handler) {
    var timespan = 60 * 60 * 24 * days; // 多少天内的联系对象
    var sql = "SELECT * FROM(" +
        "SELECT DISTINCT p.code code, p.name name, p.birthday birthday, p.sex sex, p.photo photo, ms.timestamp timestamp, 'patient' type " +
        "FROM im_new.msg_statistic ms, wlyy.wlyy_patient p " +
        "WHERE ms.uid = ? AND ms.uid = p.code AND " +
        "UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(ms.timestamp) < ? AND msg_type = 1" +

        " UNION " +

        "SELECT DISTINCT d.code code, d.name name, d.birthday birthday, d.sex sex, d.photo photo, ms.timestamp timestamp,'doctor' type " +
        "FROM im_new.msg_statistic ms, wlyy.wlyy_doctor d, (SELECT CASE WHEN ms1.timestamp > ms2.timestamp THEN ms1.id ELSE ms2.id END id " +
        "                                                   FROM msg_statistic ms1, msg_statistic ms2 " +
        "                                                   WHERE ms1.from_gid IS NULL AND ms2.from_gid IS NULL AND ms1.uid = ms2.peer_uid AND ms1.peer_uid = ms2.uid) x " +
        "WHERE x.id = ms.id AND ((ms.uid = ? AND ms.peer_uid = d.code) OR (ms.uid = d.code AND ms.peer_uid = ?)) AND UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(ms.timestamp) < ?" +

        " UNION " +

        "SELECT g.id code, g.name name, '' birthday, '' sex, '' photo, max(ms.timestamp) timestamp, 'type' ':group' " +
        "FROM im_new.msg_statistic ms, wlyy.wlyy_admin_team g, wlyy.wlyy_admin_team_member m, wlyy.wlyy_doctor d " +
        "WHERE d.code = ? AND d.code = m.doctor_code AND m.team_id = g.id AND g.id = ms.from_gid " +
        "   AND (ms.uid = d.code or ms.from_uid = d.code) AND UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(ms.timestamp) < ? group by g.id, g.name " +
        ") x ORDER BY timestamp DESC";

    imRepo.execQuery({
        "sql": sql,
        "args": [userId, timespan, userId, userId, timespan, userId, timespan],
        "handler": handler
    });
};

//--------------------About group chat summary--------------------
/**
 * 更新群聊统计摘要。
 *
 * @param userId
 * @param groupId
 * @param from
 * @param atMe
 * @param type
 * @param content
 * @param msgCountPlusOne
 * @param handler
 */
exports.updateGroupChatSummary = function (userId, groupId, from, atMe, type, content, msgCountPlusOne, handler) {
    var uuid = userId + '_' + groupId;
    if (msgCountPlusOne) {
        imRepo.execQuery({
            "sql": "INSERT INTO msg_statistic (uid,uuid,from_uid,from_gid,at_me,msg_type,last_content_type,last_content,new_msg_count) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE from_uid=?,at_me=?,last_content_type=?,last_content=?,new_msg_count=new_msg_count+1",
            "args": [userId, uuid, from, groupId, atMe, 2, type, content, 1, from, atMe, type, content],
            "handler": handler
        });
    } else {
        imRepo.execQuery({
            "sql": "INSERT INTO msg_statistic (uid,uuid,from_uid,from_gid,at_me,msg_type,last_content_type,last_content,new_msg_count) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE from_uid=?,at_me=?,last_content_type=?,last_content=?",
            "args": [userId, uuid, from, groupId, atMe, 2, type, content, 0, from, atMe, type, content],
            "handler": handler
        });
    }
};

exports.getGroupChatAllUnReadCount = function (userId, handler) {
    imRepo.execQuery({
        "sql": "SELECT new_msg_count from msg_statistic WHERE uid=? AND msg_type=2 AND new_msg_count>0",
        "args": [userId],
        "handler": handler
    });
};

exports.getGroupChatSummary = function (userId, groupId, handler) {
    var uuid = userId + '_' + groupId;
    imRepo.execQuery({
        "sql": "SELECT uid,from_uid,from_gid,at_me,last_content_type,last_content,new_msg_count,timestamp from msg_statistic WHERE uuid = ?",
        "args": [uuid],
        "handler": handler
    });
};

exports.clearGroupChatSummary = function clearGroupChatInfo(userId, groupId, handler) {
    var uuid = userId + '_' + groupId;
    imRepo.execQuery({
        "sql": "UPDATE msg_statistic SET new_msg_count='0' WHERE uuid=?",
        "args": [uuid],
        "handler": handler
    });
};

//--------------------Others--------------------
exports.getAppMsgAmount = function (userId, handler) {
    wlyyRepo.execQuery({
        "sql": "SELECT imei,token from wlyy_token WHERE user=?",
        "args": [userId],
        "handler": function (err, result) {
            if (err || result.length == 0) {
                handler(null, 0);
                return;
            }

            var options = {
                hostname: config.wlyyServerConfig.hostname,
                port: config.wlyyServerConfig.port,
                path: config.wlyyServerConfig.path,
                method: config.wlyyServerConfig.method,
                headers: {
                    'userAgent': '{"token":"' + result[0].token + '","uid":"' + userId + '","imei":"' + result[0].imei + '"}'
                }
            };

            var req = http.request(options, function (res) {
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    log.info('请求家庭医生平台: ', options.hostname + ":" + options.port + options.path);
                    log.info('家庭医生平台返回: ', chunk);

                    handler(null, JSON.parse(chunk));
                });
            });

            req.on('error', function (e) {
                log.error('家庭医生平台接口调用出错: ', e.message);

                handler(e, null);
            });

            req.end();
        }
    });
};

exports.getBadgeNumber = function (userId, handler) {
    var self = this;
    async.parallel([
            function (callback) {
                callback(null, 0);
            },

            function (callback) {
                self.getAppMsgAmount(userId, function (err, result) {
                    if (err) {
                        callback(null, 0);
                    } else {
                        var count = 0;
                        try {
                            count += result.data.healthIndex;
                            count += result.data.sign;
                            count += result.data.consultTeam;
                            callback(null, count);
                        } catch (e) {
                            callback(null, 0);
                        }
                    }
                });
            }],

        function (err, results) {
            var badge = 0;
            for (var index = 0; index < results.length; index++) {
                badge += results[index];
            }

            handler(null, badge);
        });
};
