define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var imgsettimer = 0 ;
    var nametimer = 0;
    var bgtimer = 0 ;
    var qrtimer = 0 ;
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'poster/index' + location.search,
                    add_url: 'poster/add',
                    edit_url: 'poster/edit',
                    del_url: 'poster/del',
                    multi_url: 'poster/multi',
                    table: 'poster',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                commonSearch: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title')},
                        {field: 'bg_image', title: __('Bg_image'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'weigh', title: __('Weigh')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'datalist', title: __('Operate'), table: table,operate:false,
                            buttons: [
                                {
                                    name: 'content',
                                    text: __('Posterrecord'),
                                    extend: 'data-area=\'["1024px", "678px"]\'',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-list-ul',
                                    url: 'poster/posterrecord/ids/{ids}'
                                }
                            ],
                            formatter: Table.api.formatter.buttons
                        },
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);

            table.on('post-body.bs.table', function () {
                $(".btn-editone").data("area", ["1024px", "678px"]);
            });
        },
        posterrecord: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'poster/posterrecord' + location.search + '&ids=' + Config.ids,
                    table: 'poster',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                columns: [
                    [
                        {field: 'id', title: __('Id')},
                        {field: 'user.nickname', title: __('Nickname')},
                        {field: 'image', title: __('Image'), events: Controller.api.events.image, formatter: Controller.api.image},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);


            $('.btn-clear').click(function(){
                var url = $(this).data('url');
                Fast.api.ajax({
                    url: url,
                }, function (data, ret) {
                    table.bootstrapTable('refresh', {});
                }, function (data, ret) {

                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                $("form[role=form]").data("validator-options", {ignore: ':hidden'});
                //表单提交事件绑定
                Form.api.bindevent($("form[role=form]"), function (data, ret) {}, function (data, ret) {}, function (success, error) {
                    var data = [];
                    $('.drag').each(function () {
                        var obj = $(this);
                        var type = obj.attr('type');
                        var left = obj.css('left'), top = obj.css('top');
                        var d = {
                            left: left,
                            top: top,
                            type: obj.attr('type'),
                            width: obj.css('width'),
                            height: obj.css('height')
                        };
                        if (type == 'nickname') {
                            d.size = obj.attr('size');
                            d.color = obj.attr('color');
                        } else if (type == 'qr') {
                            d.size = obj.attr('size');
                            d.qr_table = obj.attr('qr_table');
                            d.qr_field = obj.attr('qr_field');
                            d.qr_relation = obj.attr('qr_relation');
                        } else if (type == 'img') {
                            d.src = Fast.api.cdnurl(obj.attr('src'));
                        }
                        data.push(d);
                    });
                    $(':input[name="row[data]"]').val(JSON.stringify(data));
                });


                //图片地址变化
                $('#c-bg_image').on('change', function () {
                    $('.bg').remove();
                    $('#poster').prepend("<img src='" + Fast.api.cdnurl($(this).val()) + "' class='bg'/>");
                });
                $('#c-img').on('change', function () {
                    $('.drag').each(function () {
                        if ($(this).attr("type") == 'img') {
                            $(this).find('img').attr('src', Fast.api.cdnurl($('#c-img').val()));
                        }
                    });
                });
                // 移除图片事件
                $(document.body).on("click", "#p-bg_image .btn-trash", function () {
                    $('.bg').attr('src', '');
                });
                $(document.body).on("click", "#p-img .btn-trash", function () {
                    $('.drag').each(function () {
                        if ($(this).attr("type") == 'img') {
                            $(this).attr('src', '');
                            $(this).find('img').attr('src', '/assets/addons/poster/images/img.jpg');
                        }
                    });
                });

                require(['designer'], function () {
                    //添加元素
                    $('.btn-com').click(function(){
                        var imgset = $('#imgset'), nameset = $("#nameset"),qrset = $('#qrset');
                        imgset.hide(),nameset.hide(),qrset.hide();
                        Controller.api.clearTimers();
                        var type = $(this).data('type');
                        $('.drag').each(function () {
                            if ($(this).attr("type") == type) {
                                type = false;
                            }
                        });

                        if(type == false){
                            Layer.msg('请不要重复添加');
                        }else{
                            var img = "";
                            if(type=='qr'){
                                img = '<img src="/assets/addons/poster/images/qr.jpg" />';
                            } else if(type=='head'){
                                img = '<img src="/assets/addons/poster/images/head.jpg" />';
                            } else if(type=='img' || type=='thumb'){
                                img = '<img src="/assets/addons/poster/images/img.jpg" />';
                            } else if(type=='nickname'){
                                img = '<div class=text>昵称</div>';
                            }
                            var index = $('#poster .drag').length + 1;
                            var obj = $('<div class="drag" type="' + type +'" index="' + index +'" style="z-index:' + index+'">' + img+'<div class="rRightDown"> </div><div class="rLeftDown"> </div><div class="rRightUp"> </div><div class="rLeftUp"> </div><div class="rRight"> </div><div class="rLeft"> </div><div class="rUp"> </div><div class="rDown"></div></div>');
                            $('#poster').append(obj);
                            Controller.api.bindEvents(obj);
                        }
                    });

                    $('.drag').each(function () {
                        Controller.api.bindEvents($(this));
                        Controller.api.bind($(this));
                    });

                });

                //颜色
                Controller.api.color();


                //选择二维码数据表
                $(document).on('change', "select[name='qr_table']", function () {
                    var that = this;
                    Fast.api.ajax({
                        url: "poster/get_field_list",
                        data: {table: $(that).val()},
                    }, function (data, ret) {
                        mainfields = data.fieldlist;
                        renderselect($("#c-qr_field"), mainfields, 'qr_field');//渲染数据
                        renderselect($("#c-qr_relation"), mainfields, 'qr_relation');//渲染数据
                        return false;
                    });
                    return false;
                });
                var renderselect = function (select, data, field_type) {
                    var html = [];
                    html.push("<option value=''>请选择</option>");
                    for (var i = 0; i < data.length; i++) {
                        html.push("<option value='" + data[i] + "'>" + data[i] + "</option>");
                    }
                    select.html(html.join(""));
                    select.trigger("change");
                    if (select.data("selectpicker")) {
                        $('.drag').each(function () {
                            var type = $(this).attr('type');
                            if(type == 'qr'){
                                if(field_type == 'qr_field'){
                                    var qr_field = $(this).attr('qr_field') || "";
                                    select.selectpicker('val',qr_field).trigger("change").trigger("validate");;
                                } else {
                                    var qr_relation = $(this).attr('qr_relation') || "";
                                    select.selectpicker('val',qr_relation).trigger("change").trigger("validate");;
                                }
                            }
                        });
                        select.selectpicker('refresh').trigger("change");
                    }
                    return select;
                };
                $("select[name='qr_table']").trigger("change");
            },
            bindEvents: function (obj) {
                var index = obj.attr('index');
                var rs = new Resize(obj, { Max: true, mxContainer: "#poster" });
                rs.Set($(".rRightDown",obj), "right-down");
                rs.Set($(".rLeftDown",obj), "left-down");
                rs.Set($(".rRightUp",obj), "right-up");
                rs.Set($(".rLeftUp",obj), "left-up");
                rs.Set($(".rRight",obj), "right");
                rs.Set($(".rLeft",obj), "left");
                rs.Set($(".rUp",obj), "up");
                rs.Set($(".rDown",obj), "down");
                rs.Scale = true;
                var type = obj.attr('type');
                if(type=='nickname' || type=='img' || type=='title' || type=='marketprice' || type=='productprice'){
                    rs.Scale = false;
                }
                new Drag(obj, { Limit: true, mxContainer: "#poster" });
                $('.drag .remove').unbind('click').click(function(){
                    $(this).parent().remove();
                })
                require(['jquery.contextMenu'],function(){
                    $.contextMenu({
                        selector: '.drag[index=' + index + ']',
                        callback: function(key, options) {
                            var index = parseInt($(this).attr('zindex'));

                            if(key=='next'){
                                var nextdiv = $(this).next('.drag');
                                if(nextdiv.length>0 ){
                                    nextdiv.insertBefore($(this));
                                }
                            } else if(key=='prev'){
                                var prevdiv = $(this).prev('.drag');
                                if(prevdiv.length>0 ){
                                    $(this).insertBefore(prevdiv);
                                }
                            } else if(key=='last'){
                                var len = $('.drag').length;
                                if(index >=len-1){
                                    return;
                                }
                                var last = $('#poster .drag:last');
                                if(last.length>0){
                                    $(this).insertAfter(last);
                                }
                            }else if(key=='first'){
                                var index = $(this).index();
                                if(index<=1){
                                    return;
                                }
                                var first = $('#poster .drag:first');
                                if(first.length>0){
                                    $(this).insertBefore(first);
                                }
                            }else if(key=='delete'){
                                $(this).remove();
                            }
                            var n =1 ;
                            $('.drag').each(function(){
                                $(this).css("z-index",n);
                                n++;
                            })
                        },
                        items: {
                            "last": {name: "调整到最顶层"},
                            "first": {name: "调整到最低层"},
                            "delete": {name: "删除元素"}
                        }
                    });
                    obj.unbind('click').click(function () {
                        Controller.api.bind($(this));
                    });
                });
            },
            color: function () {
                var refreshStyle = function () {
                    var style = [];
                    if ($(".btn-color").hasClass("active")) {
                        style.push($(".btn-color").data("color"));
                    }
                    $("#c-color").val(style.join("|"));
                };
                if ($(".btn-color").hasClass("active")) {
                    style.push($(".btn-color").data("color"));
                }
                require(['jquery-colorpicker'], function () {
                    $('.colorpicker').colorpicker({
                        color: function () {
                            var color = "#000000";
                            var rgb = $("#c-color").css('color').match(/^rgb\(((\d+),\s*(\d+),\s*(\d+))\)$/);
                            if (rgb) {
                                color = rgb[1];
                            }
                            return color;
                        }
                    }, function (event, obj) {
                        $("#c-color").css('color', '#' + obj.hex);
                        $(event).addClass("active").data("color", '#' + obj.hex);
                        refreshStyle();
                    }, function (event) {
                        $("#c-color").css('color', 'inherit');
                        $(event).removeClass("active");
                        refreshStyle();
                    });
                });
            },
            bind: function (obj) {
                var imgset = $('.imgset'), nameset = $(".nameset"),qrset = $('.qrset');
                imgset.hide(),nameset.hide(),qrset.hide();
                Controller.api.clearTimers();
                var type = obj.attr('type');

                //图片
                if(type=='img'){
                    imgset.show();
                    var src = obj.attr('src');
                    var input = imgset.find('#c-img');

                    if(typeof(src)!='undefined' && src!=''){
                        input.val(src).trigger("change").trigger("validate");
                    }
                    imgsettimer = setInterval(function(){
                        if(input.val()!=src && input.val()!=''){
                            var url = input.val();
                            obj.attr('src',Fast.api.cdnurl(input.val()));
                        }
                    },50);

                    //昵称
                } else if(type=='nickname'){
                    nameset.show();
                    var color = obj.attr('color') || "#000";
                    var size = obj.attr('size') || "16";
                    var input = nameset.find('input:first');
                    var namesize = nameset.find('#namesize');
                    var picker = nameset.find('.sp-preview-inner');
                    input.val(color); namesize.val(size.replace("px",""));
                    picker.css( {'background-color':color,'font-size':size});

                    nametimer = setInterval(function(){
                        obj.attr('color',input.val()).find('.text').css('color',input.val());
                        obj.attr('size',namesize.val() +"px").find('.text').css('font-size',namesize.val() +"px");
                    },50);

                    //二维码
                } else if(type=='qr'){
                    qrset.show();
                    //得到属性上的值
                    var qr_table = obj.attr('qr_table') || "";
                    var qr_field = obj.attr('qr_field') || "";
                    var qr_relation = obj.attr('qr_relation') || "";

                    //表单
                    var qrtable = qrset.find("select[name='qr_table']");
                    var qrfield = qrset.find("#c-qr_field");
                    var qrrelation = qrset.find("#c-qr_relation");

                    //编辑的时候吧属性值设置到编辑框
                    if(typeof(qr_table)!='undefined' && qr_table!=''){
                        qrtable.val(qr_table).trigger("change").trigger("validate");
                    }
                    if(typeof(qr_relation)!='undefined' && qr_relation!=''){
                        qrrelation.val(qr_relation).trigger("change").trigger("validate");
                    }

                    //修改内容的时候设置attr
                    qrtimer = setInterval(function(){
                        if(qrtable.val()!=qr_table && qrtable.val()!='' && qrtable.val() != 'null' && qrtable.val() != null){
                            obj.attr('qr_table',qrtable.val());
                        }
                        if(qrfield.val()!=qr_field && qrfield.val()!='' && qrfield.val() != 'null' && qrfield.val() != null){
                            obj.attr('qr_field',qrfield.val());
                        }
                        if(qrrelation.val()!=qr_relation && qrrelation.val()!='' && qrrelation.val() != 'null' && qrrelation.val() != null){
                            obj.attr('qr_relation',qrrelation.val());
                        }
                    },50);
                }
            },
            clearTimers: function () {
                clearInterval(imgsettimer);
                clearInterval(nametimer);
                clearInterval(bgtimer);
                clearInterval(qrtimer);
            },
            image: function (value, row, index) {
                value = value ? value : '/assets/img/blank.gif';
                var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
                return '<a href="javascript:"><img class="' + classname + '" src="' + value + '" /></a>';
            },
            events: {
                //单元格图片预览
                image: {
                    'click .img-center': function (e, value, row, index) {
                        var data = [];
                        value = value.toString().split(",");
                        $.each(value, function (index, value) {
                            data.push({
                                src: value,
                            });
                        });
                        Layer.photos({
                            photos: {
                                "start": $(this).parent().index(),
                                "data": data
                            },
                            anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                        });
                    },
                }
            },
        }
    };
    return Controller;
});