
(function (root) {

    var fetion = root.fetion = {};

    fetion.author = 'C.';

    fetion.version = '13.5.1001';

    fetion.debug = true;

    fetion.noConsole = function () {
        if (!this.debug)
            console.log = console.warn = console.error = new Function;
    };

    fetion.pcrun = function (command, data, loading, callback) {
        try {
            if (typeof callback !== 'function') {
                console.error(String.format('{0}: callback is not function.', command));
                return;
            }

            var instance = this;

            SM.ajax('HIS', command, '', data, function (status, txt, json) {

                try {
                    if (status == 200) {
                        callback.call(instance, json);
                    } else {
                        console.warn(String.format('exec {0} failed({1})', command, status));
                    }
                } catch (err1) {
                    console.error(String.format('callback of {0} error({1})', command, err1));
                }

            });

        } catch (err2) {
            console.error(String.format('exec {0} error({1})', command, err2));
        }
    };

    fetion.History = function () {
        /// <summary>
        /// 历史记录管理器实体
        /// </summary>

        // 初始界面是最近联系人
        this.nav = fetion.History.NAV.CONTACT_RECENT_LIST;

        // 自己的userid
        this.myself = 0;

        // 分页页大小
        this.pageSize = 30;

        // 联系人  最近|所有|分组|聊天记录
        this.contact = {
            recent: [],
            all: {},
            group: {},   // eg: {-1:{n:'未分组', cl:[]}}
            logs: {
                index: 0,   // 当前页索引
                size: 0,   // 页大小
                items: []   // 聊天记录，数组索引对应了页索引
            }
        };

        // 群
        this.group = {
            usual: [],
            thumb: []
        };

        // 讨论组
        this.discus = [];
    };

    fetion.History.NAV = {
        CONTACT_RECENT_LIST: 0,
        CONTACT_ALL_LIST: 1,
        CONTACT_CHATLOG: 2,
        DISCUS_CHATLOG: 3,
        GROUP_CHATLOG: 4
    };

    fetion.History.prototype.getRecentContacts = function (loading, callback) {
        var instance = this;

        fetion.pcrun('AsyncQueryRecentContactList', null, loading, function (result) {
            instance.myself = result.ru;
            instance.contact.recent = result.rv;

            callback.call(instance);
        });
    };

    fetion.History.prototype.getAllContacts = function (loading, callback) {
        var contact = this.contact;

        fetion.pcrun('AsyncQueryContactList', null, loading, function (result) {
            _.each(result, function (c) {
                var gs = c.gs, gsArr;

                if (gs.indexOf(';') != -1) {
                    gsArr = gs.split(';');

                } else {
                    gsArr = gs.split(',');
                }

                _.each(gsArr, function (gid) {
                    if (!contact.group[gid]) {
                        contact.group[gid] = {};
                        contact.group[gid].cs = [];
                    }

                    contact.group[gid].cs.push(c);
                });

                contact.all[c.uid] = c;
            });

            callback.call(contact);
        });
    };

    fetion.History.prototype.getContactGroups = function (loading, callback) {
        var instance = this;
        var group = instance.contact.group;

        fetion.pcrun('AsyncQueryContactGroupList', null, loading, function (result) {
            _.each(result, function (g) {
                if (g.id == 9999995 || g.id == 9999998)
                    return;

                group[g.id] = {};
                group[g.id].cs = [];

                switch (g.id) {
                    case '': group[g.id].n = '未分组'; break;
                    case 9999991: group[g.id].n = '聊友'; break;
                    case 9999992: group[g.id].n = '陌生人'; break;
                    case 9999998: group[g.id].n = '黑名单'; break;
                    case 9999995: group[g.id].n = '通讯录'; break;
                    case 9999997: group[g.id].n = '推荐好友'; break;
                    default: group[g.id].n = g.n; break;
                }
            });

            callback.call(group);
        });
    };

    fetion.History.prototype.getRecentGroups = function (loading, callback) {
    };

    fetion.History.prototype.getGroups = function (loading, callback) {
        var instance = this;

        fetion.pcrun('AsyncQueryGroupList', null, loading, function (result) {
            _.each(result, function (item) {
                if (/^sip:DG/.test(item.uri)) {
                    instance.discus.push(item);

                } else if (/^sip:PG/.test(item.uri)) {
                    instance.group.usual.push(item);
                }
            });

            callback.call(instance);
        });
    };

    fetion.History.prototype.getDiscus = function () {

    };

    fetion.History.prototype.getSms = function () {

    };

    fetion.History.prototype.getOthers = function () {

    };

    fetion.History.prototype.getChatLog = function (yourself, pageIndex, loading, callback) {
        var instance = this;

        if (instance.contact.logs.length < pageIndex) {
            pageIndex = 0;
        }

        var logs = instance.contact.logs;
        var contacts = instance.contact.all;
        var data = {
            pageIndex: pageIndex,
            pageSize: instance.pageSize
        };

        fetion.pcrun('AsyncQueryRecentContactList', data, loading, function (result) {
            $.each(result, function (i, log) {
                log.date = new Date(log.dt);
                log.un = contacts[log.uid].n;

                var key = log.date.toLocaleDateString();
                logs[key] = logs[key] || [];
                logs[key].push(log);
            });

            callback.call(instance);
        });
    };

})(this);