(function() {
    'use strict';

    angular
        .module('appMessage')
        .directive('ngHistoryMsg', HistoryMsg);

    HistoryMsg.inject = ['$location', '$anchorScroll', '$filter', '$compile', '$timeout'];

    function HistoryMsg($location, $anchorScroll, $filter, $compile, $timeout) {
        var directive = {
            link: link,
            restrict: 'A',
            controller: ControllerController,
            scope: {
                msg: '=ngHistoryMsg',
                appContent: '=ngAppContent',
                count: '=ngCount',
                height: '=ngHeight'
            }
        };
        return directive;

        function link(scope, element, attrs) {

            var gotoBottom = function() {
                $location.hash("bottom");
                $anchorScroll();
            };

            var getFileName = function(item) {
                var arr = item.fileName.split("\\");
                return arr[arr.length - 1];
            };

            var getSuffix = function(item) {
                var arr = item.fileName.split(".");
                return '../img/file/' + arr[arr.length - 1] + '.png';
            };

            var getUserID = function() {
                var arr = scope.appContent.directory.user.split("\\");
                var userself = arr[arr.length - 2];
                return scope.msg.sender.indexOf(userself) !== -1;
            };

            var getFileSize = function(item) {
                var fileSize = item.length;
                if (fileSize > 1024 * 1024 * 1024)
                    return (Math.round(fileSize * 100 / (1024 * 1024 * 1024)) / 100).toString() + 'GB';
                else if (fileSize > 1024 * 1024)
                    return (Math.round(fileSize * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                else
                    return (Math.round(fileSize * 100 / 1024) / 100).toString() + 'KB';
            };

            var getFileInfo = function(item) {
                var file = '“' + getFileName(item) + '”' + '(' + getFileSize(item) + ')';
                var fileInfo = new Array('您取消了' + file + '的发送，文件传输失败。', '您取消接收' + file + '，文件传输失败。', '对方取消了' + file + '的发送。', '对方取消接收' + file + '，文件发送失败。', '您终止了' + file + '的发送。', '您终止了' + file + '的接收。', '对方中断了' + file + '的发送。', '对方中断了' + file + '的接收。', '对方取消在线传输，转为发送离线文件' + file + '。');
                return fileInfo;
            };

            var ifSelf = function(item) {
                return item.operatorName == scope.msg.sender;
            };

            var replaceSystemFace = function(content) {
                //匹配表情
                var g = (/\/\:([\w]+)/).exec(content);
                while (g !== null) {
                    scope.appContent.faceConfig.sys.forEach(function(element) {
                        content = content.replace(element.shortcut, '<img style="height:56px" src="local://' + scope.appContent.directory.base + element.image + '">');
                    }, this);
                    g = (/\/\:([\w]+)/).exec(content);
                }
                //匹配截图
                var g = (/\[image\-src=\"([\w\W]+?)\"\]/i).exec(content);
                while (g !== null) {
                    content = content.replace(g[0], function() {
                        scope["img_" + g[1]] = "local://" + scope.appContent.directory.received + g[1] + ".JPG";
                        var html = '<a class="thumbnail"' + '>' +
                            '<img ng-click="showImage(\'' + g[1] + '\')" ng-error="onFaceLoadError(\'' + g[1] + '\')" ng-load="scrollController()" style="max-width:300px;max-height:250px;" ng-src="{{img_' + g[1] + '}}">' +
                            '</a>';
                        return html;
                    });
                    g = (/\[image\-src=\"([\w\W]+?)\"\]/i).exec(content);
                }
                //匹配网址
                var i = 0;
                var m = content.match(/(((((http|ftp|https|HTTP|FTP|HTTPS):\/\/)[\w\-_]+)|www|WWW)(\.(?!gif|jpg|png|mp3)[\w\-_]+)+([\w\-\.,@?^=%:/~\+#]*[\w\-\@?^=%/~\+#\r\n]))|(([0-9]+)(\.[0-9]+)(\.[0-9]+)(\.[0-9]+)([\/\w\W]*))/ig);
                if (m == null)
                    return content;
                content = content.replace(/(((((http|ftp|https|HTTP|FTP|HTTPS):\/\/)[\w\-_]+)|www|WWW)(\.(?!gif|jpg|png|mp3)[\w\-_]+)+([\w\-\.,@?^=%:/~\+#]*[\w\-\@?^=%/~\+#\r\n]))|(([0-9]+)(\.[0-9]+)(\.[0-9]+)(\.[0-9]+)([\/\w\W]*))/ig, function() {
                    var html = '';
                    var g = (/((((http|ftp|https|HTTP|FTP|HTTPS):\/\/)[\w\-_]+)(\.[\w\-_]+)+([\w\-\.,@?^=%:/~\+#]*[\w\-\@?^=%/~\+#\r\n]))/ig).exec(m[i]);
                    if (getUserID()) {
                        if (g == null)
                            html = '<a style="color:white;text-decoration:underline;cursor:pointer;" ng-click="openLink(\'http://' + m[i] + '\')">' +
                            m[i] +
                            '</a>';
                        else
                            html = '<a style="color:white;text-decoration:underline;cursor:pointer;" ng-click="openLink(\'' + m[i] + '\')">' +
                            m[i] +
                            '</a>';
                        i = i + 1;
                    } else {
                        if (g == null)
                            html = '<a style="text-decoration:underline;cursor:pointer;" ng-click="openLink(\'http://' + m[i] + '\')">' +
                            m[i] +
                            '</a>';
                        else
                            html = '<a style="text-decoration:underline;cursor:pointer;" ng-click="openLink(\'' + m[i] + '\')">' +
                            m[i] +
                            '</a>';
                        i = i + 1;
                    }
                    return html;
                });
                return content;
            };
            var replaceImage = function(content) {}
            var html = '';
            //var message = document.getElementById("loadmore");
            //console.log(scope.appContent.font);
            if (scope.msg.senderDisplayName === undefined || scope.msg.senderDisplayName == '')
                scope.msg.senderDisplayName = scope.msg.sender;
            // 消息类型（[1，文本消息]，[2，图片消息]，[3，文件消息], [4，位置消息]，[5，语音消息]）
            if (scope.appContent === undefined || scope.appContent.faceConfig === undefined || scope.appContent.faceConfig.sys === undefined) {
                html = '<span class="text-message">' + scope.msg.content + '</span>';
            } else if (scope.msg.contentType == 1) {
                if (getUserID()) {
                    var style = scope.appContent.font === "" || scope.appContent.font === undefined ? {
                        style: 'normal',
                        weight: 'normal',
                        size: 9,
                        family: '微软雅黑',
                        color: 16777215
                    } : _.assign({
                        style: 'normal',
                        weight: 'normal',
                        size: 9,
                        family: '微软雅黑',
                        color: 16777215
                    }, scope.appContent.font);
                    style.color = 16777215;
                } else {
                    var style = scope.appContent.font === "" || scope.appContent.font === undefined ? {
                        style: 'normal',
                        weight: 'normal',
                        size: 9,
                        family: '微软雅黑',
                        color: 0
                    } : _.assign({
                        style: 'normal',
                        weight: 'normal',
                        size: 9,
                        family: '微软雅黑',
                        color: 0
                    }, scope.appContent.font);
                    style.color = 0;
                }
                html = '<span class="text-message"' + ' style="font:' + style.style + ' ' + style.weight + ' ' + style.size + 'pt' + ' ' + style.family + ';color:#' + _.padStart(style.color.toString(16), 6, '0') + '">' +
                    replaceSystemFace(scope.msg.content) + '</span>';
            } else if (scope.msg.contentType == 2) {
                html = '<span class="text-message">' +
                    '<a href="#" class="thumbnail" >' +
                    '<img src="' + scope.msg.content + '" alt="通用的占位符缩略图" >' +
                    '</a>' +
                    '</span>';
            } else if (scope.msg.contentType == 3) {
                var content = JSON.parse(scope.msg.content);
                console.log(content);
                if (content.status == 2 && content.way !== 1)
                    html = '<div class="file-message" style="width:265px">' +
                    '<img src="' + getSuffix(content) + '" onError= "this.src = \'../img/file/unkown.png\'">' +
                    '<p><input type="text" readonly="readonly" value="' + getFileName(content) + '"></p>' +
                    '<span>大小：' + getFileSize(content) + '</span>' +
                    '<div class="p-t-sm text-right">' +
                    '<span class="transinfo"><span style="color:green;" class="glyphicon glyphicon-ok"></span><span>在线传输</span></span>' +
                    '<a class="text-primary" role="button"><span ng-click="OpenFile(msg.content)">打开</span></a>&nbsp&nbsp&nbsp' +
                    '<a class="text-primary" role="button"><span ng-click="OpenDirectory(msg.content)">打开文件夹</span></a>' +
                    '</div>' +
                    '</div>';
                else if (content.status == 2 && content.way == 1) {
                    if (getUserID())
                        html = '<div class="file-message" style="width:265px">' +
                        '<img src="' + getSuffix(content) + '" onError= "this.src = \'../img/file/unkown.png\'">' +
                        '<p><input type="text" readonly="readonly" value="' + getFileName(content) + '"></p>' +
                        '<span>大小：' + getFileSize(content) + '</span>' +
                        '<div class="p-t-sm text-right">' +
                        '<span class="transinfo"><span style="color:green;" class="glyphicon glyphicon-ok"></span><span>离线传输</span></span>' +
                        '<a class="text-primary" role="button"><span ng-click="OpenFile(msg.content)">打开</span></a>&nbsp&nbsp&nbsp' +
                        '<a class="text-primary" role="button"><span ng-click="OpenDirectory(msg.content)">打开文件夹</span></a>' +
                        '</div>' +
                        '</div>';
                    else
                        html = '<div class="file-message" style="width:265px">' +
                        '<img src="' + getSuffix(content) + '" onError= "this.src = \'../img/file/unkown.png\'">' +
                        '<p><input type="text" readonly="readonly" value="' + getFileName(content) + '"></p>' +
                        '<span>大小：' + getFileSize(content) + '</span>' +
                        '<div class="p-t-sm text-right">' +
                        '<span class="transinfo"><span style="color:green;" class="glyphicon glyphicon-ok"></span><span>离线传输</span></span>' +
                        '<a class="text-primary" role="button"><span ng-click="OpenFile(msg.content)">打开</span></a>&nbsp&nbsp&nbsp' +
                        '<a class="text-primary" role="button"><span ng-click="OpenDirectory(msg.content)">打开文件夹</span></a>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp' +
                        '<a class="text-primary" role="button"><span ng-click="OpenDirectory(msg.content)">重新下载</span></a>' +
                        '</div>' +
                        '</div>';
                } else if (ifSelf(content) && content.way == 0 && content.status == 0) {
                    if (getUserID())
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[0] + '</span></div>';
                    else
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[2] + '</span></div>';
                } else if (!ifSelf(content) && content.way == 0 && content.status == 0) {
                    if (getUserID())
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[3] + '</span></div>';
                    else
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[1] + '</span></div>';
                } else if (ifSelf(content) && content.way == 0 && content.status == 1) {
                    if (getUserID())
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[4] + '</span></div>';
                    else
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[6] + '</span></div>';
                } else if (!ifSelf(content) && content.way == 0 && content.status == 1) {
                    if (getUserID())
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[7] + '</span></div>';
                    else
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-error"><span class="glyphicon glyphicon-remove-sign"></span><span>' + getFileInfo(content)[5] + '</span></div>';
                } else if (ifSelf(content) && content.way == 1) {
                    if (getUserID())
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-info"><span class="glyphicon glyphicon-info-sign"></span><span>' + getFileInfo(content)[8] + '</span></div>';
                    else
                        html = '<div class="well m-l-xs m-t-xs fit-content" id="file-info"><span class="glyphicon glyphicon-info-sign"></span><span>' + getFileInfo(content)[8] + '</span></div>';
                }
            } else if (scope.msg.contentType == 4) {
                html = '<span class="text-message">' +
                    '<iframe class="map" border=0 src="' + scope.msg.content + '" frameBorder=no></iframe>' +
                    '</span>';
            } else if (scope.msg.contentType == 5) {
                html = '<span class="text-message">' +
                    '<audio src="' + scope.msg.content + '" controls="controls">' +
                    '</audio>' +
                    '</span>';
            }


            if (scope.msg.contentType == 3 && content.status !== 2) {
                var html_g = html;
                $(element[0].previousElementSibling).remove();
            } else {
                if (getUserID()) {
                    var html_g =
                        '<div class="wellself m-l-xs m-t-xs fit-content" >' +
                        '<div class="text-point"></div>' + html +
                        '</div>';
                } else {
                    var html_g =
                        '<div class="well m-l-xs m-t-xs fit-content" >' +
                        '<div class="text-point"></div>' + html +
                        '</div>';
                }
            }
            console.log(html_g);
            var compileFn = $compile(html_g);
            // 传入scope，得到编译好的dom对象(已封装为jqlite对象)
            // 也可以用$scope.$new()创建继承的作用域
            var $dom = compileFn(scope);
            // 添加到文档中
            //angular.element("#loadmore").prepend($dom);
            var newElement = angular.element($dom);
            element.prepend(newElement);
            console.log(element);
            if (scope.count) {
                gotoBottom();
            } else {
                element[0].addEventListener('load', window.scrollTo(0, document.body.scrollHeight - scope.height));
            }
        }
    };
    /* @ngInject */
    function ControllerController($scope, $timeout, $location, $anchorScroll, $sce) {

        $scope.$on('font_changed', function(event, data) {
            $scope.appContent.font = JSON.parse(data);
        });

        $scope.OpenFile = function(item) {
            var file = JSON.parse(item);
            return lxtalkClient.Invoke('{15180DEF-D508-45F7-BAEB-6486CD8752C8}', 'OpenFile', JSON.stringify(file), $scope);
        };

        $scope.OpenDirectory = function(item) {
            var file = JSON.parse(item);
            return lxtalkClient.Invoke('{15180DEF-D508-45F7-BAEB-6486CD8752C8}', 'OpenDirectory', JSON.stringify(file), $scope);
        };

        $scope.openLink = function(md5) {
            var link = { fileName: md5 };
            return lxtalkClient.Invoke('{15180DEF-D508-45F7-BAEB-6486CD8752C8}', 'OpenUrl', JSON.stringify(link), $scope);
        };

        $scope.showImage = function(md5) {
            var imgSrc = $scope.appContent.directory.received + md5 + ".JPG";
            var img = { fileName: imgSrc };
            return lxtalkClient.Invoke('{15180DEF-D508-45F7-BAEB-6486CD8752C8}', 'OpenFile', JSON.stringify(img), $scope);
        };

        $scope.scrollController = function() {
            if ($scope.count) {
                window.scrollTo(0, document.body.scrollHeight);
            } else
                window.scrollTo(0, document.body.scrollHeight - $scope.height);
        };

        $scope.onFaceLoadError = function(md5) {
            $scope["img_" + md5] = "local://" + $scope.appContent.directory.base + "Images\\" + "Loading.gif";
            $timeout();
            lxtalkClient.Invoke('{15180DEF-D508-45F7-BAEB-6486CD8752C8}', 'LoadImages', JSON.stringify({ uid: $scope.msg.uid, md5: [md5] }), function() {
                console.log($scope["img_" + md5]);
                $scope["img_" + md5] = "local://" + $scope.appContent.directory.received + md5 + ".JPG";
                $timeout();
            });
        };
    }
})();