define(function(require) {
    var func = {
        // 侧边工具栏 
        toolbar: function() {
            $("#toolbar").on("click", "[rel=backtop]", function() {
                $('html, body').animate({
                    scrollTop: 0
                }, 300);
                return false;
            });
        },
        // 下划菜单
        slowdown: function() {
            $(".dropdown").hover(function() {
                $(this).find(".dropdown-menu").stop(!0, !0).slideDown(250);
            }, function() {
                $(this).find(".dropdown-menu").stop(!0, !0).slideUp(150);
            });
        },
        // bootstrap文字提示
        tooltip: function() {
            $(function() {
                $('[data-toggle="tooltip"]').tooltip();
            });
        },
        //搜索下拉选择
        select: function() {
            $('[rel=select]').find('li').each(function() {
                var obj = $(this);
                obj.click(function() {
                    $('#search-type').val(obj.data('value'));
                    $('[rel=type]').text(obj.text());
                });
            });
        },
        //浏览记录弹窗
        trace: function() {
            var $trace = $('[rel=trace]');
            $trace.click(function() {
                require(['layer'], function(layer) {
                    layer.open({
                        type: 2, //iframe
                        shadeClose: true,
                        area: ['800px', '640px'],
                        title: '我的足迹',
                        content: '/tools/history.html',
                        btn: ['一键清空'],
                        yes: function() {
                            require(['jstorage'], function(jstorage) {
                                jstorage.flush();
                                layer.closeAll();
                                layer.msg('删除成功');
                            });
                        }
                    });
                });
            });
        },
        init: function() {
            func.toolbar();
            func.tooltip();
            func.slowdown();
            func.select();
            func.trace();
            //图片延迟加载
            if ($(".lazyload").length > 0) {
                require(['lazyload'], function(lazyload) {
                    $(".lazyload img").lazyload({
                        placeholder: "/static/img/nopic.gif", //用图片提前占位
                        effect: "fadeIn",
                        threshold: 200
                    });
                });
            }
            if ($('.bottom-bar').length > 0) {
                require(['cookie'], function(){
                    if ($.cookie('close_bottom_bar')!=1) {
                        $('.bottom-bar').removeClass('hide');
                    }
                });
                $('.bottom-bar .bottom-close').click(function(){
                    $('.bottom-bar').fadeOut('fast');
                    $.cookie('close_bottom_bar', '1', { expires: 1 });
                });
            }
        },
        is_login: function() {
            if (sys.user.id == '') {
                layer.confirm('请登录后进行操作，现在登录吗？', {
                        btn: ['去登录', '再看看']
                    },
                    function() {
                        window.location = '/user/index/login';
                    },
                    function() {});
                return false;
            } else
                return true;
        },
    };
    return {
        init: function() {
            func.init();
        },
        // 时间
        moment: function() {
            if ($('[rel=moment]').length > 0) {
                require(['moment'], function(moment) {
                    $('[rel=moment]').each(function() {
                        $(this).html(moment((parseInt($(this).data('time')) * 1000 || parseInt($(this).attr('title')) * 1000)).fromNow());
                    });
                });
            }
        },
        editor: function(ops) {
            var $obj = $('[rel=editor]');
            if ($obj.length>0) {
                require(['simditor', 'layer'], function(Simditor, layer) {
                    $obj.each(function() {
                        Simditor.locale = 'zh-CN';//设置中文
                        new Simditor({
                            textarea: $(this),  //textarea的id
                            placeholder: '这里输入文字...',
                            toolbar:  ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment'],
                            pasteImage: true,
                            defaultImage : '',
                            upload : {
                                url : '/files/api/upload/module/' + sys.module + '/field/' + $obj.attr('name') + '/file/file',
                                params: null,
                                fileKey: 'file',
                                connectionCount: 3,
                                leaveConfirm: '正在上传文件'
                            }
                        });
                    });
                });
            }
        },
        // 跳转确认
        confirm: function() {
            var $obj = $('[rel=confirm]');
            if ($obj.length > 0) {
                $obj.each(function() {
                    if (!$(this).data('href')) $(this).attr('data-href', $(this).attr('href')).attr('href', 'javascript:;');
                    $(this).click(function() {
                        var $this = $(this);
                        require(['layer'], function(layer) {
                            layer.confirm(($this.data('title') || '确实要执行此操作吗？'), {
                                btn: ['确定', '取消']
                            }, function() {
                                window.location = $this.data('href');
                            });
                        });
                    });
                });
            }
        },
        // 单选
        radio: function() {
            $('[rel=radio]').each(function() {
                if (!$(this).data('value') && $(this).data('value') !== 0) return true;
                $(this).find('input[value=' + $(this).data('value') + ']:radio').attr('checked', true);
            });
        },
        // 下拉选择
        value: function() {
            $('[rel=value]').each(function() {
                if (!$(this).data('value') && $(this).data('value') !== 0) return true;
                $(this).val($(this).data('value'));
            });
        },
        // 多选框
        checkbox: function() {
            $('[rel=checkbox]').each(function() {
                if (!$(this).data('value') && $(this).data('value') !== 0) return true;
                $(this).find('input:checkbox').val($(this).data('value').split(','));
            });
        },
        // 验证码
        captcha: function() {
            $('[rel=captcha]').each(function() {
                var obj = $(this);
                obj.click(function() {
                    obj.attr('src', (obj.data('src') ? obj.data('src') : '/index.php/captcha') + '?' + Math.random());
                    $('input[name=captcha]').val('');
                });
            });
            $('[rel=captcha]').click();
        },
        // 图片上传
        upload: function(ops) {
            var args = {
                obj: '[rel=upload]',
                module: sys.module,
                name: 'thumb',
                cid: sys.data.cid,
                url: '/files/api/upload',
                callback: null
            };
            if (ops != undefined) args = $.extend(args, ops);
            if ($(args.obj).length > 0) {
                require(['upload'], function() {
                    $(args.obj).each(function() {
                        var obj = $(this);
                        obj.change(function() {
                            if (obj.data('module')) args.module = obj.data('module');
                            if (obj.data('name')) args.name = obj.data('name');
                            if (obj.data('url')) args.url = obj.data('url');
                            args.url += '/module/' + args.module + '/file/' + obj.attr('name') + '/field/' + args.name + '/cid/' + args.cid;
                            obj.upload(args.url, function(rs) {
                                if (typeof(args.callback) == 'function') {
                                    return args.callback(rs, obj, args);
                                } else {
                                    if (rs.success_count == 1) {
                                        if (typeof(rs.success[0].type) == 'undefined') rs.success[0].type = 0;
                                        var $target = obj.next(rs.success[0].type == 0 ? 'img._upload' : 'span._upload');
                                        if ($target.length > 0) {
                                            $target.remove();
                                            obj.next('input._upload').remove();
                                        }
                                        obj.after(
                                            (rs.success[0].type == 0 ? "<img class='_upload' src='" + rs.success[0].url + "?" + Math.random() + "' border='0'>" : "<span class='_upload'>" + rs.success[0].name + "</span>") + "<input type='hidden' class='_upload' name='" + args.name + "' value='" + rs.success[0].path + "'>");
                                        obj.val('');
                                    } else {
                                        require(['layer'], function(layer) {
                                            layer.msg('上传失败，请重试');
                                        });
                                    }
                                }
                            }, 'json');

                        });
                    });
                });
            }
        },
        // 存储浏览记录
        storage: function(type) {
            require(['jstorage'], function(jstorage) {
                var sTitle = document.title;
                var sType = type || sys.module;
                var sUrl = window.location.href;
                var date = new Date().toLocaleString().split(' ')[0];
                var time = {};
                var info = {
                    'title': sTitle,
                    'url': sUrl,
                };
                var newTime = true;
                var repeat = false; //过滤重复链接
                var val = jstorage.get(sType);
                if (val) { //判断类型
                    time = val;
                    // debugger
                    for (var key in time) { //循环时间，判断该日期下是否有记录
                        if (key === date) {
                            newTime = false; //不是新的时间
                            for (var item in time[date]) { //过滤重复链接
                                if (time[date][item].url === sUrl) {
                                    repeat = true;
                                    break;
                                }
                            }
                            if (repeat === false) {
                                time[date].unshift(info);
                                break;
                            }
                        }
                    }
                    if (newTime) {
                        time[date] = [];
                        time[date].push(info);
                    }
                } else {
                    time[date] = [];
                    time[date].push(info);
                }
                jstorage.set(sType, time, { TTL: 604800000 }); //TTL用来设置key值对应的生存时间的值单位毫秒 目前设置7天
            });
        },
        // 删除搜索记录
        deleteHistory: function() {
            var $obj = $('[rel=del]');
            if ($obj.length > 0) {
                $obj.each(function() {
                    $(this).click(function() {
                        var $this = $(this);
                        var index = $this.data('index');
                        var key = $this.data('time');
                        require(['layer', 'jstorage'], function(layer, jstorage) {
                            layer.confirm(($this.data('title') || '确实要删除此条搜索记录吗？'), {
                                btn: ['确定', '取消']
                            }, function() {
                                //删除单个搜索记录
                                var data = jstorage.get('search') || '';
                                data[key].splice(index, 1);
                                jstorage.set('search', data, { TTL: 604800000 });
                                $this.prev().remove();
                                $this.remove();
                                layer.msg('删除成功');
                            });
                        });
                    });
                });
            }
        },
        // 渲染搜索记录
        renderHistory: function() {
            var parent = $('[rel=render]');
            var str = '';
            var data = $.jStorage.get('search') || '';
            if (!!data) {
                var num = 0;
                for (var key in data) {
                    str += "<dt class='mt-sm'>" + key + "</dt>";
                    for (var i = 0; i < data[key].length; i++) {
                        // 默认显示10条历史搜索记录
                        if (num < 10) {
                            str += "<dd class='mt-xs'> <p class='overflow'>" + data[key][i].title + "</p><a href='javascript:;' rel='del' class='fa fa-trash pull-right mt-xs' data-index=" + i + " data-time=" + key + "></a>";
                            num++;
                        } else {
                            break;
                        }
                    }
                }
            }
            parent.html(str);
        },
        // 举报
        report: function() {
            $("[rel=report]").on('click', function(e) {
                e.preventDefault();
                var data = {
                    'data_id': $(this).data('id'),
                    'column_id': $(this).data('cid')
                };
                require(['layer'], function(layer) {
                    $.get('/tools/report.html', function(rs) {
                        layer.open({
                            type: 1,
                            title: '举报',
                            shadeClose: true,
                            resize: false,
                            area: ['300px', '190px'], //宽高
                            content: rs,
                            btn: ['确定'],
                            yes: function(index, layero) {
                                data.type = $('[type=radio]:checked').val();
                                $.ajax({
                                    type: "POST",
                                    url: API.report,
                                    data: data,
                                    success: function(data) {
                                        layer.msg(data.message);
                                        if (data.code == 1) {
                                            layer.closeAll();
                                            layer.alert('感谢您的举报，我们会尽快处理。');
                                        } else {
                                            layer.closeAll();
                                            layer.alert('出了点问题，您再试试..');
                                        }
                                    },
                                    error: function(request) {
                                        layer.closeAll();
                                        layer.msg('出了点问题，您再试试..');
                                    }
                                });
                            },
                        });
                    });
                });
            });
        },

        //删除信息
        delete: function() {
            var $obj = $('[rel=delinfo]');
            $obj.each(function() {
                $(this).click(function() {
                    var id = $(this).data('id');
                    require(['layer'], function(layer) {
                        layer.open({
                            type: 2,
                            shadeClose: true,
                            area: ['360px', '280px'],
                            title: '管理信息',
                            content: ['/index/block/delete']
                        });
                    });
                });
            });
        },

    };
});