ReportBuilder.core

/// <reference path="../../../JS/jquery.min.js" />
var StringBuilder = function () {
    var strArray = [];
    this.Append = function (s) {
        strArray.push(s);
        return this;
    }
    this.ToString = function () {
        return strArray.join("");
    }
}

var OnSelectChanged = function (ctrl) {

}

var FindDropCell = function (point) {

    for (var i = 0; i < ReportMain.Elements.length; i++) {
        var ctrl = ReportMain.Elements[i];
        if (ctrl.IsIReportPanel) {
            var left = ctrl.MarginLeftWidth;
            var top = ctrl.MarginTopWidth;
            var width = ctrl.Width;
            var height = ctrl.Height;
            if (((left + width) > point.X && point.X > left)
                && ((top + height) > point.Y && point.Y > top)) {//找到该位置的table
                var table = ctrl.Element;
                var $td = FindTableCell(table, { X: point.X - left, Y: point.Y - top });
                return $td;

            }
        }
    }
}

var IsRowSpan = function (td, rs, ri, ci) {//判断该td是否已经被合并
    if (!td.is(":visible")) {
        var trs = rs;
        var rowIndex = ri;
        var colIndex = ci;
        if (!trs) {
            trs = td.closest("table").find(">tbody>tr");
        }
        if (rowIndex === undefined) {
            rowIndex = td.parent().index();
        }
        if (colIndex === undefined) {
            colIndex = td.index();
        }
        //往上找,看是不是被合并了
        var rowCount = 0;
        var preRowIndex = rowIndex;
        while (--preRowIndex >= 0) {
            rowCount++;
            var preTr = $(trs[preRowIndex]);
            var upTd = preTr.find(">td:eq(" + colIndex + ")");
            if (upTd.is(":visible")) {
                var rowSpan = Z.ToInt(upTd.attr("rowspan"));
                if (rowSpan > rowCount) {
                    return true;
                }
                break;
            }
        }
    }
    return false;
}

var FindSpanCell = function (td, rs, ri, ci) {//判断该td是否已经被合并
    if (!td.is(":visible")) {
        var trs = rs;
        var rowIndex = ri;
        var colIndex = ci;
        if (!trs) {
            trs = td.closest("table").find(">tbody>tr");
        }
        if (rowIndex === undefined) {
            rowIndex = td.parent().index();
        }
        if (colIndex === undefined) {
            colIndex = td.index();
        }
        //往上找,看是不是被合并了
        var rowCount = 0;
        while (rowIndex > 0) {
            rowCount++;
            var tr = $(trs[rowIndex]);
            var colCount = 0;
            var ci = colIndex;
            while (ci >= 0) {
                colCount++;
                var td = tr.find(">td:eq(" + ci + ")");
                if (td.is(":visible")) {
                    var rowSpan = GetRowSpan(td);
                    var colSpan = GetColSpan(td);
                    if (rowSpan == rowCount && colSpan == colCount) {
                        return td;
                    }
                }
                ci--;
            }
            rowIndex--;
        }
    }
    return td;
}

//给定一个table和位于table上的点坐标,找出该点所在的td
var FindTableCell = function (table, point) {
    var width = table.outerWidth();
    var height = table.outerHeight();
    var trs = table.find(">tbody>tr");
    var helperTr = table.find(">tbody>tr.tr-helper");
    var rowStart = 0;
    var rowEnd = 0;
    for (var rowIndex = 0; rowIndex < trs.length; rowIndex++) {
        var $tr = $(trs[rowIndex]);
        rowStart = rowEnd;
        rowEnd += $tr.outerHeight();
        if (rowStart < point.Y && rowEnd > point.Y) {//找到行
            var tds = $tr.children();
            var colStart = 0;
            var colEnd = 0;
            for (var colIndex = 0; colIndex < tds.length; colIndex++) {
                var $td = $(tds[colIndex]);
                //不管是否已经被合并都假设它存在
                var w = helperTr.find(">td:eq(" + colIndex + ")").outerWidth(); //单元格宽度
                colStart = colEnd;
                colEnd += w;
                if (colStart < point.X && colEnd > point.X) {//找到单元格
                    if (!$td.is(":visible")) {//已经被合并,找到可见的单元格
                        $td = FindSpanCell($td, trs, rowIndex, colIndex);
                    }
                    var child = $td.find(">.ctrl-container>.element").data("Tag"); //包含子节点
                    if (child) {
                        if (child.IsIReportPanel) {
                            return FindTableCell(child.Element, { X: point.X - colStart, Y: point.Y - rowStart });
                        }
                    }
                    return $td;
                }
            }
        }
    }
}

//var FindTdPosition = function (td) {
//    var pos = { Left: 0, Top: 0 };
//    td.prevAll().each(function () {
//        pos.Left += $(this).outerWidth();
//    });
//    var tr = td.parent();
//    tr.prevAll().each(function () {
//        pos.Top += $(this).outerHeight();
//    });
//    var ctrl = td.closest(".element").data("Tag");
//    if (ctrl) {
//        pos.Left += ctrl.MarginLeftWidth;
//        pos.Top += ctrl.MarginTopWidth;
//    }
//    return pos;
//}

var GetControlPosition = function (ctrl) {
    var pos = { Left: ctrl.MarginLeftWidth, Top: ctrl.MarginTopWidth };
    var parentControl = ctrl.ParentControl;
    if (parentControl) {
        var td = ctrl.Element.closest("td");
        td.prevAll().each(function () {
            pos.Left += $(this).outerWidth();
        });
        var tr = td.parent();
        tr.prevAll().each(function () {
            pos.Top += $(this).outerHeight();
        });
        pos.Top += 2; //误差?
        var parentPos = GetControlPosition(parentControl);
        pos.Left += parentPos.Left;
        pos.Top += parentPos.Top;
    }
    return pos;
}

var GetTdResizeProxyPosition = function (ctrl, td) {
    var pos = GetControlPosition(ctrl);
    td.prevAll().each(function () {//
        pos.Left += $(this).outerWidth();
    });
    return pos;
}

var StopEvent = function (e) {
    e.preventDefault();
    e.stopPropagation();
}

var TableClasses = ["tb-default", "tb-only-tb-border",
                        "tb-all-border", "tb-only-td-border", "tb-bottom-border"];

var GetCData = function (node) {
    var text = "";
    if (node.length > 0 && node[0].childNodes[0]) {
        text = node[0].childNodes[0].data;
        text = $.trim(text);
    }
    return text;
};

var LastDragContainer = null;
var IsResizing = false;
var IsCellResizing = false;
var ControlContainer = function (ctrl) {
    this.Control = ctrl;
    ctrl.Container = this;
    this.DesignerPanel = $(".report-designer");
    ctrl.Element.addClass("element");
    this.Container = $("<div></div>").addClass("ctrl-container   container-selected")
                                     .attr("ControlID", ctrl.ID).append(ctrl.Element);
    this.Container.on("dblclick", ctrl, function (e) {
        if (ctrl.Type != "TextBox") return null;
        setTextBoxFunc(ctrl, "Text");
    });
    this.Container.on("click", ctrl, function (e) {
        SelectElement.call(e.data, e);
        ShowControlAttr(ctrl);
        StopEvent(e);
    });

    this.RemoveSelectedStyle = function () {
        this.Container.removeClass("container-selected");
    }

    this.Remove = function () {
        this.Container.remove();
    }

    this.DisableResize = function () {
        this.Container.resizable("disable");
    }

    this.EnableResize = function () {
        this.Container.resizable("enable");
    }

    this.MoveInTable = function () {
        this.Container.draggable({
            proxy: proxy, deltaX: 3, deltaY: 20,
            revert: true
        });
        this.DisableResize();
    }

    this.MoveOutTable = function () {
        this.Container.draggable({ proxy: null, revert: false, deltaX: null, deltaY: null });
        this.EnableResize();
    }

    this.AddSelectedStyle = function () {
        this.Container.addClass("container-selected");
    }


    //判断是否点击事件
    var dragTimeSpan = 200, dragTimerID;
    var StartCountDrag = function () {
        dragTimeSpan = 200
        CountDrag(200);
    }
    var CountDrag = function (span) {
        if (dragTimeSpan > 0) {
            dragTimerID = setTimeout(function () {
                dragTimeSpan = 0;
            }, span);
        }
    }

    var proxy = function (source) {
        var opts = $(this).draggable("options");
        var container = opts.Container;
        var proxy = $("<div></div>").addClass("move-element-proxy min-proxy")
                                            .css("z-index", 9999).hide(); //.css({ left: -10000, top: -10000 })
        if (container && container.Control) {
            container.DesignerPanel.append(proxy);
        }
        return proxy;
    };
    var isClick = false;
    this.Container.draggable({
        cursor: "default",
        onBeforeDrag: function (e) {
            if (IsResizing || IsCellResizing) {
                IsCellResizing = false;
                return false;
            }
            if (LastDragContainer) {
                return false;
            }
            LastDragContainer = this;
            StartCountDrag(50);
        },
        onStartDrag: function (e) {
            var opts = $(this).draggable("options");
            var container = opts.Container;
            if (container && container.Control) {
                SelectElement.call(container.Control, e);
            }
            if (IsResizing || IsCellResizing) {
                return false;
            }
        },
        onDrag: function (e) {
            isClick = false;
            var d = e.data;
            if (IsResizing) {
                return false;
            }
            if (IsCellResizing) {
                d.left = d.startLeft;
                d.top = d.startTop;
                return false;
            }
            var opts = $(this).draggable("options");
            var container = opts.Container;
            var ctrl = container.Control;
            LastDragControl = container.Control;
            if (ctrl) {
                if (dragTimeSpan > 0) {
                    d.top = ctrl.MarginTopWidth;
                    d.left = ctrl.MarginLeftWidth;
                    isClick = true;
                    return false;
                }

                var parentControl = ctrl.ParentControl;
                if (parentControl != null && parentControl.IsIReportPanel) {
                    var p = GetMouseAlias(e);
                    d.left = p.X + opts.deltaX;
                    d.top = p.Y + opts.deltaY;
                    var proxy = $(this).draggable("proxy");
                    if (proxy) {
                        proxy.show();
                    }
                }
                if (ctrl.MovedOriginal) {
                    d.left = ctrl.MarginLeftWidth;
                    d.top = ctrl.MarginTopWidth;
                    $(this).draggable("options").revert = false;
                }
                var top = d.top;
                var left = d.left;
                if (left < 0) {
                    d.left = 0;
                }
                if (top < 0) {
                    d.top = 0;
                }
                var designerPanel = ReportMain.designerPanel;
                if (left + $(d.target).outerWidth() > designerPanel.width()) {
                    d.left = designerPanel.width() - $(d.target).outerWidth();
                }
                if (top + $(d.target).outerHeight() > designerPanel.height()) {
                    d.top = designerPanel.height() - $(d.target).outerHeight();
                }
            }
        },
        onStopDrag: function (e) {
            LastDragContainer = null;
            LastDragControl = null;
            if (IsResizing || IsCellResizing) {
                IsCellResizing = false;
                return false;
            }
            var d = e.data;
            var opts = $(this).draggable("options");
            if (isClick) {
                isClick = false;
                return false;
            }
            var proxy = $(this).draggable("proxy");
            if (proxy) {
                proxy.hide();
            }

            d.left -= opts.deltaX;
            d.top -= opts.deltaY;

            var container = opts.Container;

            if (container && container.Control) {
                var ct = container.Control;
                if (ct.MovedOriginal) {//已经从父级移除
                    delete ct.MovedOriginal;
                    return false;
                }
                else {
                    ct.MarginLeftWidth = Z.ToInt(d.left) || 0;
                    ct.MarginTopWidth = Z.ToInt(d.top) || 0;
                }
                ShowControlAttr(ct);
                if (ControlPropPanel.Items && ControlPropPanel.Items["MarginLeftWidth"])
                    ControlPropPanel.Update("MarginLeftWidth", ct.MarginLeftWidth);
                if (ControlPropPanel.Items && ControlPropPanel.Items["MarginTopWidth"])
                    ControlPropPanel.Update("MarginTopWidth", ct.MarginTopWidth);
            }
        },
        Container: this
    });

    this.Container.resizable({
        handles: "e,s,se",
        onStartResize: function (e) {
            IsResizing = true;
        },
        onResize: function (e) {
            var opts = $(this).resizable("options");
            var container = opts.Container;
            if (container && container.Control) {
                var d = e.data;
                var ct = container.Control;
                ct.Width = Z.ToInt(d.width) - Z.ToInt(ct.Element.css("border-left-width")) - Z.ToInt(ct.Element.css("border-right-width"));
                ct.Height = Z.ToInt(d.height) - Z.ToInt(ct.Element.css("border-top-width")) - Z.ToInt(ct.Element.css("border-bottom-width")) + 4;
            }
        },
        onStopResize: function (e) {
            // IsResizing = false;
            var opts = $(this).resizable("options");
            var container = opts.Container;
            if (container && container.Control) {
                var ct = container.Control;
                ShowControlAttr(ct);
                if (ControlPropPanel.Items && ControlPropPanel.Items["Width"])
                    ControlPropPanel.Update("Width", ct.Width);
                if (ControlPropPanel.Items && ControlPropPanel.Items["Height"])
                    ControlPropPanel.Update("Height", ct.Height);
                ct.UpdateLayout();
            }

            IsResizing = false;
        },
        Container: this
    });

    var SelectElement = function (e) {
        this.ReportMain.SelectControl(this);
        if (e) {
            if (this.IsIReportPanel) {
                this.SelectCell(e);
            }
            if (this.ParentControl != null && this.ParentControl.IsIReportPanel) {
                this.ParentControl.SelectCell(e);
            }
            StopEvent(e);
        }
        this.Container.Container.css("z-index", ZIndex++);
        OnSelectChanged(this);
    }
}

var ReportControl = function () {

    /*************基本属性*************/

    /// <summary>
    /// 数据源
    /// </summary>
    this.DataSource = null;

    /// <summary>
    /// 控件编号
    /// </summary>
    this.ID = null;

    /// <summary>
    /// 控件类型
    /// </summary>
    this.Type = null;

    /// <summary>
    /// 控件描述
    /// </summary>
    this.Name = null;

    /// <summary>
    /// 宽度
    /// </summary>
    this.Width = 0.0;

    /// <summary>
    /// 高度
    /// </summary>
    this.Height = 0.0;

    /// <summary>
    /// 水平对齐
    /// </summary>
    this.Halign = null;

    /// <summary>
    /// 垂直对齐
    /// </summary>
    this.Valign = null;

    /// <summary>
    /// 字体
    /// </summary>
    this.FontFamily = null;

    /// <summary>
    /// 字体加粗
    /// </summary>
    this.FontWeight = null;

    /// <summary>
    /// 字体颜色
    /// </summary>
    this.Foreground = null;

    /// <summary>
    /// 字体大小
    /// </summary>
    this.FontSize = null;

    /// <summary>
    /// 字体类型(斜体)
    /// </summary>
    this.FontStyle = null;

    /// <summary>
    /// 文字效果(下划线)
    /// </summary>
    this.TextDecorations = null;

    //在Grid中的位置
    this.GridRow = 0;
    this.GridCol = 0;
    this.GridRowSpan = 0;
    this.GridColSpan = 0;

    //页边距
    this.MarginLeftWidth = 0;
    this.MarginTopWidth = 0;
    this.MarginRightWidth = 0;
    this.MarginBottomWidth = 0;

    //内边距
    this.PaddingLeftWidth = 0;
    this.PaddingTopWidth = 0;
    this.PaddingRightWidth = 0;
    this.PaddingBottomWidth = 0;

    //背景颜色
    this.BackGroundColor;

    /// <summary>
    /// 实线或虚线
    /// </summary>
    this.BorderStyle;

    this.BorderColor;
    this.BorderLeftWidth = 0;
    this.BorderTopWidth = 0;
    this.BorderRightWidth = 0;
    this.BorderBottomWidth = 0;

    /**************默认属性***********/

    this.DefaultBackgroundColor = null;
    this.DefaultBorderColor = null;
    this.DefaultBorderStyle = null;
    this.DefaultBorderLeftWidth = 0;
    this.DefaultBorderTopWidth = 0;
    this.DefaultBorderRightWidth = 0;
    this.DefaultBorderBottomWidth = 0;


    /*************其他属性**********/

    /// <summary>
    /// 父控件
    /// </summary>
    this.ParentControl = null;

    /// <summary>
    /// 控件最外层
    /// </summary>
    this.Element = null;

    this.ReportMain = null;

    /// <summary>
    /// 需要显示的特殊菜单
    /// </summary>
    this.MenuItems = [
        {
            id: "m_delete",
            text: "删除",
            name: "Delete",
            iconCls: "icon-remove"
        }
        //,
        //{
        //    id: "m_property",
        //    text: "属性",
        //    name: "Property",
        //    iconCls: "icon-sum"
        //}
    ];

    //this.GetDataSource = function (key) {
    //    if (this.ReportMain && this.ReportMain.DataSources) {
    //        var ds;
    //        if (key && key != "-1") {
    //            ds = this.ReportMain.DataSources[key];
    //        }
    //        else {
    //            ds = this.FindParentDataSource();
    //        }
    //        return ds;
    //    }
    //}

    /// <summary>
    /// 是否可以改变大小
    /// </summary>
    this.IsCanChangeSize = true;

    this.IsAdded = false;

    this.ToXML = function () {
        return String.Empty;
    }

    this.ToCommonXml = function () {
        return String.Empty;
    }

    this.ToGroupXML = function (xml, group) {
        xml.Append("<Group>");
        xml.Append(this.GetPropXML("Name", group.Name));
        xml.Append(this.GetPropXML("GroupField", group.GroupField));
        xml.Append(this.GetPropXML("SortField", group.SortField));
        xml.Append(this.GetPropXML("SortType", group.SortType));
        xml.Append(this.GetPropXML("BreakPage", group.BreakType));
        xml.Append(this.GetPropXML("RepeatHeader", group.RepeatHeader));
        xml.Append(this.GetPropXML("RepeatFooter", group.RepeatFooter));
        xml.Append(this.GetPropXML("Top", group.Top));

        xml.Append("<GroupHeader>");
        xml.Append("<Height>" + group.Header.RowHeight + "</Height>");
        xml.Append(this.GetPropXML("Function", group.Header.Function));
        xml.Append("</GroupHeader>");

        xml.Append("<GroupFooter>");
        xml.Append("<Height>" + group.Footer.RowHeight + "</Height>");
        xml.Append(this.GetPropXML("Function", group.Footer.Function));
        xml.Append("</GroupFooter>");

        xml.Append("</Group>");
    }

    this.RenderBeginXML = function () {
        return "<" + this.Type + " ID=\"" + this.ID + "\" >";
    }

    this.RenderEndXML = function () {
        return "</" + this.Type + ">";
    }

    this.GetStylePropXML = function (value, name) {
        if (value) {
            return "<Item Name=\"" + name + "\" Value=\"" + value + "\" />";
        }
        return String.Empty;
    }
    this.GetTextXML = function (name, value) {
        if (value) {
            return "<" + name + "><![CDATA[" + value + "]]></" + name + ">";
        }

        return String.Empty;
    }
    this.GetPropXML = function (name, value) {
        if (value) {
            return "<" + name + ">" + value + "</" + name + ">";
        }

        return String.Empty;
    }

    this.GetCDataPropXML = function (name, value) {
        if (value) {
            return "<" + name + "><![CDATA[" + value + "]]></" + name + ">";
        }

        return String.Empty;
    }

    //ReportControl
    this.RenderCommonStyleXML = function () {
        var xml = new StringBuilder();
        if (this.ParentControl == null || this.ParentControl.IsReportList) {
            xml.Append(this.GetStylePropXML(this.Width, "width"));
            xml.Append(this.GetStylePropXML(this.Height, "height"));
            xml.Append(this.GetStylePropXML(this.MarginLeftWidth, "left"));
            xml.Append(this.GetStylePropXML(this.MarginTopWidth, "top"));
        }
        else { //table子元素 模拟合并单元格   

            //if (this.GridRow != 0 && this.ParentControl.Type != "Table")
            if (this.GridRow != 0)
                xml.Append(this.GetStylePropXML(this.GridRow, "Row"));

            if (this.GridCol != 0)
                xml.Append(this.GetStylePropXML(this.GridCol, "Column"));

            if (this.GridRowSpan != 1)
                xml.Append(this.GetStylePropXML(this.GridRowSpan, "RowSpan"));

            if (this.GridColSpan != 1)
                xml.Append(this.GetStylePropXML(this.GridColSpan, "ColSpan"));
        }

        xml.Append(this.GetStylePropXML(this.BackGroundColor, "background"));

        return xml.ToString();
    }

    this.GetBorderWidthXML = function () {
        return "<Item Name=\"BorderWidth\" Value=\"" +
                String.Join(",",
                this.BorderLeftWidth,
                this.BorderTopWidth,
                this.BorderRightWidth,
                this.BorderBottomWidth)
                + "\" />";
    }

    this.GetPaddingXML = function () {
        if (!this.PaddingLeftWidth && !this.PaddingTopWidth
                && !this.PaddingRightWidth && !this.PaddingBottomWidth) {
            return String.Empty;
        }
        else {
            return "<Item Name=\"Padding\" Value=\"" +
                    String.Join(",",
                    this.PaddingLeftWidth || 0,
                    this.PaddingTopWidth || 0,
                    this.PaddingRightWidth || 0,
                    this.PaddingBottomWidth || 0)
                    + "\" />";
        }
    }

    this.ToEventXML = function (xml, oEvent) {
        xml.Append("<Event>");
        xml.Append(this.GetPropXML("EventName", oEvent.EventName));
        xml.Append(this.GetPropXML("Action", oEvent.Action));
        xml.Append(this.GetPropXML("OpenWin", oEvent.OpenWin));
        xml.Append(this.GetPropXML("Url", oEvent.Url));
        xml.Append(this.GetPropXML("ChildReport", oEvent.ChildReport));

        if (oEvent.Parameters != null && oEvent.Parameters.length != 0) {
            xml.Append("<Parameters>");
            for (var i = 0; i < oEvent.Parameters.length; i++) {
                var para = oEvent.Parameters[i];
                xml.Append("<Parameter Name=\"" + para.Text + "\" Value=\"" + para.Value + "\" />");
            }

            xml.Append("</Parameters>");
        }

        xml.Append("</Event>");
    }

    this.ToCondXML = function (cond, xml) {
        xml.Append("<Item>");
        xml.Append(GetPropXML("Left", cond.Left));
        xml.Append(GetPropXML("Oper", cond.Oper));
        xml.Append(GetPropXML("Value", cond.Value));
        if (cond.Conditions != null && cond.Conditions.length != 0) {
            xml.Append("<Conditions>");
            for (var i = 0; i < cond.Conditions.length; i++) {
                var child = cond.Conditions[i];
                this.ToCondXML(child, xml);
            }
            xml.Append("</Conditions>");
        }
        xml.Append("</Item>");
    }

    /*********解析XML***********/

    /// <summary>
    /// 解释其他基本属性
    /// </summary>
    /// <param name="node"></param>
    this.ExplainControl = function (node) { }

    /// <summary>
    /// 解释子控件(控件创建后执行)
    /// </summary>
    /// <param name="node"></param>
    this.ExplainOther = function (node) { }

    /// <summary>
    /// 解释公共属性
    /// </summary>
    /// <returns></returns>
    this.ExplainCommonXml = function (node) {
        this.Name = node.children("Name").text();
        this.ID = node.attr("ID");

        var style = node.children("Style");
        if (style.length > 0) {
            var items = style.children();
            for (var i = 0; i < items.length; i++) {
                var item = $(items[i]);
                var val = item.attr("Value");
                var name = item.attr("Name").toLowerCase();
                switch (name) {
                    case "width":
                        this.Width = Z.V(val);
                        break;
                    case "height":
                        this.Height = Z.V(val);
                        break;
                    case "left":
                        this.MarginLeftWidth = Z.V(val);
                        break;
                    case "top":
                        this.MarginTopWidth = Z.V(val);
                        break;
                    case "column":
                        this.GridCol = Z.ToInt(val);
                        break;
                    case "row":
                        this.GridRow = Z.ToInt(val);
                        break;
                    case "colspan":
                        this.GridColSpan = Z.ToInt(val);
                        break;
                    case "rowspan":
                        this.GridRowSpan = Z.ToInt(val);
                        break;
                    case "background":
                        this.BackGroundColor = val;
                        break;
                    case "borderwidth":
                        var arrBorder = val.split(',');
                        this.BorderLeftWidth = Z.V(arrBorder[0]);
                        this.BorderTopWidth = Z.V(arrBorder[1]);
                        this.BorderRightWidth = Z.V(arrBorder[2]);
                        this.BorderBottomWidth = Z.V(arrBorder[3]);
                        break;
                    case "bordercolor":
                        this.BorderColor = val;
                        break;
                    case "borderstyle":
                        this.BorderStyle = val;
                        break;
                    case "padding":
                        var arrPadding = val.split(',');
                        this.PaddingLeftWidth = Z.V(arrPadding[0]);
                        this.PaddingTopWidth = Z.V(arrPadding[1]);
                        this.PaddingRightWidth = Z.V(arrPadding[2]);
                        this.PaddingBottomWidth = Z.V(arrPadding[3]);
                        break;
                    default:
                        this.ExplainAddtionStyleXml(item);
                        break;
                }
            }
        }
    }

    /// <summary>
    /// 解释特殊样式属性
    /// </summary>
    /// <param name="node"></param>
    this.ExplainAddtionStyleXml = function (node) { }

    /// <summary>
    /// 解析分组
    /// </summary>
    /// <param name="node"></param>
    this.ExplainGroupXML = function (node) {
        var group = new TableGroup();
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var item = nodes[i];
            var name = item.nodeName;
            item = $(item);
            var val = item.text();
            switch (name) {
                case "Name":
                    group.Name = val;
                    break;
                case "GroupField":
                    group.GroupField = val;
                    break;
                case "SortField":
                    group.SortField = val;
                    break;
                case "SortType":
                    group.SortType = val;
                    break;
                case "BreakPage":
                    group.BreakType = val;
                    break;
                case "RepeatFooter":
                    group.RepeatFooter = val;
                    break;
                case "RepeatHeader":
                    group.RepeatHeader = val;
                    break;
                case "Top":
                    group.Top = val;
                    break;
                case "GroupHeader":
                    var header = new TableGroupHeader();
                    header.RowHeight = Z.V(item.children("Height").text());
                    var functionHeader = item.children("Function");
                    if (functionHeader.length > 0) {
                        header.Function = functionHeader.text();
                    }
                    header.Name = group.Name;
                    group.Header = header;
                    break;
                case "GroupFooter":
                    var footer = new TableGroupFooter();
                    footer.RowHeight = Z.V(item.children("Height").text());
                    var functionFooter = item.children("Function");
                    if (functionFooter.length > 0) {
                        footer.Function = functionFooter.text();
                    }
                    footer.Name = group.Name;
                    group.Footer = footer;
                    break;
            }

        }
        return group;
    }

    /// <summary>
    /// 解析事件
    /// </summary>
    /// <param name="node"></param>
    /// <returns></returns>
    this.ExplainEvent = function (node) {
        var oEvent = {};

        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            var val = elem.text();
            switch (name) {
                case "EventName":
                    oEvent.EventName = val;
                    break;
                case "Action":
                    oEvent.Action = val;
                    break;
                case "OpenWin":
                    oEvent.OpenWin = val;
                    break;
                case "Url":
                    oEvent.Url = val;
                    break;
                case "ChildReport":
                    oEvent.ChildReport = val;
                    break;
                case "Parameters":
                    var paras = elem.children();
                    oEvent.Parameters = [];
                    for (var i = 0; i < paras.length; i++) {
                        var paraNode = paras[i];
                        var para = {};
                        para.Text = paraNode.attr("Name");
                        para.Value = paraNode.attr("Value");
                        oEvent.Parameters.push(para);
                    }
                    break;
            }
        }

        return oEvent;
    }

    this.ExpainConditions = function (node) {
        var cond = {};
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var item = nodes[i];
            var name = item.nodeName;
            item = $(item);
            var val = item.text();
            switch (name) {
                case "Left":
                    cond.Left = val;
                    break;
                case "Opter":
                    cond.Oper = val;
                    break;
                case "Value":
                    cond.Value = val;
                    break;
                case "Conditions":
                    cond.Conditions = [];
                    var childs = item.children();
                    for (var i = 0; i < childs.length; i++) {
                        var child = childs[i];
                        cond.Conditions.push(this.ExpainConditions(child));
                    }
                    break;
            }
        }
        return cond;
    }

    this.Init = function () {
        this.GridRow = 0;
        this.GridCol = 0;
        this.GridRowSpan = 1;
        this.GridColSpan = 1;
        this.PaddingBottomWidth = 0;
        this.PaddingLeftWidth = 0;
        this.PaddingRightWidth = 0;
        this.PaddingTopWidth = 0;

        //this.DefaultBackgroundColor = "White";
        this.DefaultBorderBottomWidth = 0;
        this.DefaultBorderColor = "Black";
        this.DefaultBorderLeftWidth = 0;
        this.DefaultBorderRightWidth = 0;
        this.DefaultBorderTopWidth = 0;
        this.DefaultBorderStyle = "none";
    }

    /// <summary>
    /// 创建控件 ReportControl
    /// </summary>
    this.CreateElement = function () {
        if (this.ID == null) {
            this.ID = this.ReportMain.GetNewID();
        }

        if (this.Name == null) {
            this.Name = this.ID;
        }

        this.Create();

        this.Element.Name = this.ID;
        $(this.Element).data("Tag", this).attr("id", this.ID);

        this.ReportMain.AllIds.push(this.ID);
    }

    this.UnFocus = function () {
        if (this.Container) {
            this.Container.RemoveSelectedStyle();
        }
        if (this.OnUnFocus) {
            this.OnUnFocus();
        }
    }

    this.Focus = function () {
        if (this.Container) {
            this.Container.AddSelectedStyle();
        }
        if (this.OnFocus) {
            this.OnFocus();
        }
    }

    this.Create = function () {
    }

    //ReportControl
    this.ShowProp = function () {
        ReportMain.SelectControl(this);
        ShowControlAttr(this);
    }

    /// <summary>
    /// 创建右键菜单
    /// </summary>
    //this.CreateContextMenu = function () { }

    /// <summary>
    /// 执行菜单方法
    /// </summary>
    this.ExcuteMenuCommand = function (commandname) {
        switch (commandname) {
            case "Delete":
                this.Remove();
                break;
            case "Property":
                this.ShowProp();
                break;
            case "TextBoxSameRowStyle":
                this.IsSameRowStyle = true;
                this.ApplyCommonProps();
                break;
            case "TextBoxSameColStyle":
                this.IsSameColStyle = true;
                this.ApplyCommonProps();
                break;
            default:
                var parent = this.ParentControl;
                if (parent && parent.IsIReportPanel) {
                    parent.ExcuteMenuCommand(commandname);
                }
                break;
        }
    }

    this.Remove = function () {
        if (this.ParentControl != null) {
            var panel = this.ParentControl;
            panel.RemoveChild(this);
        }
        else {
            this.ReportMain.RemoveChild(this);
        }
        this.Container.Remove();
        this.Element = null;
        this.ReportMain.SelectedReportControl = null;
    }

    //ReportControl
    this.UpdateLayout = function () {
        this.ApplyDefaultStyle();
        if (this.ParentControl != null && this.ParentControl.IsIReportPanel) {
            var cell = this.Element.closest("td");
            var isDisplay = cell.is(":visible");
            this.Width = isDisplay ? (cell.innerWidth() - this.BorderLeftWidth - this.BorderRightWidth - this.PaddingLeftWidth - this.PaddingRightWidth) : NaN;
            this.Height = isDisplay ? (cell.innerHeight() - this.BorderBottomWidth - this.BorderTopWidth - this.PaddingBottomWidth - this.PaddingTopWidth) : NaN;
        }
        this.ApplyCommonProps();
    }
    //ReportControl
    this.ApplyDefaultStyle = function () {
        if (this.DefaultBackgroundColor) {
            $(this.Element).css("background-color", this.DefaultBackgroundColor);
        }
        else {
            $(this.Element).css("background", "transparent");
        }

        $(this.Element).css("border-color", this.DefaultBorderColor);
        $(this.Element).css("border-width", String.Join(",", this.DefaultBorderTopWidth, this.DefaultBorderRightWidth, this.DefaultBorderBottomWidth, this.DefaultBorderLeftWidth));
    }

    //ReportControl
    this.ApplyCommonProps = function () {

        this.MarginTopWidth = (Z.V(this.MarginTopWidth) || 0);
        this.MarginLeftWidth = (Z.V(this.MarginLeftWidth) || 0);
        this.PaddingTopWidth = Z.SafeToInt(this.PaddingTopWidth);
        this.PaddingRightWidth = Z.SafeToInt(this.PaddingRightWidth);
        this.PaddingBottomWidth = Z.SafeToInt(this.PaddingBottomWidth);
        this.PaddingLeftWidth = Z.SafeToInt(this.PaddingLeftWidth);
        var padding = String.Join(" ", this.PaddingTopWidth + "px",
                                    this.PaddingRightWidth + "px",
                                    this.PaddingBottomWidth + "px",
                                    this.PaddingLeftWidth + "px");
        this.BorderTopWidth = Z.SafeToInt(this.BorderTopWidth);
        this.BorderRightWidth = Z.SafeToInt(this.BorderRightWidth);
        this.BorderBottomWidth = Z.SafeToInt(this.BorderBottomWidth);
        this.BorderLeftWidth = Z.SafeToInt(this.BorderLeftWidth);

        $(this.Element).css("padding", padding)
        .css("border-color", GetValidColor(this.BorderColor))
        .css("color", this.Foreground)
        .css("background-color", this.BackGroundColor)
        .css("font-family", this.FontFamily);
        $(this.Element).css("width", isNaN(this.Width) ? "100%" : Z.ToInt(this.Width - 4))//减去4pxContainer
        .css("text-align", this.TextAlign)
        .css("height", isNaN(this.Height) ? "100%" : Z.ToInt(this.Height - 4))
        .css("vertical-align", this.TextValign == "Center" ? "middle" : this.TextValign)
        .css("font-style", this.FontStyle)
        .css("font-size", Z.SafeToInt(this.FontSize, 12) + "px")
        .css("font-weight", this.FontWeight)
        .css("text-decoration", this.TextDecorations);
        if (!isNaN(this.Width))
            this.Width = Z.ToInt(this.Width);
        if (!isNaN(this.Height))
            this.Height = Z.ToInt(this.Height);
        if (this.BorderBottomWidth > 0) {
            $(this.Element).css("border-bottom-width", this.BorderBottomWidth)
                .css("border-bottom-style", this.BorderStyle);
        }
        if (this.BorderLeftWidth > 0) {
            $(this.Element).css("border-left-width", this.BorderLeftWidth)
                .css("border-left-style", this.BorderStyle);
        }

        if (this.BorderRightWidth > 0) {
            $(this.Element).css("border-right-width", this.BorderRightWidth)
                .css("border-right-style", this.BorderStyle);
        }

        if (this.BorderTopWidth > 0) {
            $(this.Element).css("border-top-width", this.BorderTopWidth)
                .css("border-top-style", this.BorderStyle);
        }

        if (this.Container) {
            var container = this.Container.Container;
            container.css("top", (Z.V(this.MarginTopWidth) || 0))
            .css("left", (Z.V(this.MarginLeftWidth) || 0));
            var cw = isNaN(this.Width) ? '100%' : this.Element.outerWidth();
            var ch = isNaN(this.Height) ? '100%' : this.Element.outerHeight();
            container.css({
                width: cw + 4,
                height: ch + 4
            });
        }
    }

    var GetValidColor = function (color) {
        if (color && color.length == 9) {
            return ("#" + color.substr(3));
        }
        return color;
    }

    this.IsInLayoutPanel = function () {
        return (this.ParentControl != null && this.ParentControl.IsIReportPanel);
    }

    this.MergeRowColSpan = function () {
        var td = $(this.Element).closest("td");
        var tr = $(this.Element).closest("tr");
        MergeCell(tr, td, this.GridColSpan);
        MergeRow(tr, td, this.GridRowSpan);
    }
}

var ReportManager = function () {

    this.Type = "ReportManager";

    this.UpdateLayout = function () {
        if (this.Elements) {
            for (var i = 0; i < this.Elements.length; i++) {
                var elem = this.Elements[i];
                elem.UpdateLayout();
            }
        }
    }
    //TODO:效率问题
    //考虑到效率问题,是否应该使用$.data()缓存
    this.GetControlByID = function (id) {
        if (id) {
            return $("#" + id).data("Tag");
        }
        return null;
    }

    this.SelectControl = function (ctrl) {
        var selected = this.SelectedReportControl;
        if (selected != null && selected != ctrl) {
            selected.Container.RemoveSelectedStyle();
            selected.UnFocus();
        }

        this.SelectedReportControl = ctrl;
        if (ctrl) {
            ctrl.Focus();
            //if (ctrl.ParentControl != null && ctrl.ParentControl.IsIReportPanel) {
            //    ctrl.ParentControl.SelectCell(e);
            //}
        }
    }

    /**********报表基本属性**********/

    /// <summary>
    /// 编号
    /// </summary>
    this.ID = 0;
    /// <summary>
    /// 模板ID
    /// </summary>
    this.TemplateID = 0;
    /// <summary>
    /// 报表名称
    /// </summary>
    this.Name = "";

    /// <summary>
    /// 报表描述
    /// </summary>
    this.Memo = "";

    /// <summary>
    /// 创建人
    /// </summary>
    this.CreateUser = null;

    /// <summary>
    /// 创建时间
    /// </summary>
    this.CreateDate = null;

    this.TableId = null;

    this.DataSource = "";

    /// <summary>
    /// 报表宽度(cm)
    /// </summary>
    this.Width = 20.9; //0;

    /// <summary>
    /// 报表页高度
    /// </summary>
    this.Height = 29.7;// 0;

    /// <summary>
    /// 单位
    /// </summary>
    this.ReportUnit = null;


    //边距
    this.MarginLeft = 0;
    this.MarginRight = 0;
    this.MarginTop = 0;
    this.MarginBottom = 0;

    /// <summary>
    /// 格式化图片
    /// </summary>
    this.ListFormatImages = null;

    /// <summary>
    /// 数字格式
    /// </summary>
    this.DecimalFormat = null;

    /// <summary>
    /// 日期格式
    /// </summary>
    this.DateFormat = null;

    /// <summary>
    /// 是否显示0
    /// </summary>
    this.IsNotShowZero = null;


    /// <summary>
    /// 参数
    /// </summary>
    this.Parameters = null;

    /// <summary>
    /// 默认打印方式
    /// </summary>
    this.PrintType = null;
    /// <summary>
    /// 默认纸张
    /// </summary>
    this.PaperType = 0;
    /// <summary>
    /// 是否打印背景图片
    /// </summary>
    this.IsPrintBackGround = null;

    /// <summary>
    /// 显示页眉
    /// </summary>
    this.IsShowHeader = 0;

    /// <summary>
    /// 显示页脚
    /// </summary>
    this.IsShowFooter = 0;

    this.HeaderPos = 32;

    this.FooterPos = 32;


    /************其他属性************/

    this.ReportUserControl = null;

    this.designerPanel = null;

    this.AllIds = [];

    this.Elements = [];

    this.IsCanSmallChange = true;

    /// <summary>
    /// 数据源
    /// </summary>
    this.DataSources = [];

    this.SelectedReportControl = null;

    this.GridPageHeader = null; //页眉控件
    this.GridPageFooter = null; //页脚控件

    this.ActionReadOver = null;

    this.ActionSaveOver = null;

    /************加载报表***************/

    this.LoadReport = function () {
        //this.DataSources = [];
        if (this.ID > 0) {
            $this = this;
            EMW.API.UserFileAPI.LoadUserFile(this.ID, function (data) {
                $this.ReadReportOver(data);
            });
        }
    }

    this.ReadReportOver = function (userfile) {
        if (userfile != null) {
            this.ID = userfile.ID;
            this.Name = userfile.Name;
            this.Memo = userfile.Memo;
            this.DataSource = userfile.DataSource;

            var xml = userfile.Content;
            var root = LoadXMLDom(xml);
            var nodes = root.children();
            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                var name = node.nodeName;
                node = $(node);
                var explainFn = this["Explain" + name];
                if ($.isFunction(explainFn)) {
                    explainFn.call(this, node);
                }
            }
        }
        //显示页面页脚
        this.ShowHeaderFooter();
        this.SelectedReportControl = null;
        this.UpdateLayout();
        if (null != this.ActionReadOver) {
            this.ActionReadOver();

        }
    }
    this.ExplainItems = function (node) {
        this.ExplainControls(node, null);
    }

    this.ExplainPrint = function (node) {
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "MarginLeft":
                    this.MarginLeft = Z.V(elem.text());
                    break;
                case "MarginTop":
                    this.MarginTop = Z.V(elem.text());
                    break;
                case "MarginRight":
                    this.MarginRight = Z.V(elem.text());
                    break;
                case "MarginBottom":
                    this.MarginBottom = Z.V(elem.text());
                    break;
                case "PaperType":
                    this.PaperType = elem.text();
                    break;
                case "PrintType":
                    this.PrintType = elem.text();
                    break;
                case "PrintBackground":
                    this.IsPrintBackGround = elem.text();
                    break;
            }
        }
    }

    this.ExplainFormats = function (node) {
        var elems = node.children();
        this.ListFormatImages = [];
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            var format = {};

            var props = elem.children();
            for (var j = 0; j < props.length; j++) {
                var prop = props[j];
                var name = prop.nodeName;
                prop = $(prop);
                switch (name) {
                    case "Name":
                        format.Name = prop.text();
                        break;
                    case "Src":
                        format.Src = prop.text();
                        break;
                    case "Width":
                        format.Width = prop.text();
                        break;
                    case "Height":
                        format.Height = prop.text();
                        break;
                }
            }

            this.ListFormatImages.push(format);
        }
    }

    //this.ExplainDataFormat = function (node) {
    //    var elems = node.children();
    //    for (var i = 0; i < elems.length; i++) {
    //        var elem = elems[i];
    //        var name = elem.nodeName;
    //        elem = $(elem);
    //        switch (name) {
    //            case "Decimal":
    //                this.DecimalFormat = elem.text();
    //                break;
    //            case "NotShowZero":
    //                this.IsNotShowZero = elem.text();
    //                break;
    //            case "DateFormat":
    //                this.DateFormat = elem.text();
    //                break;
    //        }
    //    }
    //}

    this.ExplainParameters = function (node) {
        this.Parameters = [];
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            var para = {};
            elem = $(elem);
            var props = elem.children();
            for (var j = 0; j < props.length; j++) {
                var prop = props[j];
                var name = prop.nodeName;
                prop = $(prop);
                switch (name) {
                    case "IsVal":
                        para.IsVal = prop.text();
                        break;
                    case "Name":
                        para.Name = prop.text();
                        break;
                    case "DataType":
                        para.DataType = prop.text();
                        break;
                    case "Type":
                        para.Type = prop.text();
                        break;
                    case "Text":
                        para.Text = prop.text();
                        break;
                    case "ShowType":
                        para.ShowType = prop.text();
                        break;
                    case "DefaultValues":
                        para.DefaultValues = [];
                        var dfElems = prop.children();
                        for (var k = 0; k < dfElems.length; k++) {
                            var dfElem = $(dfElems[k]);
                            para.DefaultValues.push(dfElem.text());
                        }
                        break;
                    case "Values":
                        para.Values = [];
                        var valElems = prop.children();
                        for (var h = 0; h < valElems.length; h++) {
                            var valElem = $(valElems[h]);
                            para.Values.push({
                                Text: valElem.attr("Text"),
                                Value: valElem.attr("Value")
                            });
                        }
                        break;
                    case "SearchSet":
                        para.SearchSet = prop.text();
                        break;
                }
            }
            this.Parameters.push(para);
        }
    }

    this.ExplainDataSources = function (node) {
        this.DataSources = ConvertDS(node);
    }
    //默认数据源
    this.ExplainDataSource = function (node) {
        this.DataSource = node.text();
    }

    this.ExplainInfo = function (node) {
        this.Name = node.children("Name").text();
        this.Memo = node.children("Memo").text();
    }

    this.ExplainSize = function (node) {
        this.Width = Z.V(node.children("Width").text());
        this.Height = Z.V(node.children("Height").text());
        this.ReportUnit = Z.V(node.children("Unit").text());
    }

    this.ExplainHeader = function (node) {
        this.IsShowHeader = 1;
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "Height":
                    this.HeaderPos = Z.V(elem.text());
                    break;
                case "Items":
                    this.ExplainControls(elem, null);
                    break;
            }
        }
    }

    this.ExplainFooter = function (node) {
        this.IsShowFooter = 1;
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "Height":
                    this.FooterPos = Z.V(elem.text());
                    break;
                case "Items":
                    this.ExplainControls(elem, null);
                    break;
            }
        }
    }

    this.CreateControl = function (node) {
        var ctrl = new Function("return new Report" + node[0].nodeName + "();").call();
        ctrl.ReportMain = this;
        ctrl.ExplainCommonXml(node);
        ctrl.ExplainControl(node);
        ctrl.CreateElement();
        ctrl.ExplainOther(node);
        return ctrl;
    }

    //ReportManager
    this.ExplainControls = function (node, parentControl) {
        if (node != null) {
            var items = node.children();
            for (var i = 0; i < items.length; i++) {
                this.SelectControl(null);
                var item = items[i];
                var ctrl = this.CreateControl($(item));
                if (parentControl != null) {
                    container = new ControlContainer(ctrl);
                    parentControl.AddChild(ctrl);
                }
                else {
                    this.AddChild(ctrl);
                }
                ctrl.Container.RemoveSelectedStyle();

                ctrl.MergeRowColSpan();
            }
        }
    }
    /*******************保存报表****************/

    /// <summary>
    /// 报表基本属性XML
    /// </summary>
    /// <returns></returns>
    this.ToReportPropertyXml = function () {
        var xml = new StringBuilder();

        //常规
        xml.Append("<Info>");
        xml.Append("<Name>" + this.Name + "</Name>");
        xml.Append("<CreateUser>" + EMW.Global.User.ID + "</CreateUser>");
        xml.Append("<CreateDate>" + (new Date()).ToDateString() + "</CreateDate>");
        xml.Append("<Memo>" + this.Memo + "</Memo>");
        xml.Append("</Info>");

        //if (this.AllowMail) {
        //    xml.Append("<Mail Allow=\"1\"><![CDATA[" + this.MailValue + "]]></Mail>");
        //}

        //大小
        xml.Append("<Size>");
        xml.Append("<Width>" + this.Width + "</Width>");
        xml.Append("<Height>" + this.Height + "</Height>");
        xml.Append("<Unit>cm</Unit>");
        xml.Append("</Size>");

        //打印格式
        xml.Append("<Print>");

        if (!isNaN(this.MarginLeft) && this.MarginLeft != 0) {
            xml.Append("<MarginLeft>" + this.MarginLeft + "</MarginLeft>");
        }
        if (!isNaN(this.MarginTop) && this.MarginTop != 0) {
            xml.Append("<MarginTop>" + this.MarginTop + "</MarginTop>");
        }
        if (!isNaN(this.MarginRight) && this.MarginRight != 0) {
            xml.Append("<MarginRight>" + this.MarginRight + "</MarginRight>");
        }
        if (!isNaN(this.MarginBottom) && this.MarginBottom != 0) {
            xml.Append("<MarginBottom>" + this.MarginBottom + "</MarginBottom>");
        }

        if (this.PaperType) {
            xml.Append("<PaperType>" + this.PaperType + "</PaperType>");
        }

        if (this.PrintType == 1) {
            xml.Append("<PrintType>" + this.PrintType + "</PrintType>");
        }

        if (this.IsPrintBackGround == "1") {
            xml.Append("<PrintBackground>" + this.IsPrintBackGround + "</PrintBackground>");
        }

        xml.Append("</Print>");

        //报表格式

        if (this.ListFormatImages != null) {
            xml.Append("<Formats>");
            for (var i = 0; i < this.ListFormatImages.length; i++) {
                var format = this.ListFormatImages[i];
                xml.Append("<Item>");
                xml.Append("<Name>" + format.Name + "</Name>");
                xml.Append("<Src>" + format.Src + "</Src>");
                xml.Append("<Width>" + format.Width + "</Width>");
                xml.Append("<Height>" + format.Height + "</Height>");
                xml.Append("</Item>");
            }
            xml.Append("</Formats>");
        }

        if (this.DateFormat || this.DecimalFormat) {
            xml.Append("<DataFormat>");
            if (this.DecimalFormat) {
                xml.Append("<Decimal>" + this.DecimalFormat + "</Decimal>");
            }
            if (this.IsNotShowZero == "1") {
                xml.Append("<NotShowZero>" + this.IsNotShowZero + "</NotShowZero>");
            }
            if (this.DateFormat) {
                xml.Append("<DateFormat>" + this.DateFormat + "</DateFormat>");
            }
            xml.Append("</DataFormat>");
        }

        //参数
        this.ToParametersXML(xml);

        //页眉和页脚
        if (this.IsShowHeader == 1) {
            xml.Append("<Header>");
            xml.Append("<Height>" + this.HeaderPos + "</Height>");
            xml.Append("<Items>");
            for (var j = 0; j < this.Elements.length; j++) {
                var ctrl = this.Elements[j];
                ctrl.IsAdded = false;
                if (ctrl.MarginTopWidth < this.HeaderPos) {
                    xml.Append(ctrl.ToXML());
                    ctrl.IsAdded = true;
                }
            }
            xml.Append("</Items>");
            xml.Append("</Header>");
        }

        if (this.IsShowFooter == 1) {
            xml.Append("<Footer>");
            xml.Append("<Height>" + this.FooterPos + "</Height>");
            xml.Append("<Items>");
            for (var k = 0; k < this.Elements.length; k++) {
                var ctrl = this.Elements[k];
                if (ctrl.MarginTopWidth > (this.GridPageFooter.parent().height() - this.FooterPos) && !ctrl.IsAdded) {
                    xml.Append(ctrl.ToXML());
                    ctrl.IsAdded = true;
                }
            }
            xml.Append("</Items>");
            xml.Append("</Footer>");
        }

        return xml.ToString();
    }

    this.ToParametersXML = function (xml) {
        if (this.Parameters != null && this.Parameters.length != 0) {
            xml.Append("<Parameters>");
            for (var i = 0; i < this.Parameters.length; i++) {
                var para = this.Parameters[i];
                xml.Append("<Parameter>");
                if (para.IsVal == "1") {
                    xml.Append("<IsVal>1</IsVal>");
                }
                xml.Append("<Name>" + para.Name + "</Name>");
                xml.Append("<DataType>" + para.DataType + "</DataType>");
                xml.Append("<Type>" + para.Type + "</Type>");
                xml.Append("<Text>" + para.Text + "</Text>");
                xml.Append("<ShowType>" + para.ShowType + "</ShowType>");

                if (para.DefaultValues != null && para.DefaultValues.length != 0) {
                    xml.Append("<DefaultValues>");
                    for (var j = 0; j < para.DefaultValues.length; j++) {
                        var val = para.DefaultValues[j];
                        xml.Append("<Value><![CDATA[" + val + "]]></Value>");
                    }
                    xml.Append("</DefaultValues>");
                }

                if (para.Values != null && para.Values.length != 0) {
                    xml.Append("<Values>");
                    for (var k = 0; k < para.Values.length; k++) {
                        var val = para.Values[k];
                        xml.Append("<Value Text=\"" + val.Text + "\" Value=\"" + val.Value + "\" />");
                    }
                    xml.Append("</Values>");
                }
                if (para.SearchSet) {
                    xml.Append("<SearchSet><![CDATA[" + para.SearchSet + "]]></SearchSet>");
                }
                xml.Append("</Parameter>");
            }
            xml.Append("</Parameters>");
        }
    }

    /// <summary>
    /// 数据源XMl
    /// </summary>
    /// <returns></returns>
    this.ToDataSourceXml = function () {
        var xml = new StringBuilder();
        xml.Append("<DataSources>");
        xml.Append(DataSourceToXML(this.DataSources));
        xml.Append("</DataSources>");
        //添加报表默认数据源
        xml.Append("<DataSource>");
        xml.Append(this.DataSource);
        xml.Append("</DataSource>");
        return xml.ToString();
    }

    this.SaveReport = function () {

        if (!this.Name) {
            //  EMW.API.MessageBox.Warning("报表名称不能为空");
            var table = EMW.UI.Dialog({
                content: "<h3>报表名称不能为空</h3>",
                title: "错误提示!!!",
                width: 250,
                height: 180
            });
            ShowReportPropertyPanel();
            return;
        }

        var xml = new StringBuilder();
        xml.Append("<Report>");

        //基本属性
        xml.Append(this.ToReportPropertyXml());

        //数据源
        xml.Append(this.ToDataSourceXml());

        xml.Append("<Items>");
        //报表控件
        var result = this.Elements.OrderBy(function (x) {
            return x.MarginTopWidth;
        });
        for (var i = 0; i < result.length; i++) {
            var ctrl = result[i];
            if (!ctrl.IsAdded) {
                xml.Append(ctrl.ToXML());
            }
        }
        xml.Append("</Items>");
        xml.Append("</Report>");
        var userFile = {
            TemplateID: this.TemplateID,
            ID: this.ID,
            Name: this.Name,
            Memo: this.Memo,
            TableId: this.TableId || 0,
            DataSource: this.DataSource || 0,
            UserFileType: 2,
            Content: xml.ToString(),
            Language: 0
        };
        var $this = this;
        EMW.API.UserFileAPI.SaveUserFile(userFile, function (data) {
            $this.SaveOver(data);
        });
    }

    this.SaveNewReport = function () {
        this.ID = 0;
        this.Name = this.Name + "_1";
        this.SaveReport();
    }

    this.SaveOver = function (reportid) {
        this.ID = reportid;
        if ($.isFunction(this.ActionSaveOver)) {
            this.ActionSaveOver();
        }
    }

    //方法

    /// <summary>
    /// 得到新的编号
    /// </summary>
    /// <returns></returns>
    this.GetNewID = function () {
        var index = 1;
        while (this.AllIds.Contains("Element" + index)) {
            index++;
        }
        return ("Element" + index);
    }

    /***************添加或删除子控件******************/

    /// 添加子控件到报表上
    //ReportMananger
    this.AddChild = function (ctrl) {
        var container = ctrl.Container;
        if (!container) {
            container = new ControlContainer(ctrl);
        }
        else {
            container.Container.removeAttr("style");
        }
        var selected = this.SelectedReportControl;

        var nestTable = ctrl.Type != "LayoutTable" && ctrl.Type != "CrossTable" && ctrl.Type != "Table";
        //表格禁止嵌套
        if (selected != null && selected.IsIReportPanel && selected != ctrl && nestTable) {
            this.SelectedReportControl.AddChild(ctrl);
            // ShowControlAttr(ctrl);
        }
        else {
            this.designerPanel.append(container.Container);
            this.Elements.push(ctrl);
            ctrl.IsCanChangeSize = true;
        }
        if (selected) {
            selected.UnFocus();
        }
        //防止控件加入到trHeader表格中
        if (ctrl.Elements != null) {
            this.SelectedReportControl = ctrl;
        }
        ctrl.UpdateLayout();
    }

    this.RemoveChild = function (ctrl) {
        this.Elements.Remove(ctrl);
        $(ctrl.Element).remove();
    }

    //页面和页脚
    this.ShowHeaderFooter = function () {
        if (this.IsShowHeader == 1) {
            $(this.GridPageHeader).show().css("height", this.HeaderPos);
        }
        else {
            $(this.GridPageHeader).hide();
        }
        if (this.IsShowFooter == 1) {
            $(this.GridPageFooter).show().css("height", this.FooterPos);
        }
        else {
            $(this.GridPageFooter).hide();
        }
    }

    //加载背景图片

    this.LoadBackgroudImage = function (url) {
        if (url) {
            $(".designer-grid").css("background-image", String.Concat("url('", url, "')"));
        }
        else {
            $(".designer-grid").css("background-image", "");
        }
    }

}
/***********报表控件***************/

/****文本框****/
var ReportTextBox = function () {
    this.Text = String.Empty;
    this.IsWrap = null;
    this.OutPut = null;
    this.TextAlign = null;
    this.TextValign = null;

    this.IsSameRowStyle = false;
    this.IsSameColStyle = false;

    this.Event = null;

    //{构造函数
    this.Type = "TextBox";
    this.Width = 100;
    this.Height = 22;
    this.Halign = "Left";
    this.Valign = "Top";

    this.DefaultBackgroundColor = "White";
    //}

    //////////////解析XML
    //ReportTextBox
    this.ExplainAddtionStyleXml = function (node) {
        var val = node.attr("Value")
        var name = node.attr("Name").toLowerCase();
        switch (name) {
            case "halign":
                this.TextAlign = val;
                break;
            case "valign":
                this.TextValign = val;
                break;
            case "fontsize":
                this.FontSize = val;
                break;
            case "fontweight":
                this.FontWeight = val;
                break;
            case "foreground":
                this.Foreground = val;
                break;
            case "fontstyle":
                this.FontStyle = val;
                break;
            case "fontfamily":
                this.FontFamily = val;
                break;

        }
    }
    //ReportTextBox
    this.ExplainControl = function (node) {
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "Value":
                    this.Text = GetCData(elem);
                    break;
                case "IsWrap":
                    this.IsWrap = elem.text();
                    break;
                case "OutPut":
                    this.OutPut = elem.text();
                    break;
                case "Event":
                    this.Event = this.ExplainEvent(elem);
                    break;
            }
        }
    }
    //this.MenuItems = new Array().concat(this.MenuItems);
    this.Create = function () {
        if (!this.Text) {
            //this.Text = this.ID;
        }
        this.Element = $("<div></div>")
                .addClass("el-textbox")
                .addClass("el-textbox-default")
                .attr("title", "文本框-" + this.ID);
    }

    var baseApplyCommonProps = this.ApplyCommonProps;
    //ReportTextBox
    this.ApplyCommonProps = function () {
        baseApplyCommonProps.call(this);
        this.SetText(this.Text);
        if (this.IsSameRowStyle) {
            if (this.ParentControl != null && this.ParentControl.IsIReportPanel) {
                var parentPanel = this.ParentControl;
                var children = null;
                //同行/同列应用样式
                if (parentPanel.Type == "LayoutTable") {
                    children = parentPanel.ChildControls;
                }
                else {
                    children = parentPanel.GetRowType(this.GridRow).Items;
                }
                for (var i = 0; i < children.length; i++) {
                    var child = children[i];
                    if (child != this && child.Type == "TextBox") {
                        if (child.GridRow == this.GridRow) {
                            this.CopyStyle(child);
                        }
                    }
                }
            }
            this.IsSameRowStyle = false;
        }

        if (this.IsSameColStyle) {
            if (this.ParentControl != null && this.ParentControl.IsIReportPanel) {
                var parentPanel = this.ParentControl;
                for (var j = 0; j < parentPanel.ChildControls.length; j++) {
                    var child = parentPanel.ChildControls[j];
                    if (child != this && child.Type == "TextBox") {
                        if (child.GridCol == this.GridCol) {
                            this.CopyStyle(child);
                        }
                    }
                }
            }
            this.IsSameColStyle = false;
        }
    }

    this.ToXML = function () {
        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        xml.Append("<Value><![CDATA[" + this.Text + "]]></Value>");

        if (this.IsWrap == "1") {
            xml.Append("<IsWrap>1</IsWrap>");
        }

        if (this.OutPut == "0") {
            xml.Append("<OutPut>0</OutPut>");
        }

        xml.Append("<Style>");

        xml.Append(this.GetStylePropXML(this.FontFamily, "fontFamily"));
        xml.Append(this.GetStylePropXML(this.FontSize, "fontSize"));
        xml.Append(this.GetStylePropXML(this.BorderStyle, "BorderStyle"));
        if (this.BorderStyle) {
            xml.Append(this.GetBorderWidthXML());
            xml.Append(this.GetStylePropXML(this.BorderColor, "BorderColor"));
        }

        xml.Append(this.GetStylePropXML(this.FontWeight, "fontWeight"));
        xml.Append(this.GetStylePropXML(this.Foreground, "Foreground"));
        xml.Append(this.GetStylePropXML(this.FontStyle, "fontStyle"));

        if (this.TextAlign != "Left") {
            xml.Append(this.GetStylePropXML(this.TextAlign, "Halign"));
        }

        if (this.TextValign != "Top") {
            xml.Append(this.GetStylePropXML(this.TextValign, "Valign"));
        }

        xml.Append(this.GetPaddingXML());
        //  xml.Append(this.GetBorderWidthXML());

        xml.Append(this.RenderCommonStyleXML());


        xml.Append("</Style>");

        if (this.Event != null) {
            this.ToEventXML(xml, this.Event);
        }

        xml.Append("<Name>" + this.Name + "</Name>");
        xml.Append(this.RenderEndXML());
        return xml.ToString();
    }

    this.SetText = function (text) {
        this.Element.html(text || this.ID);
    }

    /// <summary>
    /// 应用相同样式
    /// </summary>
    /// <param name="ctrl"></param>
    this.CopyStyle = function (ctrl) {
        ctrl.PaddingLeftWidth = this.PaddingLeftWidth;
        ctrl.PaddingTopWidth = this.PaddingTopWidth;
        ctrl.PaddingRightWidth = this.PaddingRightWidth;
        ctrl.PaddingBottomWidth = this.PaddingBottomWidth;

        ctrl.FontSize = this.FontSize;
        ctrl.FontFamily = this.FontFamily;
        ctrl.FontStyle = this.FontStyle;
        ctrl.FontWeight = this.FontWeight;
        ctrl.Foreground = this.Foreground;

        ctrl.TextAlign = this.TextAlign;
        ctrl.TextDecorations = this.TextDecorations;
        ctrl.TextValign = this.TextValign;

        ctrl.BorderColor = this.BorderColor;
        ctrl.BorderLeftWidth = this.BorderLeftWidth;
        ctrl.BorderRightWidth = this.BorderRightWidth;
        ctrl.BorderTopWidth = this.BorderTopWidth;
        ctrl.BorderBottomWidth = this.BorderBottomWidth;
        ctrl.BackGroundColor = this.BackGroundColor;
        ctrl.BorderStyle = this.BorderStyle;

        ctrl.UpdateLayout();
    }
}
ReportTextBox.prototype = new ReportControl();
ReportTextBox.prototype.OnUnFocus = function () {
}
ReportTextBox.prototype.OnFocus = function () {
}

var RowDefinition = function (height) {
    this.Height = height;
}

var ColumnDefinition = function (width) {
    this.Width = width;
}

//////////////布局表格
var ReportLayoutTable = function () {
    this.IsIReportPanel = true;
    this.TableBorderType = null;
    this.TableBorderStyle = null;
    this.TableBorderColor = null;

    this.RowDefines = null;
    this.ColDefines = null;

    this.ListRowDefines = null;
    this.ListColDefines = null;

    this.InitRowCount = 3; //初始的行数
    this.InitColCount = 3; //初始的列数

    this.GridTable = null;

    this.SelectedColIndex = 0;
    this.SelectedRowIndex = 0;
    this.IsCanDelete = true;
    this.IsCanEditRow = true;
    this.SelectedCell = null;
    this.SelectedCellControl = null;
    this.ChildControls = null;

    /// <summary>
    /// 筛选条件
    /// </summary>
    this.ListCond = null;

    this.IsCanHasChild = true;
    this.Type = "LayoutTable";
    this.Width = 400;
    this.Height = 80;
    this.Halign = "Left";
    this.Valign = "Top";

    this.DefaultBackgroundColor = "White";
    this.RowDefines = [];
    this.ColDefines = [];
    this.ChildControls = [];
    this.ListColDefines = [];
    this.ListRowDefines = [];
    //LayoutTable
    this.AddChild = function (ctrl) {
        ctrl.MarginBottomWidth = 0;
        ctrl.MarginLeftWidth = 0;
        ctrl.MarginRightWidth = 0;
        ctrl.MarginTopWidth = 0;

        ctrl.IsCanChangeSize = false;
        ctrl.Container.DisableResize();
        ctrl.Container.MoveInTable();

        if (this.ReportMain.SelectedReportControl) {
            ctrl.GridCol = this.SelectedColIndex;
            ctrl.GridRow = this.SelectedRowIndex - 1; //减去辅助行
        }

        var cell = this.SelectedCell || this.Element.find(">tbody > tr:eq(" + (ctrl.GridRow + 1) + ") > td:eq(" + ctrl.GridCol + ")");

        var isDisplay = cell.is(":visible");

        ctrl.Container.Container.css({ width: 0, height: 0 });
        cell.append(ctrl.Container.Container);
        if (!this.ChildControls.Contains(ctrl)) {
            this.ChildControls.push(ctrl);
        }
        ctrl.ParentControl = this;
        if (isDisplay) {
            ctrl.UpdateLayout();
        }
    }

    this.RemoveChild = function (ctrl) {
        this.ChildControls.Remove(ctrl);
        ctrl.ParentControl = null;
    }

    //////////////选择单元格的位置


    this.SelectedCell = null;
    this.SelectCell = function (e) {
        this.SetSelectedCell($(e.target).closest("td"));
    }

    this.SetSelectedCell = function (td) {
        if (this.SelectedCell) {
            this.SelectedCell.removeClass("selected-cell");
        }
        this.SelectedCell = td;
        this.SelectedCell.addClass("selected-cell");
        var tr = this.SelectedCell.parent();
        this.SelectedColIndex = tr.children().index(this.SelectedCell);
        this.SelectedRowIndex = tr.index();
    }

    this.UnSelectCell = function () {
        if (this.SelectedCell) {
            this.SelectedCell.removeClass("selected-cell");
            this.SelectedRowIndex = this.SelectedColIndex = 0;
            this.SelectedCell = null;
        }
    }

    //////////////选择控件和未选择样式

    var _baseFocus = this.Focus;
    this.Focus = function () {
        _baseFocus.call(this);
    }

    var _baseUnFocus = this.UnFocus;
    this.UnFocus = function () {
        if (this.SelectedCell) {
            this.SelectedCell.removeClass("selected-cell");
        }
        _baseUnFocus.call(this);
    }

    //////////////菜单事件 LayoutTable
    this.baseExcuteMenuCommand = this.ExcuteMenuCommand;
    this.ExcuteMenuCommand = function (commandname) {
        switch (commandname) {
            case "AddRowBefore":
                this.AddRow(0);
                break;
            case "AddRowAfter":
                this.AddRow(1);
                break;
            case "AddColBefore":
                this.AddCol(0);
                break;
            case "AddColAfter":
                this.AddCol(1);
                break;
            case "DeleteRow":
                this.DeleteRow();
                break;
            case "DeleteCol":
                this.DeleteCol();
                break;
            case "LayoutTableProp":
                this.ShowProp();
                OnSelectChanged(this);
                break;
            case "RowAuto":
                this.ChangeRowType("Auto");
                break;
            case "RowStar":
                this.ChangeRowType("Star");
                break;
            case "RowPixel":
                this.ChangeRowType("Pixel");
                break;
            case "ColAuto":
                this.ChangeColType("Auto");
                break;
            case "ColStar":
                this.ChangeColType("Star");
                break;
            case "ColPixel":
                this.ChangeColType("Pixel");
                break;
            default:
                this.baseExcuteMenuCommand(commandname);
                break;
        }
    }

    this.ChangeRowType = function (gridUnitType) {
        var rowIndex = this.SelectedRowIndex;
        var define = this.ListRowDefines.First(function (x) { return x.Row == rowIndex; });
        if (define) {
            define.GridUnitType = gridUnitType;
        }
        else {
            define = new LayoutTableRowColDefine();
            define.Row = this.SelectedRowIndex;
            define.GridUnitType = gridUnitType;
            this.ListRowDefines.push(define);
        }
    }

    //LayoutTable
    this.ChangeColType = function (gridUnitType) {
        var colIndex = this.SelectedColIndex;
        var define = this.ListColDefines.First(function (x) { return x.Col == colIndex; });
        if (define) {
            define.GridUnitType = gridUnitType;
        }
        else {
            define = new LayoutTableRowColDefine();
            define.Col = this.SelectedColIndex;
            define.GridUnitType = gridUnitType;
            this.ListColDefines.push(define);
        }
    }
    //LayoutTable
    this.AddRow = function (type) {
        if (this.SelectedCell) {
            var slRow = this.SelectedCell.parent();
            var tr = $("<tr></tr>").css("height", 22);
            for (var i = 0; i < this.ColDefines.length; i++) {
                var td = $("<td></td>");
                if (i == this.ColDefines.length - 1) {
                    td.addClass("last-col-td");
                }
                tr.append(td);
            }
            var rowIndex = this.SelectedRowIndex;
            var rowDefIndex = rowIndex - 1;
            if (type == 0) {
                slRow.before(tr);
            }
            else {
                rowIndex++;
                rowDefIndex++;
                if (rowDefIndex == this.RowDefines.length) {
                    slRow.children("td").removeClass("last-row-td");
                    tr.children().addClass("last-row-td");
                }
                slRow.after(tr);
            }
            this.BindCellResize(tr.children());
            var rowDef = new RowDefinition(new GridLength(22));
            this.RowDefines.Insert(rowDefIndex, rowDef);

            if (rowDefIndex == this.RowDefines.length - 1) {
                this.Element.find(">tbody>tr:eq(" + (rowIndex - 1) + ")").css("height", rowDef.Height.Value);
                rowDef = this.RowDefines[rowDefIndex - 1];
                rowDef.Height = new GridLength(rowDef.Height.Value);

                rowDef = this.RowDefines[rowDefIndex];
                this.Element.find(">tbody>tr:last").css("height", "100%");
                rowDef.Height = new GridLength(rowDef.Height.Value, GridUnitType.Star);
            }

            for (var i = 0; i < this.ChildControls.length; i++) {
                var child = this.ChildControls[i];
                if (child.GridRow >= rowDefIndex) {
                    child.GridRow++;
                }
            }
            //this.UpdateLayout();
        }
    }

    this.DeleteRow = function () {
        this.DeleteRowByIndex(this.SelectedRowIndex);
    }

    //LayoutTable
    this.DeleteRowByIndex = function (rowIndex) {
        if (this.RowDefines.length > 1) {
            var tr = $("tr:nth-child(" + (rowIndex + 1) + ")", this.Element)
            if (rowIndex == (this.RowDefines.length - 1)) {
                tr.prev().children("td").addClass("last-row-td");
            }
            var ri = rowIndex - 1; //减去辅助行
            this.RowDefines.RemoveAt(ri);
            var $this = this;
            tr.find(".ctrl-container").each(function () {
                var ctrlID = $(this).attr("ControlID");
                $this.ChildControls.RemoveWhile(function (o) {
                    return o.ID == ctrlID;
                });
            });
            tr.remove();
            if (ri == this.RowDefines.length) {
                var rowDef = this.RowDefines[ri - 1];
                this.Element.find(">tbody>tr:last").css("height", "100%");
                rowDef.Height = new GridLength(rowDef.Height.Value, GridUnitType.Star);
            }
            for (var i = 0; i < this.ChildControls.length; i++) {
                var child = this.ChildControls[i];
                if (child.GridRow > ri) {
                    child.GridRow--;
                }
            }
        }
    }

    //LayoutTable
    this.AddCol = function (type) {
        if (this.SelectedCell) {
            var slRow = this.SelectedCell.parent();
            var colIndex = this.SelectedColIndex;
            var trs = this.Element.find(">tbody>tr");
            if (type == 0) {
                for (var i = 0; i < trs.length; i++) {
                    var td = $("<td></td>");
                    this.BindCellResize(td);
                    $(trs[i]).find(">td:eq(" + colIndex + ")").before(td);
                }
            }
            else {
                if (colIndex == (this.ColDefines.length - 1)) {
                    trs.find(">td:nth-child(" + (colIndex + 1) + ")").removeClass("last-col-td");
                }
                for (var i = 0; i < trs.length; i++) {
                    var td = $("<td></td>");
                    if (colIndex == (this.ColDefines.length - 1)) {
                        td.addClass("last-col-td");
                    }
                    if (i == trs.length - 1) {
                        td.addClass("last-row-td");
                    }
                    this.BindCellResize(td);
                    $(trs[i]).find(">td:eq(" + colIndex + ")").after(td);
                }
                colIndex++;
            }

            if (this.ChildControls) {
                for (var i = 0; i < this.ChildControls.length; i++) {
                    var child = this.ChildControls[i];
                    if (child.GridCol >= colIndex) {
                        child.GridCol++;
                    }
                }
            }
            this.ColDefines.Insert(colIndex, new ColumnDefinition(new GridLength(22, GridUnitType.Star)));
            if (colIndex == this.ColDefines.length - 1) {
                colDef = this.ColDefines[colIndex - 1];
                //nth-child从1开始
                this.Element.find(">tbody>tr>td:nth-child(" + colIndex + ")").css("width", colDef.Width.Value);
                colDef.Width = new GridLength(colDef.Width.Value);

                var colDef = this.ColDefines[colIndex];
                this.Element.find(">tbody>tr>td:nth-child(" + (colIndex + 1) + ")").css("width", "");
                colDef.Width = new GridLength(colDef.Width.Value, GridUnitType.Star);

            }
        }
    }

    this.DeleteCol = function () {
        this.DeleteColByIndex(this.SelectedColIndex);
    }
    //LayoutTable
    this.DeleteColByIndex = function (colIndex) {
        if (this.ColDefines.length > 1) {
            var $this = this;
            var cells = $(">tbody>tr>td:nth-child(" + (colIndex + 1) + ")", this.Element);
            if (colIndex == (this.ColDefines.length - 1)) {
                cells.prev().addClass("last-col-td");
            }
            cells.remove()
                .find(".ctrl-container")
                .each(function () {
                    var ctrlID = $(this).attr("ControlID");
                    $this.ChildControls.RemoveWhile(function (o) {
                        return o.ID == ctrlID;
                    });
                });

            if (this.ChildControls) {
                for (var i = 0; i < this.ChildControls.length; i++) {
                    var child = this.ChildControls[i];
                    if (child.GridCol > colIndex) {
                        child.GridCol--;
                    }
                }
            }
            this.ColDefines.RemoveAt(colIndex);
            if (colIndex == this.ColDefines.length) {
                var colDef = this.ColDefines[colIndex - 1];
                this.Element.find(">tbody>tr>td:nth-child(" + colIndex + ")").css("width", "");
                colDef.Width = new GridLength(colDef.Width.Value, GridUnitType.Star);
            }
        }
    }

    //////////////显示表格行和列
    /// <summary>
    /// 初始化行列
    /// </summary>
    this.InitRowCol = function () {
        if (!this.InitRowCount || this.InitRowCount < 1) this.InitRowCount = 3;
        if (!this.InitColCount || this.InitColCount < 1) this.InitColCount = 3;
        for (var i = 0; i < this.InitRowCount; i++) {
            this.RowDefines.push(new RowDefinition(new GridLength(22)));
        }
        if (this.RowDefines.length > 0) {
            this.RowDefines[this.RowDefines.length - 1].Height = new GridLength(22, GridUnitType.Star);
        }
        for (var j = 0; j < this.InitColCount; j++) {
            this.ColDefines.push(new ColumnDefinition(new GridLength(100)));
        }
        if (this.ColDefines.length > 0) {
            this.ColDefines[this.ColDefines.length - 1].Width = new GridLength(200, GridUnitType.Star);
        }
    }

    this.DisplayRowCol = function () {
        var rowCount = this.RowDefines.length;
        var colCount = this.ColDefines.length;
        for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
            var row = $("<tr></tr>");
            var rowDefine = this.RowDefines[rowIndex];
            row.css("height", rowDefine.Height.GetValue());
            for (var colIndex = 0; colIndex < colCount; colIndex++) {
                var td = $("<td></td>");
                if (rowIndex == rowCount - 1) {
                    td.addClass("last-row-td");
                }
                if (colIndex == colCount - 1) {
                    td.addClass("last-col-td");
                }
                else {
                    //td.css("width", this.ColDefines[colIndex].Width.GetValue())
                }
                row.append(td);
            }
            this.Element.append(row);
        }
    }

    //////////////创建
    this.AddChildItems = function () {
        for (var i = 0; i < this.ChildControls.length; i++) {
            var child = this.ChildControls[i];
            this.AddChild(child);
        }
    }

    this.MenuItems = new Array().concat(this.MenuItems);
    this.Create = function () {
        this.MenuItems.Insert(0, {
            separator: true
        }).Insert(0, {
            id: "m_LayoutTableProp",
            text: "表格属性",
            name: "LayoutTableProp",
            iconCls: "icon-edit"
        }).Insert(0, {
            id: "m_LayoutTableCol",
            text: "表格列",
            name: "LayoutTableCol",
            children: [{
                id: "#m_AddColBefore",
                text: '<-在前面插入列',
                name: "AddColBefore",
                iconCls: 'icon-add'
            }, {
                id: "#m_AddColAfter",
                text: '在后面插入列->',
                name: "AddColAfter",
                iconCls: 'icon-add'
            }, {
                separator: true
            }, {
                id: "#m_ColAuto",
                text: '宽度自动增长',
                name: "ColAuto"
            }, {
                id: "#m_ColPixel",
                text: '宽度固定',
                name: "ColPixel"
            }, {
                id: "#m_ColStar",
                text: '宽度按比例',
                name: "ColStar"
            }, {
                separator: true
            }, {
                id: "#m_DeleteCol",
                text: '删除列',
                name: "DeleteCol",
                iconCls: "icon-remove"
            }]
        }).Insert(0, {
            id: "m_LayoutTableRow",
            text: "表格行",
            name: "LayoutTableRow",
            children: [{
                id: "#m_AddRowBefore",
                text: '<-在前面插入行',
                name: "AddRowBefore",
                iconCls: 'icon-add'
            }, {
                id: "#m_AddRowAfter",
                text: '在后面插入行->',
                name: "AddRowAfter",
                iconCls: 'icon-add'
            }, {
                separator: true
            }, {
                id: "#m_RowAuto",
                text: '高度自动增长',
                name: "RowAuto"
            }, {
                id: "#m_RowPixel",
                text: '高度固定',
                name: "RowPixel"
            }, {
                id: "#m_RowStar",
                text: '高度按比例',
                name: "RowStar"
            }, {
                separator: true
            }, {
                id: "#m_DeleteRow",
                text: '删除行',
                name: "DeleteRow",
                iconCls: "icon-remove"
            }]
        });
        this.Element = $("<table></table>").attr("cellpadding", "0")
                            .attr("cellspacing", "0")
                            .attr("title", (this.TypeText || "布局表格") + "-" + this.ID);
        this.ApplyClass();
        if (this.RowDefines == null || this.RowDefines.length == 0) {
            this.RowDefines = this.RowDefines || [];
            this.InitRowCol();
        }
        //显示单元格
        this.DisplayRowCol();

        this.BindCellResize(this.Element.find(">tbody>tr>td"));

        this.AddHelperRow();

        //显示子控件
        this.AddChildItems();

    }

    //前面插入一行,用于设置宽度(由于首行有合并列时,设置其它列的宽度无效)
    this.AddHelperRow = function () {
        var tr = $("<tr></tr>").addClass("tr-helper");
        for (var i = 0; i < this.ColDefines.length; i++) {
            var td = $("<td></td>");
            if (i == this.ColDefines.length - 1) {
                td.addClass("last-col-td");
            }
            else {
                td.css("width", this.ColDefines[i].Width.GetValue())
            }
            tr.append(td);
        }
        this.Element.prepend(tr);
    }

    //LayoutTable
    this.BindCellResize = function (jq) {
        jq.resizable({
            handles: "e,s",
            onStartResize: function (e) {
                IsCellResizing = true;
                var d = e.data;
                if ((d.dir == "s" && !$(this).hasClass("last-row-td")) || (d.dir == "e" && !$(this).hasClass("last-col-td"))) {
                    var opts = $(this).resizable("options");
                    var ctrl = opts.Control;
                    var prox = $("<div></div>").css({ "z-index": 9999 }).addClass("mousemoveline");
                    if (d.dir == "s") {//上下
                        var pos = GetControlPosition(ctrl);
                        prox.addClass("mousemoveline-y").css({ width: ctrl.Width, left: pos.Left, top: -10000 });
                    }
                    else if (d.dir == "e") {//左右
                        var pos = GetTdResizeProxyPosition(ctrl, $(this));
                        prox.addClass("mousemoveline-x").css({ height: ctrl.Height, top: pos.Top, left: -10000 });
                        //prox.appendTo(ctrl.Container.Container);//这是一种方式,top:0
                    }
                    prox.appendTo(".report-designer");
                    d.MyProxy = prox;
                }
            },
            onResize: function (e) {
                var opts = $(this).resizable("options");
                var ctrl = opts.Control;

                //在父table内不可以改变大小
                if (ctrl.ParentControl && ($(this).hasClass("last-col-td") || $(this).hasClass("last-row-td"))) {
                    return false;
                }

                var d = e.data || {};
                var container = ctrl.Container.Container;
                var height = ctrl.Height + (d.height - d.startHeight) - 4;
                var pos = GetMouseAlias(e);
                if (d.dir == "s") {//垂直方向
                    if ($(this).hasClass("last-row-td")) {//最后一行,增加table高度
                        container.css({ height: height });
                        return false;
                    }
                    d.MyProxy.css({ top: pos.Y });
                    return false;
                }
                else if (d.dir == "e") {
                    if ($(this).hasClass("last-col-td")) {//左右方向,且是最后一格,增加table宽度
                        container.css({ width: (ctrl.Width + (d.width - d.startWidth) - 4) });
                        return false;
                    }
                    d.MyProxy.css({ left: pos.X });
                }
            },
            onStopResize: function (e) {
                var d = e.data || {};
                if (d.MyProxy) {
                    d.MyProxy.remove();
                }
                var opts = $(this).resizable("options");
                var ctrl = opts.Control;

                var col = $(this).index();
                var container = ctrl.Container.Container;

                var row = $(this).parent("tr").index();
                var rowspan = Z.V($(this).attr("rowspan"));
                if (rowspan > 1) {
                    row = row + rowspan - 1;
                }
                if (d.dir == "s") {//垂直方向
                    var tr = ctrl.Element.find(">tbody>tr:eq(" + row + ")");
                    var tds = tr.children();
                    if (rowspan > 1) {
                        tds = tds.add($(this));
                    }
                    ctrl.Element.find(">tbody>tr>td>.ctrl-container").css({ height: 0 });
                    //tds.children(".ctrl-container").css({ height: 0 }); //让它自适应
                    if ($(this).hasClass("last-row-td")) {//最后一行,增加table高度
                        if (!ctrl.ParentControl) {//在父table内不可以改变大小
                            var height = ctrl.Height + (d.height - d.startHeight);
                            ctrl.Height = height;
                            ctrl.UpdateLayout();
                        }
                        tds.css("height", "auto");
                        return;
                    }

                    var h = d.height;
                    var rowIndex = row;
                    while (rowspan-- > 1) {
                        var r = ctrl.Element.find(">tbody>tr:eq(" + (--rowIndex) + ")");
                        h -= r.outerHeight();
                    }

                    opts.Control.RowDefines[row - 1].Height.Value = h; //row-1,减去辅助行
                    tds.css({ height: "" });
                    tr.css({ height: h - 2 });
                    ctrl.UpdateLayout();
                }
                else if (d.dir == "e") {//左右方向
                    if ($(this).hasClass("last-col-td")) {//且是最后一格,增加table宽度
                        if (!ctrl.ParentControl) {//在父table内不可以改变大小
                            var width = ctrl.Width + (d.width - d.startWidth);
                            ctrl.Width = width;
                            var lastCol = ctrl.Element.find(">tbody>tr>td:last-child");
                            lastCol.children(".ctrl-container").css({ width: 0 }); //让它自适应
                            ctrl.UpdateLayout();
                        }
                        $(this).css("width", "auto");
                        return;
                    }
                    var w = d.width;
                    var colSpan = Z.V($(this).attr("colspan"));
                    if (colSpan > 1) {
                        col = col + colSpan - 1;
                        var colIndex = col;
                        var tr = ctrl.Element.find(">tbody>tr.tr-helper");
                        while (colSpan-- > 1) {
                            var td = tr.find("td:eq(" + (--colIndex) + ")");
                            w -= td.outerWidth();
                        }
                    }
                    opts.Control.ColDefines[col].Width.Value = w;
                    ctrl.Element.find(">tbody>tr.tr-helper>td:eq(" + col + ")").css({ width: w - 2 });
                    ctrl.UpdateLayout();
                }
            },
            Control: this
        });
    }

    this.MoveIn = function (e, source, cell, ctrl) {
        var nestTable = ctrl.Type == "LayoutTable" || ctrl.Type == "CrossTable" || ctrl.Type == "Table";
        //表格禁止嵌套
        if (nestTable) { this.SelectedCell = null; return null; }

        this.SetSelectedCell(cell);
        this.AddChild(ctrl);

    }

    this.ApplyClass = function () {
        var borderClass = TableClasses[Z.SafeToInt(this.TableBorderType)];
        var borderStyle = (this.TableBorderStyle == "dotted" ? "dotted" : "solid");
        var borderTypeClass = ("tb-" + borderStyle + "-border");
        this.Element.attr("class", "el-layouttable element")
                    .addClass("el-layouttable")
                    .addClass(borderTypeClass)
                    .addClass(borderClass);
    }

    //LayoutTable
    var baseApplyCommonProps = this.ApplyCommonProps;
    this.ApplyCommonProps = function () {
        this.Element.find(">tbody>tr:last").children().children(".ctrl-container").css({ height: 0 }); //最后行自适应
        this.Element.find(">tbody>tr>td:last-child").children(".ctrl-container").css({ width: 0 }); //最后列自适应
        baseApplyCommonProps.call(this);
        this.Element.css("border", "");
        var color = this.TableBorderColor || "black";
        this.Element.css("border-color", color);
        this.Element.find(">tbody>tr>td").css("border-color", color);
        this.ApplyClass();
        if (this.ChildControls) {
            for (var i = 0; i < this.ChildControls.length; i++) {
                var child = this.ChildControls[i];
                var cell = child.Element.closest("td");
                child.Width = cell.is(":visible") ? cell.innerWidth() : NaN;
                child.Height = cell.is(":visible") ? cell.innerHeight() : NaN;
                child.UpdateLayout();
            }
        }
    }

    //LayoutTable
    this.ExplainTable = function (node) {
        this.ListRowDefines = [];
        this.ListColDefines = [];

        var rowsNode = node.children("Rows");
        if (rowsNode != null) {
            var rows = rowsNode.children();
            var rowIndex = 0;
            for (var i = 0; i < rows.length; i++) {
                var row = $(rows[i]);
                var rowDef = new RowDefinition();
                rowDef.Height = new GridLength(Z.V(row.attr("Height")));
                this.RowDefines.push(rowDef);
                if (row.attr("GridUnitType")) {
                    var define = new LayoutTableRowColDefine();
                    define.Row = rowIndex;
                    define.GridUnitType = row.attr("GridUnitType");
                    this.ListRowDefines.push(define);
                }
                rowIndex++;
            }
        }

        if (this.RowDefines.length != 0) {
            this.RowDefines[this.RowDefines.length - 1].Height = new GridLength(this.RowDefines[this.RowDefines.length - 1].Height.GetValue(), GridUnitType.Star);
        }

        var columnsNode = node.children("Columns");
        if (columnsNode != null) {
            var columns = columnsNode.children();
            var colIndex = 0;
            for (var j = 0; j < columns.length; j++) {
                var column = $(columns[j]);
                var colDef = new ColumnDefinition();
                colDef.Width = new GridLength(Z.V(column.attr("Width")));
                this.ColDefines.push(colDef);

                if (column.attr("GridUnitType")) {
                    var define = new LayoutTableRowColDefine();
                    define.Col = colIndex;
                    define.GridUnitType = column.attr("GridUnitType");
                    this.ListColDefines.push(define);
                }
                colIndex++;
            }
        }

        if (this.ColDefines.length != 0) {
            this.ColDefines[this.ColDefines.length - 1].Width = new GridLength(this.ColDefines[this.ColDefines.length - 1].Width.GetValue(), GridUnitType.Star);
        }
    }

    this.baseExplainControl = this.ExplainControl;
    this.ExplainControl = function (node) {
        this.baseExplainControl(node);
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var child = nodes[i];
            var name = child.nodeName;
            child = $(child);
            switch (name) {
                case "BorderType":
                    this.TableBorderType = child.text();
                    break;
                case "BorderStyle":
                    this.TableBorderStyle = child.text();
                    break;
                case "BorderColor":
                    this.TableBorderColor = child.text();
                    break;
                case "Conditions":
                    this.ListCond = ConditionToJSON(child);
                    break;
                case "DataSource":
                    this.DataSource = child.text();
                    break;
            }
        }

        this.ExplainTable(node);
    }

    this.ExplainOther = function (node) {
        var items = node.children("Items");
        this.ReportMain.ExplainControls(items, this);
    }

    this.ToBorderXML = function (xml) {
        if (this.TableBorderType) {
            xml.Append("<BorderType>" + this.TableBorderType + "</BorderType>");
        }
        if (this.TableBorderStyle) {
            xml.Append("<BorderStyle>" + this.TableBorderStyle + "</BorderStyle>");
        }
        if (this.TableBorderColor) {
            xml.Append("<BorderColor>" + this.TableBorderColor + "</BorderColor>");
        }
    }

    //LayoutTable
    this.ToRowColDefineXML = function (xml) {
        xml.Append("<Rows>");
        for (var i = 0; i < this.RowDefines.length; i++) {
            xml.Append("<Row Height=\"" + this.RowDefines[i].Height.GetValue() + "\" ");
            if (i != this.RowDefines.length - 1) {
                var unit = this.ListRowDefines.First(function (x) { return x.Row == i; });
                if (unit) {
                    xml.Append("GridUnitType=\"" + unit.GridUnitType + "\" ");
                }
            }
            else {
                xml.Append("GridUnitType=\"Star\" ");
            }
            xml.Append(" />");
        }
        xml.Append("</Rows>");

        xml.Append("<Columns>");
        for (var i = 0; i < this.ColDefines.length; i++) {
            xml.Append("<Column Width=\"" + this.ColDefines[i].Width.GetValue() + "\" ");
            if (i != this.ColDefines.length - 1) {
                var unit = this.ListColDefines.First(function (x) { return x.Col == i; });
                if (unit) {
                    xml.Append("GridUnitType=\"" + unit.GridUnitType + "\" ");
                }
            }
            else {
                xml.Append("GridUnitType=\"Star\" ");
            }
            xml.Append(" />");
        }
        xml.Append("</Columns>");
    }

    this.ToXML = function () {
        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        this.ToRowColDefineXML(xml);

        this.ToBorderXML(xml);

        xml.Append("<Style>");

        xml.Append(this.RenderCommonStyleXML());

        xml.Append("</Style>");

        xml.Append("<Name>" + this.Name + "</Name>");
        xml.Append(this.GetPropXML("DataSource", this.DataSource));

        //////////////筛选条件
        if (this.ListCond != null && this.ListCond.length > 0) {
            xml.Append("<Conditions>");
            xml.Append(getConditionXML(this.ListCond));
            xml.Append("</Conditions>");
        }

        xml.Append("<Items>");

        var listItems = this.ChildControls.OrderBy(); //.OrderBy(x => x.GridCol);
        for (var i = 0; i < listItems.length; i++) {
            var child = listItems[i];
            xml.Append(child.ToXML());
        }

        xml.Append("</Items>");

        xml.Append(this.RenderEndXML());

        return xml.ToString();
    }
}
ReportLayoutTable.prototype = new ReportControl();

var LayoutTableRowColDefine = function () {
    this.Row = 0;
    this.Col = 0;
    this.GridUnitType = null;

}

//////////////数据表格
var ReportTable = function () {
    //////////////属性
    this.IsIReportPanel = true;
    this.TableBorderType = null;
    this.TableBorderStyle = null;
    this.TableBorderColor = null;
    this.ColDefines = null;
    this.ColDefineUnits = null;
    this.Element = null;
    this.Header = null;
    this.Footer = null;
    this.HeaderProxy = 1;
    this.FooterProxy = 1;
    this.DataRow = null;

    /// <summary>
    /// 重复方式
    /// </summary>
    this.RepeatX = null;

    /// <summary>
    /// 分页方式
    /// </summary>
    this.BreakType = null;

    /// <summary>
    /// 是否重复表头
    /// </summary>
    this.RepeatHeader = null;

    /// <summary>
    /// 是否重复表尾
    /// </summary>
    this.RepeatFooter = null;

    /// <summary>
    /// 排序字段
    /// </summary>
    this.OrderField = null;

    /// <summary>
    /// 排序方式
    /// </summary>
    this.OrderType = null;

    /// <summary>
    /// 显示行数
    /// </summary>
    this.MaxRow = null;

    /// <summary>
    /// 筛选条件
    /// </summary>
    this.ListCond = null;

    /// <summary>
    /// 显示条件
    /// </summary>
    this.DisplayCond = null;

    this.IsCanHasChild = false;

    this.InitColCount = 3;

    this.GridTable = null;

    this.SelectedColIndex = 0;
    this.SelectedRowIndex = 0;

    this.SelectedCellControl = null;

    this.ChildControls = [];

    //////////////添加和删除子控件
    //ReportTable
    this.AddChild = function (ctrl) {
        ctrl.MarginBottomWidth = 0;
        ctrl.MarginLeftWidth = 0;
        ctrl.MarginRightWidth = 0;
        ctrl.MarginTopWidth = 0;

        ctrl.IsCanChangeSize = false;
        ctrl.Container.DisableResize();
        ctrl.Container.MoveInTable();
        if (this.ReportMain.SelectedReportControl) {
            ctrl.GridCol = this.SelectedColIndex;
            ctrl.GridRow = this.SelectedRowIndex - 1; //减去辅助行
        }

        var cell = this.SelectedCell || this.Element.find(">tbody > tr:eq(" + (ctrl.GridRow + 1) + ") > td:eq(" + ctrl.GridCol + ")");

        var isDisplay = cell.is(":visible");

        ctrl.Container.Container.css({ width: 0, height: 0 });
        cell.append(ctrl.Container.Container);
        //var gridRow = this.GetRowType(this.SelectedRowIndex - 1); //减去辅助行


        var gridRow = this.GetRowType(ctrl.GridRow);

        if (gridRow != null && !gridRow.Items.Contains(ctrl)) {
            gridRow.Items.push(ctrl);
        }

        this.ChildControls.push(ctrl);
        ctrl.ParentControl = this;
        if (isDisplay) {
            ctrl.UpdateLayout();
        }
    }

    //解析表头表尾
    this.AddTableChild = function (ctrl) {
        ctrl.MarginBottomWidth = 0;
        ctrl.MarginLeftWidth = 0;
        ctrl.MarginRightWidth = 0;
        ctrl.MarginTopWidth = 0;

        ctrl.IsCanChangeSize = false;
        ctrl.Container.DisableResize();
        ctrl.Container.MoveInTable();

        this.ReportMain.SelectedReportControl = this;
        var cell = this.SelectedCell || this.Element.find(">tbody > tr:eq(" + (ctrl.GridRow + 1) + ") > td:eq(" + ctrl.GridCol + ")");

        var isDisplay = cell.is(":visible");

        ctrl.Container.Container.css({ width: 0, height: 0 });
        cell.append(ctrl.Container.Container);
        //var gridRow = this.GetRowType(this.SelectedRowIndex - 1); //减去辅助行

        var gridRow = this.GetRowType(ctrl.GridRow);
        if (gridRow != null && !gridRow.Items.Contains(ctrl)) {
            gridRow.Items.push(ctrl);
        }

        this.ChildControls.push(ctrl);
        ctrl.ParentControl = this;
        // if (isDisplay) {
        ctrl.UpdateLayout();
        // }
    }

    this.RemoveChild = function (ctrl) {
        var gridRow = this.GetRowType(ctrl.GridRow);
        gridRow.Items.Remove(ctrl);
        ctrl.ParentControl = null;
        this.ChildControls.RemoveWhile(function (o) {
            return o.ID === ctrl.ID;
        });
    }
    //ReportTable
    var baseApplyCommonProps = this.ApplyCommonProps;
    this.ApplyCommonProps = function () {
        this.Element.find(">tbody>tr:last").children().children(".ctrl-container").css({ height: 0 }); //最后行自适应
        this.Element.find(">tbody>tr>td:last-child").children(".ctrl-container").css({ width: 0 }); //最后列自适应
        baseApplyCommonProps.call(this);
        this.Element.css("border", "");
        var color = this.TableBorderColor || "black";
        this.Element.css("border-color", color);
        //$("td", this.Element).css("border-color", color);
        this.Element.find(">tbody>tr>td").css("border-color", color);
        this.ApplyClass();
        if (this.ChildControls) {
            for (var i = 0; i < this.ChildControls.length; i++) {
                var child = this.ChildControls[i];
                var cell = child.Element.closest("td");
                child.Width = cell.is(":visible") ? cell.innerWidth() : NaN;
                child.Height = cell.is(":visible") ? cell.innerHeight() : NaN;
                child.UpdateLayout();
            }
        }
    }

    this.Type = "Table";
    this.Width = 400;
    this.Height = 150;
    this.Halign = "Left";
    this.Valign = "Top";

    this.ColDefines = [];
    this.ColDefineUnits = [];
    this.Groups = [];
    this.DefaultBackgroundColor = "White";
    this.ChildControls = [];

    //////////////选择单元格的位置
    this.SelectedCell = null;
    this.SelectCell = function (e) {
        this.SetSelectedCell($(e.target).closest("td"));
    }

    this.SetSelectedCell = function (td) {
        if (this.SelectedCell) {
            this.SelectedCell.removeClass("selected-cell");
        }
        this.SelectedCell = td;
        this.SelectedCell.addClass("selected-cell");
        var tr = this.SelectedCell.parent();
        this.SelectedColIndex = tr.children().index(this.SelectedCell);
        this.SelectedRowIndex = tr.index();
    }

    this.UnSelectCell = function () {
        if (this.SelectedCell) {
            this.SelectedCell.removeClass("selected-cell");
            this.SelectedRowIndex = this.SelectedColIndex = 0;
            this.SelectedCell = null;
        }
    }

    //////////////选择控件和未选择样式
    var _baseFocus = this.Focus;
    this.Focus = function () {
        _baseFocus.call(this);
    }

    var _baseUnFocus = this.UnFocus;
    this.UnFocus = function () {
        if (this.SelectedCell) {
            this.SelectedCell.removeClass("selected-cell");
        }
        _baseUnFocus.call(this);
    }

    //////////////菜单事件
    this.CreateContextMenu = function () {

    }

    this.SetMenuText = function () {
        this.MenuItemHideFooter.text = this.Footer.IsShow ? "隐藏表尾" : "显示表尾";
        this.MenuItemHideHeader.text = this.Header.IsShow ? "隐藏表头" : "显示表头";
    }
    //ReportTable
    this.baseExcuteMenuCommand = this.ExcuteMenuCommand;
    this.ExcuteMenuCommand = function (commandname, target) {
        switch (commandname) {
            case "AddRowBefore":
                this.AddRow(0);
                break;
            case "AddRowAfter":
                this.AddRow(1);
                break;
            case "DeleteRow":
                this.DeleteRow();
                break;
            case "AddColBefore":
                this.AddCol(0);
                break;
            case "AddColAfter":
                this.AddCol(1);
                break;
            case "DeleteCol":
                this.DeleteCol();
                break;
            case "HideFooter":
                this.Footer.IsShow = !this.Footer.IsShow;
                ControlPropPanel.Update("Footer", this.Footer);
                //UpdateProperty("Footer", this.Footer);
                this.ReLoadTable();
                break;
            case "HideHeader":
                this.Header.IsShow = !this.Header.IsShow;
                ControlPropPanel.Update("Header", this.Header);
                // UpdateProperty("Header", this.Header);
                this.ReLoadTable();
                break;
            case "ReportTableProp":
                this.ShowProp();
                OnSelectChanged(this);
                break;
            case "RowAuto":
                this.ChangeRowType("Auto");
                break;
            case "RowStar":
                this.ChangeRowType("Star");
                break;
            case "RowPixel":
                this.ChangeRowType("Pixel");
                break;
            case "ColAuto":
                this.ChangeColType("Auto");
                break;
            case "ColStar":
                this.ChangeColType("Star");
                break;
            case "ColPixel":
                this.ChangeColType("Pixel");
                break;
            default:
                this.baseExcuteMenuCommand(commandname);
                break;
        }
    }

    this.ChangeRowType = function (gridUnitType) {
        var row = this.DataRow;
        if (this.SelectedRowIndex == 0) {
            row = this.Header;
        }
        else if (this.SelectedRowIndex == 1) {
            row = this.DataRow;
        }
        else if (this.SelectedRowIndex == 2) {
            row = this.Footer;
        }
        row.RowHeightUnitType = gridUnitType;
    }

    //ReportTable
    this.ChangeColType = function (gridUnitType) {
        var colIndex = this.SelectedColIndex;
        var colDef = this.ColDefineUnits.First(function (x) { return x.Col == colIndex; });
        if (colDef) {
            colDef.GridUnitType = gridUnitType;
        }
        else {
            colDef = new LayoutTableRowColDefine();
            colDef.Col = this.SelectedColIndex;
            colDef.GridUnitType = gridUnitType;
            this.ColDefineUnits.push(colDef);
        }
    }

    this.GetGridLength = function (value, gridUnitType) {
        switch (gridUnitType) {
            case GridUnitType.Auto:
                return GridLength.Auto;
            case GridUnitType.Pixel:
                return new GridLength(value);
            case GridUnitType.Star:
                return new GridLength(value, GridUnitType.Star);
        }
        return GridLength.Auto;
    }

    //添加行子控件RowIndex
    this.UpdateRowIndex = function (AddRowType, postion) {
        var CurrentIndex = this.SelectedRowIndex - 1;
        var footerItem = this.Footer.Items
        if (AddRowType == "Header") {
            var headerItem = this.Header.Items
            for (var i = 0; i < headerItem.length; i++) {
                if (postion == 0) { CurrentIndex = CurrentIndex - 1 } //在前面插入行
                if (headerItem[i].GridRow > CurrentIndex)
                    headerItem[i].GridRow += 1;
            }
            for (var i = 0; i < footerItem.length; i++) {
                footerItem[i].GridRow += 1;
            }
        }
        else if (AddRowType == "Footer") {
            for (var i = 0; i < footerItem.length; i++) {
                if (postion == 0) { CurrentIndex = CurrentIndex - 1 } //在前面插入行
                if (footerItem[i].GridRow > CurrentIndex)
                    footerItem[i].GridRow += 1;
            }
        }

    }
    //删除行RowIndex
    this.SubtractRowIndex = function (AddRowType, postion) {
        var CurrentIndex = this.SelectedRowIndex - 1;
        var footerItem = this.Footer.Items
        if (AddRowType == "Header") {
            var headerItem = this.Header.Items
            for (var i = 0; i < headerItem.length; i++) {
                if (postion == 0) { CurrentIndex = CurrentIndex - 1 } //在前面插入行
                if (headerItem[i].GridRow > CurrentIndex)
                    headerItem[i].GridRow -= 1;
            }
            for (var i = 0; i < footerItem.length; i++) {
                footerItem[i].GridRow += 1;
            }
        }
        else if (AddRowType == "Footer") {
            for (var i = 0; i < footerItem.length; i++) {
                if (postion == 0) { CurrentIndex = CurrentIndex - 1 } //在前面插入行
                if (footerItem[i].GridRow > CurrentIndex)
                    footerItem[i].GridRow -= 1;
            }
        }

    }

    this.AddRow = function (type) {
        if (this.SelectedCell) {
            var slRow = this.SelectedCell.parent();
            var AddRowType = $(slRow).attr("type");
            var rowHeight = 22;//初始高度
            //只能添加表头表尾的行
            if (AddRowType == "Header") {
                this.Header.Rows.push(rowHeight);
            } else if (AddRowType == "Footer") {
                this.Footer.Rows.push(rowHeight);
            }
            else
                return false;
            this.UpdateRowIndex(AddRowType, type);
            this.ReLoadTable();
        }
    }

    this.DeleteRow = function () {
        if (this.SelectedCell) {
            var slRow = this.SelectedCell.parent();
            var RowType = $(slRow).attr("type");
            var CurrentIndex = this.SelectedRowIndex - 1;
            var footerItem = this.Footer.Items
            var delRow = 0;
            if (RowType == "Header") {
                var headerItem = this.Header.Items;
                if (headerItem.length > 1) {  //至少一个表头表尾
                    for (var i = 0; i < headerItem.length; i++) {
                        if (headerItem[i].GridRow == CurrentIndex)
                            delRow = CurrentIndex;
                        else if (headerItem[i].GridRow > CurrentIndex) {
                            headerItem[i].GridRow -= 1;
                        }
                    }
                    this.Header.Items.splice(delRow, 1);
                    this.Header.Rows.splice(CurrentIndex, 1);
                    for (var i = 0; i < footerItem.length; i++) {
                        footerItem[i].GridRow -= 1;
                    }
                }
            }
            else if (RowType == "Footer") {
                if (footerItem.length > 1) {
                    var RowCount = this.Element.find(">tbody>tr").length - 1;
                    var subStractrow = RowCount - footerItem.length;
                    for (var i = 0; i < footerItem.length; i++) {
                        if (footerItem[i].GridRow == CurrentIndex)
                            delRow = CurrentIndex;
                        else if (footerItem[i].GridRow > CurrentIndex)
                            footerItem[i].GridRow -= 1;
                    }
                    this.Footer.Items.splice(delRow - subStractrow, 1);
                    this.Footer.Rows.splice(CurrentIndex - subStractrow, 1);
                }
            }
            else
                return false;
            this.ReLoadTable();
        }
    }

    this.AddCol = function (type) {
        if (this.SelectedCell) {
            var slRow = this.SelectedCell.parent();
            var colIndex = this.SelectedColIndex;
            var trs = this.Element.find(">tbody>tr");

            if (type == 0) {
                for (var i = 0; i < trs.length; i++) {
                    var td = $("<td></td>");
                    this.BindCellResize(td);
                    $(trs[i]).find(">td:eq(" + colIndex + ")").before(td);
                }
            }
            else {
                if (colIndex == (this.ColDefines.length - 1)) {
                    trs.find(">td:nth-child(" + (colIndex + 1) + ")").removeClass("last-col-td");
                }
                for (var i = 0; i < trs.length; i++) {
                    var td = $("<td></td>");
                    if (colIndex == (this.ColDefines.length - 1)) {
                        td.addClass("last-col-td");
                    }
                    if (i == trs.length - 1) {
                        td.addClass("last-row-td");
                    }
                    this.BindCellResize(td);
                    $(trs[i]).find(">td:eq(" + colIndex + ")").after(td);
                }
                colIndex++;
            }
            if (this.ChildControls) {
                for (var i = 0; i < this.ChildControls.length; i++) {
                    var child = this.ChildControls[i];
                    if (child.GridCol >= colIndex) {
                        child.GridCol++;
                    }
                }
            }
            this.ColDefines.Insert(colIndex, new ColumnDefinition(new GridLength(40, GridUnitType.Star)));
        }
    }


    this.DeleteCol = function () {
        this.DeleteColByIndex(this.SelectedColIndex);
    }

    this.DeleteColByIndex = function (colIndex) {
        if (this.ColDefines.length > 1) {
            var $this = this;
            var tds = $(">tbody>tr>td:nth-child(" + (colIndex + 1) + ")", this.Element);
            if (colIndex == (this.ColDefines.length - 1)) {
                tds.prev().addClass("last-col-td");
            }
            tds.find(".ctrl-container>.element")
                .each(function () {
                    $this.RemoveChild($(this).data("Tag"));
                });
            tds.remove();
            this.ColDefines.RemoveAt(colIndex);
            if (this.ChildControls) {
                for (var i = 0; i < this.ChildControls.length; i++) {
                    var child = this.ChildControls[i];
                    if (child.GridCol > colIndex) {
                        child.GridCol--;
                    }
                }
            }
        }
    }

    this.FindChild = function (id) {
        var ctrl = null;
        if (this.Header != null && this.Header.Items) {
            ctrl = this.Header.Items.First(function (o) { return o.ID == id; });
        }
        if (!ctrl) {
            if (this.DataRow && this.DataRow.Items) {
                ctrl = this.DataRow.Items.First(function (o) { return o.ID == id; });
            }
        }
        if (!ctrl) {
            if (this.Groups && this.Groups.length > 0) {
                for (var i = 0; i < this.Groups.length; i++) {
                    if (this.Groups[i].Header != null && this.Groups[i].Header.Items) {
                        ctrl = this.Groups[i].Header.Items.First(function (o) { return o.ID == id; });
                        if (ctrl) {
                            break;
                        }
                    }
                    if (this.Groups[i].Footer != null && this.Groups[i].Footer.Items) {
                        ctrl = this.Groups[i].Footer.Items.First(function (o) { return o.ID == id; });
                        if (ctrl) {
                            break;
                        }
                    }
                }
            }
        }
        if (!ctrl) {
            if (this.Footer != null && this.Footer.Items) {
                ctrl = this.Footer.Items.First(function (o) { return o.ID == id; });
            }
        }
        return ctrl;
    }

    //////////////创建
    this.InitTable = function () {
        if (this.ColDefines == null || this.ColDefines.length == 0) {
            this.ColDefines = [];
            for (var i = 0; i < this.InitColCount; i++) {
                this.ColDefines.push(new ColumnDefinition(new GridLength(100, GridUnitType.Pixel)));
                if (i == this.InitColCount - 1) {
                    this.ColDefines[i].Width = new GridLength(200, GridUnitType.Star);
                }
            }
        }
        this.InitDataTable();
    }

    this.InitDataTable = function () {
        if (this.Header == null || this.Header.length == 0) {
            this.Header = new TableHeader();
            //var rowDef = new RowDefinition();
            //rowDef.Height = new GridLength(22);
            //this.Header.RowHeight = 26;
        }

        if (this.Footer == null || this.Footer.length == 0) {
            this.Footer = new TableFooter();
            //  this.Footer.RowHeight = 26;
        }

        if (this.DataRow == null) {
            this.DataRow = new TableDataRow();
            this.DataRow.RowHeight = 26;
        }
    }
    //添加表头表尾
    this.AddMutliRow = function (row, type) {
        if (!row || !row.IsShow) return false;
        for (var i = 0; i < row.Rows.length; i++) {
            var tr = $("<tr type='" + type + "'></tr>");

            var colCount = this.ColDefines.length;
            for (var colIndex = 0; colIndex < colCount; colIndex++) {
                var td = $("<td></td>").addClass("last-row-td")
                                    .attr("title", row.GetDesc())
                                    .css("height", row.Rows[i]);
                if (colIndex == colCount - 1) {
                    td.addClass("last-col-td");
                }
                tr.append(td);
            }
            $(">tbody>tr:last>td", this.Element).removeClass("last-row-td").last().removeClass("last-col-td");
            this.Element.append(tr);
        }
        if (row.Items) {
            for (var i = 0; i < row.Items.length; i++) {
                var child = row.Items[i];
                //this.SelectedColIndex = child.GridCol;
                // this.SelectedRowIndex = child.GridRow;
                this.AddTableChild(child);
                child.MergeRowColSpan();
            }
        }
    }
    //添加分组行
    this.AddTableRow = function (row, type) {
        if (row && row.IsShow) {
            var tr = $("<tr type='" + type + "'></tr>");
            var rowIndex = this.Element.find(">tbody>tr").length;
            var colCount = this.ColDefines.length;
            for (var colIndex = 0; colIndex < colCount; colIndex++) {
                var td = $("<td></td>").addClass("last-row-td")
                                    .attr("title", row.GetDesc())
                                    .css("height", row.RowHeight);
                if (colIndex == colCount - 1) {
                    td.addClass("last-col-td");
                }
                tr.append(td);
            }
            $(">tbody>tr:last>td", this.Element).removeClass("last-row-td").last().removeClass("last-col-td");
            this.Element.append(tr);
            if (row.Items) {
                for (var i = 0; i < row.Items.length; i++) {
                    var child = row.Items[i];
                    this.SelectedColIndex = child.GridCol;
                    //this.SelectedRowIndex = rowIndex;
                    child.GridRow = rowIndex - 1;// 减去辅助行
                    this.AddTableChild(child);
                    child.MergeRowColSpan();
                }
            }
        }
    }

    //计算RowIndex得到RowType
    this.GetRowType = function (row) {
        var iRow = -1;
        if (this.Header != null && this.Header.IsShow == true) {
            for (var i = 0; i < this.Header.Rows.length; i++) {
                iRow++;
            }
        }
        if (iRow >= row) return this.Header;

        for (var i = 0; i < this.Groups.length; i++) {
            if (this.Groups[i].Header != null && this.Groups[i].Header.IsShow) {
                iRow++;
            }
            if (iRow == row) return this.Groups[i].Header;
        }

        if (this.DataRow.IsShow == true) {
            iRow++;
        }
        if (iRow == row) return this.DataRow;

        for (var i = this.Groups.length - 1; i >= 0; i--) {
            if (this.Groups[i].Footer != null && this.Groups[i].Footer.IsShow) {
                iRow++;
            }
            if (iRow == row) return this.Groups[i].Footer;
        }

        if (this.Footer != null && this.Footer.IsShow == true) {
            for (var i = 0; i < this.Footer.Rows.length; i++) {
                iRow++;
            }

        }
        if (iRow >= row) return this.Footer;
        return null;
    }

    this.ReLoadTable = function () {

        this.ClearTable();
        this.ChildControls = [];
        this.CreateTable();
        this.SetMenuText();
        this.UpdateLayout();
    }

    this.GroupsRowCount = function () {
        var count = 0;
        if (this.Groups && this.Groups.length > 0) {
            for (var g = 0; g < this.Groups.length; g++) {
                var groupHeader = this.Groups[g].Header;
                var groupFooter = this.Groups[g].Footer;
                if (groupHeader && groupHeader.IsShow)
                    count++;
                if (groupFooter && groupFooter.IsShow)
                    count++;
            }
        }
        return count;
    }
    //更新Footer
    this.UpdateFooterRowIndex = function (oldRowCount) {
        var count = this.GroupsRowCount();
        count = count - oldRowCount;
        var footerItem = this.Footer.Items;
        for (var r = 0; r < footerItem.length; r++) {
            footerItem[r].GridRow += count;
        }
    }

    this.ClearTable = function () {
        this.Element.empty();
        this.SelectedCell = null;
    }

    //ReportTable
    this.CreateTable = function () {

        this.AddHelperRow();

        //创建表头
        // this.AddTableRow(this.Header, "Header");
        this.AddMutliRow(this.Header, "Header");

        //创建分组头
        if (this.Groups) {
            for (var i = 0; i < this.Groups.length; i++) {
                var group = this.Groups[i];
                this.AddTableRow(group.Header, "");
            }
        }

        //创建数据行
        this.AddTableRow(this.DataRow, "");

        //创建分组尾
        if (this.Groups) {
            for (var i = this.Groups.length - 1; i >= 0; i--) {
                this.AddTableRow(this.Groups[i].Footer, "");
            }
        }
        //创建表尾
        //this.AddTableRow(this.Footer, "Footer");
        this.AddMutliRow(this.Footer, "Footer");

        this.Element.find(">tbody>tr:last>td").css("height", "");

        this.BindCellResize(this.Element.find(">tbody>tr>td"));
    }

    this.MenuItems = new Array().concat(this.MenuItems);

    //Override ReportTable
    this.Create = function () {
        this.MenuItems.Insert(0, {
            separator: true
        }).Insert(0, {
            id: "m_ReportTableProp",
            text: "表格属性",
            name: "ReportTableProp",
            iconCls: "icon-edit"
        });

        this.MenuItemHideFooter = {
            id: "m_ReportTableHideFooter",
            text: "隐藏表尾",
            name: "HideFooter",
            iconCls: "icon-tip"
        }
        this.MenuItems.Insert(0, this.MenuItemHideFooter);

        this.MenuItemHideHeader = {
            id: "m_ReportTableHideHeader",
            text: "隐藏表头",
            name: "HideHeader",
            iconCls: "icon-tip"
        };

        this.MenuItems.Insert(0, this.MenuItemHideHeader)
            .Insert(0, {
                id: "m_ReportTableCol",
                text: "表格列",
                name: "ReportTableCol",
                children: [{
                    id: "#m_AddColBefore",
                    text: '在前面插入列',
                    name: "AddColBefore",
                    iconCls: 'icon-add'
                }, {
                    id: "#m_AddColAfter",
                    text: '在后面插入列',
                    name: "AddColAfter",
                    iconCls: 'icon-add'
                }, {
                    separator: true
                }, {
                    id: "#m_ColAuto",
                    text: '宽度自动增长',
                    name: "ColAuto"
                }, {
                    id: "#m_ColPixel",
                    text: '宽度固定',
                    name: "ColPixel"
                }, {
                    id: "#m_ColStar",
                    text: '宽度按比例',
                    name: "ColStar"
                }, {
                    separator: true
                }, {
                    id: "#m_DeleteCol",
                    text: '删除列',
                    name: "DeleteCol",
                    iconCls: "icon-remove"
                }]
            }).Insert(0, {
                id: "m_ReportTableRow",
                text: "表格行",
                name: "ReportTableRow",
                children: [
                     {
                         id: "#m_AddRowBefore",
                         text: '<-在前面插入行',
                         name: "AddRowBefore",
                         iconCls: 'icon-add'
                     }, {
                         id: "#m_AddRowAfter",
                         text: '在后面插入行->',
                         name: "AddRowAfter",
                         iconCls: 'icon-add'
                     }, {
                         id: "#m_DeleteRow",
                         text: '删除行',
                         name: "DeleteRow",
                         iconCls: "icon-remove"
                     },
                    {
                        id: "#m_RowAuto",
                        text: '高度自动增长',
                        name: "RowAuto"
                    }, {
                        id: "#m_RowPixel",
                        text: '高度固定',
                        name: "RowPixel"
                    }, {
                        id: "#m_RowStar",
                        text: '高度按比例',
                        name: "RowStar"
                    }]
            });
        this.Element = $("<table></table>").attr("cellpadding", "0")
                            .attr("cellspacing", "0")
                            .attr("title", "数据表格-" + this.ID);
        //如果不存在设置,则采用默认设置
        this.InitTable();

        //创建数据表和其子控件
        this.CreateTable();

        this.ApplyClass();

        //this.AddHelperRow();
    }

    //前面插入一行,用于设置宽度(由于首行有合并列时,设置其它列的宽度无效)
    this.AddHelperRow = function () {
        var tr = $("<tr></tr>").addClass("tr-helper");
        for (var i = 0; i < this.ColDefines.length; i++) {
            var td = $("<td></td>");
            if (i == this.ColDefines.length - 1) {
                td.addClass("last-col-td");
            }
            else {
                td.css("width", this.ColDefines[i].Width.GetValue())
            }
            tr.append(td);
        }
        this.Element.prepend(tr);
    }

    //设置各行高度
    this.SetHeight = function (row, height) {
        var iRow = -1;
        if (this.Header != null && this.Header.IsShow == true) {
            for (var i = 0; i < this.Header.Rows.length; i++) {
                iRow++;
            }
        }
        if (iRow >= row) {
            this.Header.Rows[row] = height;
            return true;
        };

        for (var i = 0; i < this.Groups.length; i++) {
            if (this.Groups[i].Header != null && this.Groups[i].Header.IsShow) {
                iRow++;
            }
            if (iRow == row) {
                this.Groups[iRow - row].Header.RowHeight = height;
                return true;
            }
        }

        if (this.DataRow.IsShow == true) {
            iRow++;
        }
        if (iRow == row) {
            this.DataRow.RowHeight = height;
            return true;
        }

        for (var i = this.Groups.length - 1; i >= 0; i--) {
            if (this.Groups[i].Footer != null && this.Groups[i].Footer.IsShow) {
                iRow++;
            }
            if (iRow == row) { this.Groups[iRow - row].Footer = height; return true; }
        }

        if (this.Footer != null && this.Footer.IsShow == true) {
            for (var i = 0; i < this.Footer.Rows.length; i++) {
                iRow++;
            }

        }

        if (iRow >= row) {
            this.Footer.Rows[iRow - row] = height;
            return true;
        }
        return null;
    }

    //ReportTable
    this.BindCellResize = function (jq) {
        jq.resizable({
            handles: "e,s",
            onStartResize: function (e) {
                IsCellResizing = true;
                var d = e.data;
                if ((d.dir == "s" && !$(this).hasClass("last-row-td")) || (d.dir == "e" && !$(this).hasClass("last-col-td"))) {
                    var opts = $(this).resizable("options");
                    var ctrl = opts.Control;
                    var prox = $("<div></div>").css({ "z-index": 9999 }).addClass("mousemoveline");
                    if (d.dir == "s") {//上下
                        var pos = GetControlPosition(ctrl);
                        prox.addClass("mousemoveline-y").css({ width: ctrl.Width, left: pos.Left, top: -10000 });
                    }
                    else if (d.dir == "e") {//左右
                        var pos = GetTdResizeProxyPosition(ctrl, $(this));
                        prox.addClass("mousemoveline-x").css({ height: ctrl.Height, top: pos.Top, left: -10000 });
                    }
                    prox.appendTo(".report-designer");
                    d.MyProxy = prox;
                }
            },
            onResize: function (e) {
                var opts = $(this).resizable("options");
                var ctrl = opts.Control;

                //在父table内不可以改变大小
                if (ctrl.ParentControl && ($(this).hasClass("last-col-td") || $(this).hasClass("last-row-td"))) {
                    return false;
                }

                var d = e.data || {};
                var container = ctrl.Container.Container;
                var height = ctrl.Height + (d.height - d.startHeight) - 4;
                var pos = GetMouseAlias(e);
                if (d.dir == "s") {//垂直方向
                    if ($(this).hasClass("last-row-td")) {//最后一行,增加table高度
                        container.css({ height: height });
                        return false;
                    }
                    d.MyProxy.css({ top: pos.Y });
                    return false;
                }
                else if (d.dir == "e") {
                    if ($(this).hasClass("last-col-td")) {//左右方向,且是最后一格,增加table宽度
                        container.css({ width: (ctrl.Width + (d.width - d.startWidth) - 4) });
                        return false;
                    }
                    d.MyProxy.css({ left: pos.X });
                }
            },
            onStopResize: function (e) {
                var d = e.data || {};
                if (d.MyProxy) {
                    d.MyProxy.remove();
                }
                var opts = $(this).resizable("options");
                var ctrl = opts.Control;

                var col = $(this).index();
                var container = ctrl.Container.Container;

                var row = $(this).parent("tr").index();
                var rowspan = Z.V($(this).attr("rowspan"));
                if (rowspan > 1) {
                    row = row + rowspan - 1;
                }
                if (d.dir == "s") {//垂直方向
                    var tr = ctrl.Element.find(">tbody>tr:eq(" + row + ")");
                    var tds = tr.children();
                    if (rowspan > 1) {
                        tds = tds.add($(this));
                    }
                    ctrl.Element.find(">tbody>tr>td>.ctrl-container").css({ height: 0 });
                    //tds.children(".ctrl-container").css({ height: 0 }); //让它自适应
                    if ($(this).hasClass("last-row-td")) {//最后一行,增加table高度
                        if (!ctrl.ParentControl) {//在父table内不可以改变大小
                            var height = ctrl.Height + (d.height - d.startHeight);
                            ctrl.Height = height;
                            ctrl.UpdateLayout();
                        }
                        tds.css("height", "auto");
                        //   return;
                    }

                    var h = d.height;
                    var rowIndex = row;
                    while (rowspan-- > 1) {
                        var r = ctrl.Element.find(">tbody>tr:eq(" + (--rowIndex) + ")");
                        h -= r.outerHeight();
                    }
                    //console.log(row + "------" + h);
                    ctrl.SetHeight(row - 1, h);
                    tds.css({ height: "" });
                    tr.css({ height: h - 2 });
                    ctrl.UpdateLayout();


                }
                else if (d.dir == "e") {//左右方向
                    if ($(this).hasClass("last-col-td")) {//且是最后一格,增加table宽度
                        if (!ctrl.ParentControl) {//在父table内不可以改变大小
                            var width = ctrl.Width + (d.width - d.startWidth);
                            ctrl.Width = width;
                            var lastCol = ctrl.Element.find(">tbody>tr>td:last-child");
                            lastCol.children(".ctrl-container").css({ width: 0 }); //让它自适应
                            ctrl.UpdateLayout();
                        }
                        $(this).css("width", "auto");
                        return;
                    }

                    var w = d.width;
                    var colSpan = Z.V($(this).attr("colspan"));
                    if (colSpan > 1) {
                        col = col + colSpan - 1;
                        var colIndex = col;
                        var tr = ctrl.Element.find(">tbody>tr.tr-helper");
                        while (colSpan-- > 1) {
                            var td = tr.find("td:eq(" + (--colIndex) + ")");
                            w -= td.outerWidth();
                        }
                    }
                    opts.Control.ColDefines[col].Width.Value = w;
                    ctrl.Element.find(">tbody>tr.tr-helper>td:eq(" + col + ")").css({ width: w - 2 });
                    ctrl.UpdateLayout();
                }
            },
            Control: this
        });
    }

    this.MoveIn = function (e, source, cell, ctrl) {
        var nestTable = ctrl.Type == "LayoutTable" || ctrl.Type == "CrossTable" || ctrl.Type == "Table";
        //表格禁止嵌套
        if (nestTable) { this.SelectedCell = null; return null; }
        this.SetSelectedCell(cell);
        this.AddChild(ctrl);
    }

    this.ApplyClass = function () {
        var borderClass = TableClasses[Z.SafeToInt(this.TableBorderType)];
        var borderStyle = (this.TableBorderStyle == "Solid" ? "solid" : "dotted");
        var borderTypeClass = ("tb-" + borderStyle + "-border");
        this.Element.attr("class", "el-reporttable element")
                    .addClass("el-layouttable")
                    .addClass(borderTypeClass)
                    .addClass(borderClass);
    }

    this.ToChildItemsXML = function (childs) {
        var xml = new StringBuilder();
        if (childs && childs.length > 0) {
            xml.Append("<Items>");
            var list = childs.OrderBy(function (x) {
                // return x.GridCol;
                return x.GridRow;
            });

            for (var i = 0; i < list.length; i++) {
                var child = list[i];
                xml.Append(child.ToXML());
            }

            xml.Append("</Items>");
        }
        return xml.ToString();
    }

    this.ReBindReportHeight = function () {
        var rowIndex = 1; //由于辅助行,从1开始
        if (this.Header != null && this.Header.IsShow) {
            this.Header.RowHeight = this.Element.find(">tbody>tr:eq(" + rowIndex + ")").height();
            rowIndex++;
        }

        if (this.Groups && this.Groups.length > 0) {
            for (var i = 0; i < this.Groups.length; i++) {
                if (this.Groups[i].Header != null && this.Groups[i].Header.IsShow) {
                    //this.Groups[i].Header.RowHeight = GridTable.RowDefinitions[iRow].ActualHeight;
                }
            }
        }

        if (this.DataRow.IsShow) {
            this.DataRow.RowHeight = this.Element.find(">tbody>tr:eq(" + rowIndex + ")").height();
            rowIndex++;
        }

        if (this.Groups && this.Groups.length > 0) {
            for (var i = this.Groups.length - 1; i >= 0; i--) {
                if (this.Groups[i].Footer != null && this.Groups[i].Footer.IsShow) {
                    //this.Groups[i].Footer.RowHeight = GridTable.RowDefinitions[iRow].ActualHeight;
                }
            }
        }

        if (this.Footer != null && this.Footer.IsShow) {
            this.Footer.RowHeight = this.Element.find(">tbody>tr:eq(" + rowIndex + ")").height();
        }
    }

    //ReportTable
    this.ToXML = function () {
        this.ReBindReportHeight();
        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        //////////////其他属性

        xml.Append("<Name>" + this.Name + "</Name>");

        xml.Append(this.GetPropXML("BorderType", this.TableBorderType));
        xml.Append(this.GetPropXML("BorderStyle", this.TableBorderStyle));
        xml.Append(this.GetPropXML("BorderColor", this.TableBorderColor));
        xml.Append(this.GetPropXML("RepeatX", this.RepeatX));
        xml.Append(this.GetPropXML("BreakType", this.BreakType));
        xml.Append(this.GetPropXML("RepeatHeader", this.RepeatHeader));
        xml.Append(this.GetPropXML("RepeatFooter", this.RepeatFooter));
        xml.Append(this.GetPropXML("DataSource", this.DataSource));
        xml.Append(this.GetPropXML("SortField", this.OrderField));
        xml.Append(this.GetPropXML("SortType", this.OrderType));
        xml.Append(this.GetPropXML("MaxRow", this.MaxRow));

        //////////////列定义
        xml.Append("<Columns>");
        for (var i = 0; i < this.ColDefines.length; i++) {
            xml.Append("<Column Width=\"" + this.ColDefines[i].Width.GetValue() + "\" ");
            if (i != this.ColDefines.length - 1) {
                if (this.ColDefineUnits.Exist(function (x) { return x.Col == i; })) {
                    xml.Append("GridUnitType=\"" + this.ColDefineUnits.First(function (x) { return x.Col == i; }).GridUnitType + "\" ");
                }
            }
            else {
                xml.Append("GridUnitType=\"Star\" ");
            }
            xml.Append(" />");
        }
        xml.Append("</Columns>");

        //////////////基本样式
        xml.Append("<Style>");

        xml.Append(this.RenderCommonStyleXML());

        xml.Append("</Style>");

        //////////////筛选条件
        if (this.ListCond != null && this.ListCond.length > 0) {
            xml.Append("<Conditions>");
            xml.Append(getConditionXML(this.ListCond));
            xml.Append("</Conditions>");
        }

        //////////////表头、表尾、分组、数据
        if (this.Header != null && this.Header.IsShow) {
            xml.Append("<Header>");
            // xml.Append("<Height GridUnitType = \"" + this.Header.RowHeightUnitType + "\">" + this.Header.RowHeight + "</Height>");
            var rows = this.Header.Rows;
            xml.Append("<Rows>");
            for (var i = 0; i < rows.length; i++) {
                xml.Append("<Row Height=\"" + rows[i] + "\" />");
            }
            xml.Append("</Rows>");
            xml.Append(this.GetCDataPropXML("Function", this.Header.Function));
            xml.Append(this.ToChildItemsXML(this.Header.Items));
            xml.Append("</Header>");
        }
        //用于Property
        xml.Append("<HeaderProxy>");
        xml.Append(this.HeaderProxy);
        xml.Append("</HeaderProxy>");

        if (this.Groups && this.Groups.length > 0) {
            xml.Append("<Groups>");
            for (var i = 0; i < this.Groups.length; i++) {
                xml.Append("<Group>");
                xml.Append(this.GetPropXML("Name", this.Groups[i].Name));
                xml.Append(this.GetTextXML("GroupBy", this.Groups[i].GroupField));
                xml.Append(this.GetTextXML("SortField", this.Groups[i].SortField));
                xml.Append(this.GetPropXML("SortType", this.Groups[i].SortType));
                xml.Append(this.GetPropXML("BreakPage", this.Groups[i].BreakType));
                xml.Append(this.GetPropXML("RepeatHeader", this.Groups[i].RepeatHeader));
                xml.Append(this.GetPropXML("RepeatFooter", this.Groups[i].RepeatFooter));
                xml.Append(this.GetPropXML("Top", this.Groups[i].Top));
                xml.Append(this.GetPropXML("CombineColumn", this.Groups[i].CombineColumn));
                if (this.Groups[i].Header != null && this.Groups[i].Header.IsShow) {
                    xml.Append("<Header>");
                    //  xml.Append("<Height GridUnitType = \"" + this.Groups[i].Header.RowHeightUnitType + "\">" + this.Groups[i].Header.RowHeight + "</Height>");
                    xml.Append("<Rows>");
                    xml.Append("<Row Height=\"" + this.Groups[i].Header.RowHeight + "\" />");
                    xml.Append("</Rows>");
                    xml.Append(this.GetCDataPropXML("Function", this.Groups[i].Header.Function));
                    xml.Append(this.ToChildItemsXML(this.Groups[i].Header.Items));
                    xml.Append("</Header>");
                }

                if (this.Groups[i].Footer != null && this.Groups[i].Footer.IsShow) {
                    xml.Append("<Footer>");
                    //    xml.Append("<Height GridUnitType = \"" + this.Groups[i].Footer.RowHeightUnitType + "\">" + this.Groups[i].Footer.RowHeight + "</Height>");
                    xml.Append("<Rows>");
                    xml.Append("<Row Height=\"" + this.Groups[i].Footer.RowHeight + "\" />");
                    xml.Append("</Rows>");
                    xml.Append(this.GetCDataPropXML("Function", this.Groups[i].Footer.Function));
                    xml.Append(this.ToChildItemsXML(this.Groups[i].Footer.Items));
                    xml.Append("</Footer>");
                }

                xml.Append("</Group>");
            }
            xml.Append("</Groups>");
        }
        if (this.DataRow) {
            xml.Append("<DataRow>");
            //  xml.Append("<Height GridUnitType = \"" + this.DataRow.RowHeightUnitType + "\">" + this.DataRow.RowHeight + "</Height>");
            xml.Append("<Rows>");
            xml.Append("<Row Height=\"" + this.DataRow.RowHeight + "\" />");
            xml.Append("</Rows>");
            xml.Append(this.ToChildItemsXML(this.DataRow.Items));
            xml.Append("</DataRow>");
        }
        //if (this.Groups.length > 0)
        //{
        //    for (var i = this.Groups.length-1; i >=0; i--)
        //    {
        //        xml.Append("<GroupFooter>");
        //        xml.Append("<Height>" + this.Groups[i].Footer.RowHeight + "</Height>");
        //        xml.Append(this.ToChildItemsXML(this.Groups[i].Footer.Items));
        //        xml.Append("</GroupFooter>");
        //    }
        //}

        if (this.Footer != null && this.Footer.IsShow) {
            xml.Append("<Footer>");
            var rows = this.Footer.Rows;
            xml.Append("<Rows>");
            for (var i = 0; i < rows.length; i++) {
                xml.Append("<Row Height=\"" + rows[i] + "\" />");
            }
            xml.Append("</Rows>");
            xml.Append(this.GetCDataPropXML("Function", this.Footer.Function));
            xml.Append(this.ToChildItemsXML(this.Footer.Items));
            xml.Append("</Footer>");

        }
        xml.Append("<FooterProxy>");
        xml.Append(this.FooterProxy);
        xml.Append("</FooterProxy>");
        xml.Append(this.RenderEndXML());

        return xml.ToString();
    }

    this.ExplainControl = function (node) {
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var child = nodes[i];
            var name = child.nodeName;
            child = $(child);
            switch (name) {
                case "Columns": //列定义
                    if (child != null) {
                        var columns = child.children();
                        var colIndex = 0;
                        for (var j = 0; j < columns.length; j++) {
                            var column = $(columns[j]);
                            var colDef = new ColumnDefinition(new GridLength(Z.SafeToInt(column.attr("Width"))));
                            this.ColDefines.push(colDef);
                            if (column.attr("GridUnitType") != null) {
                                this.ColDefineUnits.push({ Col: colIndex, GridUnitType: column.attr("GridUnitType") });
                            }
                            colIndex++;
                        }
                    }
                    if (this.ColDefines.length != 0) {
                        this.ColDefines[this.ColDefines.length - 1].Width = this.ColDefines[this.ColDefines.length - 1].Width;
                    }
                    break;
                case "SortField":
                    this.OrderField = child.text();
                    break;
                case "SortType":
                    this.OrderType = child.text();
                    break;
                case "RepeatX":
                    this.RepeatX = child.text();
                    break;
                case "BreakType":
                    this.BreakType = child.text();
                    break;
                case "MaxRow":
                    this.MaxRow = child.text();
                    break;
                case "RepeatHeader":
                    this.RepeatHeader = child.text();
                    break;
                case "RepeatFooter":
                    this.RepeatFooter = child.text();
                    break;
                case "BorderType":
                    this.TableBorderType = child.text();
                    break;
                case "BorderStyle":
                    this.TableBorderStyle = child.text();
                    break;
                case "BorderColor":
                    this.TableBorderColor = child.text();
                    break;
                case "Conditions": //筛选条件
                    this.ListCond = ConditionToJSON(child);
                    break;
                case "DataSource":
                    this.DataSource = child.text();
                    break;
            }
        }

    }

    this.ExplainTableItems = function (node, row) {
        var items = node.children();
        for (var i = 0; i < items.length; i++) {
            var item = $(items[i]);
            var ctrl = this.ReportMain.CreateControl(item);
            container = new ControlContainer(ctrl);
            container.RemoveSelectedStyle();
            row.Items.push(ctrl);
        }
    }

    this.ExplainOther = function (node) {
        this.InitDataTable();

        this.Header.IsShow = false;
        this.Footer.IsShow = false;

        var items = node.children();
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var name = item.nodeName;
            item = $(item);
            switch (name) {
                case "Header":
                    this.Header.IsShow = true;
                    var headerProps = item.children();
                    for (var j = 0; j < headerProps.length; j++) {
                        var headerProp = headerProps[j];
                        var headerPropName = headerProp.nodeName;
                        headerProp = $(headerProp);
                        switch (headerPropName) {
                            case "Rows":
                                var rowsNode = headerProp.children();
                                this.Header.Rows = [];
                                for (var r = 0; r < rowsNode.length; r++) {
                                    this.Header.Rows.push($(rowsNode[r]).attr("Height"));
                                }
                                break;
                            case "Function":
                                this.Header.Function = headerProp.text();
                                break;
                            case "Items":
                                this.ExplainTableItems(headerProp, this.Header);
                                break;
                        }
                    }
                    break;
                case "HeaderProxy":
                    this.HeaderProxy = item.text();
                    break;
                case "DataRow":
                    //this.DataRow.RowHeightUnitType = item.children("Height").attr("GridUnitType");
                    //this.DataRow.RowHeight = Z.V(item.children("Height").text());
                    this.DataRow.RowHeight = Z.V(item.children("Rows").children("Row").attr("Height"));
                    this.ExplainTableItems(item.children("Items"), this.DataRow);
                    break;
                case "Footer":
                    this.Footer.IsShow = true;
                    var footerProps = item.children();
                    for (var k = 0; k < footerProps.length; k++) {
                        var footerProp = footerProps[k];
                        var footerPropName = footerProp.nodeName
                        footerProp = $(footerProp);
                        switch (footerPropName) {
                            case "Rows":
                                var rowsNode = footerProp.children();
                                this.Footer.Rows = [];
                                for (var r = 0; r < rowsNode.length; r++) {
                                    this.Footer.Rows.push(Z.V($(rowsNode[r]).attr("Height")));
                                }
                            case "Function":
                                this.Footer.Function = footerProp.text();
                                break;
                            case "Items":
                                this.ExplainTableItems(footerProp, this.Footer);
                                break;
                        }
                    }
                    break;
                case "FooterProxy":
                    this.FooterProxy = item.text();
                    break;
                case "Groups":
                    this.Groups = [];
                    var groups = item.children();
                    for (var x = 0; x < groups.length; x++) {
                        var groupItem = groups[x];
                        this.ExplainGroup($(groupItem));
                    }
                    break;
            }
        }
        this.ReLoadTable();
    }

    this.ExplainGroup = function (node) {
        var group = new TableGroup();
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var item = nodes[i];
            var name = item.nodeName;
            item = $(item);
            switch (name) {
                case "Name":
                    group.Name = item.text();
                    break;
                case "GroupBy":
                    group.GroupField = item.text();
                    break;
                case "SortField":
                    group.SortField = item.text();
                    break;
                case "SortType":
                    group.SortType = item.text();
                    break;
                case "BreakPage":
                    group.BreakType = item.text();
                    break;
                case "RepeatFooter":
                    group.RepeatFooter = item.text();
                    break;
                case "RepeatHeader":
                    group.RepeatHeader = item.text();
                    break;
                case "Top":
                    group.Top = item.text();
                    break;
                case "CombineColumn":
                    group.CombineColumn = item.text();
                    break;
                case "Header":
                    var header = new TableGroupHeader();
                    header.IsShow = true;
                    //header.RowHeightUnitType = item.children("Height").attr("GridUnitType");
                    //header.RowHeight = Z.V(item.children("Height").text());
                    header.RowHeight = Z.V(item.children("Rows").children("Row").attr("Height"));
                    var functionHeader = item.children("Function");
                    if (functionHeader != null && functionHeader.length > 0) {
                        header.Function = functionHeader.text();
                    }
                    this.ExplainTableItems(item.children("Items"), header);
                    header.Name = group.Name;
                    group.Header = header;
                    break;
                case "Footer":
                    var footer = new TableGroupFooter();
                    //footer.RowHeightUnitType = item.children("Height").attr("GridUnitType");
                    //footer.RowHeight = Z.V(item.children("Height").text());
                    footer.RowHeight = Z.V(item.children("Rows").children("Row").attr("Height"));
                    footer.IsShow = true;
                    var functionFooter = item.children("Function");
                    if (functionFooter.length > 0) {
                        footer.Function = functionFooter.text();
                    }
                    this.ExplainTableItems(item.children("Items"), footer);
                    footer.Name = group.Name;
                    group.Footer = footer;
                    break;
            }

        }
        this.Groups.push(group);
    }
}
ReportTable.prototype = new ReportControl();

var TableGridRow = function () {
    this.RowHeight = 22;

    /// <summary>
    /// 子控件
    /// </summary>
    this.Items = [];

    /// <summary>
    /// 表达式条件
    /// </summary>
    this.Function = null;

    this.IsShow = true;

    this.Type = null;

    this.GetDesc = function () {
        return this.Type;
    }

    this.RowHeightUnitType = String.Empty;

    this.GridRowHeight = function () {
        return GetGridLength(this.RowHeight, this.RowHeightUnitType);
    }
    var GetGridLength = function (value, gridUnitType) {
        switch (gridUnitType) {
            case "Auto":
                return GridLength.Auto;
            case "Pixel":
                return new GridLength(value);
            case "Star":
                return new GridLength(value, GridUnitType.Star);
        }
        return GridLength.Auto;
    }
}

var TableHeader = function () {
    //var rowDef = new RowDefinition();
    //rowDef.Height = new GridLength(22);
    this.Type = "表头";

    this.Rows = [22];
    this.Items = [];
}
TableHeader.prototype = new TableGridRow();

var TableFooter = function () {
    this.Type = "表尾";
    this.Rows = [22];
    this.Items = [];
}
TableFooter.prototype = new TableGridRow();

var TableDataRow = function () {
    this.Type = "数据行";
    this.Items = [];
}
TableDataRow.prototype = new TableGridRow();

var TableGroup = function () {
    /// <summary>
    /// 分组名称
    /// </summary>
    this.Name = null;
    /// <summary>
    /// 分组字段
    /// </summary>
    this.GroupField = null;
    /// <summary>
    /// 排序字段
    /// </summary>
    this.SortField = null;
    /// <summary>
    /// 排序类型
    /// </summary>
    this.SortType = null;

    /// <summary>
    /// 是否按该组分页方式
    /// </summary>
    this.BreakType = null;

    /// <summary>
    /// 是否重复分组表头
    /// </summary>
    this.RepeatHeader = null;

    /// <summary>
    /// 是否重复分组表尾
    /// </summary>
    this.RepeatFooter = null;

    /// <summary>
    /// 显示条数
    /// </summary>
    this.Top = null;

    /// <summary>
    /// 合并的列,以逗号分隔,NullOrEmpty表示不合并,0表示合并全部
    /// </summary>
    this.CombineColumn = null;
    this.Header = null;
    this.Footer = null;
}

var TableGroupHeader = function () {
    this.Type = "分组头";
    this.Name = null;
    this.Items = [];

    this.GetDesc = function () {
        return this.Name + this.Type;
    }
}
TableGroupHeader.prototype = new TableGridRow();

var TableGroupFooter = function () {
    this.Type = "分组尾";

    this.Name = null;
    this.Items = [];

    this.GetDesc = function () {
        return this.Name + this.Type;
    }
}
TableGroupFooter.prototype = new TableGridRow();

//////////////交叉表 Matrix
var ReportCrossTable = function () {
    this.IsIReportPanel = true;
    this.TableBorderType = null;
    this.TableBorderStyle = null;
    this.TableBorderColor = null;
    this.SelectedCellControl = null;

    this.ListCond = null;
    this.IsCanHasChild = true;
    this.Type = "CrossTable";
    this.TypeText = "交叉表";
    this.InitRowCount = 2;
    this.InitColCount = 2;
    this.ColumnGroups = [];
    this.RowGroups = [];

    this.ValueBodyXml = null;
    this.TitleBodyXml = null;
    this.RowDefines = [];
    this.ColDefines = [];
    this.ChildControls = [];

    //////////////重新加载
    this.ClearTable = function () {
        this.Element.empty();
        this.SelectedCell = null;
    }

    //CrossTable
    this.ReLoadTable = function () {
        this.ReportMain.SelectedReportControl = null;
        this.ClearTable();
        this.CreateTable();
    }

    //CrossTable
    this.ExplainGroups = function (node) {
        var groups = [];
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var prop = $(nodes[i]);
            var group = new ReportGroup();
            var items = prop.children();
            for (var j = 0; j < items.length; j++) {
                var item = items[j];
                var name = item.nodeName;
                item = $(item);
                switch (name) {
                    case "Name":
                        group.Name = item.text();
                        break;
                    case "GroupBy":
                        group.GroupField = item.text();
                        break;
                    case "SortField":
                        group.SortField = item.text();
                        break;
                    case "SortType":
                        group.SortType = item.text();
                        break;
                        //case "Size":
                        //    group.Size = Z.V(item.text());
                        //    break;
                        //case "LeftRows":
                        //    group.LeftRows = this.ExplainReportRows(item);
                        //    break;
                        //case "OuterLeftRows":
                        //    group.OuterLeftRows = this.ExplainReportRows(item);
                        //    break;
                        //case "TopRows":
                        //    group.TopRows = this.ExplainReportRows(item);
                        //    break;
                        //case "OuterTopRows":
                        //    group.OuterTopRows = this.ExplainReportRows(item);
                        //    break;
                        //case "RightRows":
                        //    group.RightRows = this.ExplainReportRows(item);
                        //    break;
                        //case "OuterRightRows":
                        //    group.OuterRightRows = this.ExplainReportRows(item);
                        //    break;
                        //case "BottomRows":
                        //    group.BottomRows = this.ExplainReportRows(item);
                        //    break;
                        //case "OuterBottomRows":
                        //    group.OuterBottomRows = this.ExplainReportRows(item);
                        //    break;
                    case "Items":
                        var ctrl = this.GetControl(item.children());
                        group.Items = ctrl;
                        this.ChildControls.push(ctrl);
                        //this.ReportMain.ExplainControls(item, this);
                        break;
                }
            }
            groups.push(group);
        }
        return groups;
    }

    //CrossTable
    this.ExplainOther = function (node) {
        var nodes = node.children();
        for (var i = 0; i < nodes.length; i++) {
            var prop = nodes[i];
            var name = prop.nodeName;
            prop = $(prop);
            switch (name) {
                case "ValueBody":
                    this.ValueBodyXml = prop.children();
                    break;
                case "ColumnGroups":
                    this.ColumnGroups = this.ExplainGroups(prop);
                    break;
                case "RowGroups":
                    this.RowGroups = this.ExplainGroups(prop);
                    break;
                case "TitleBody":
                    this.TitleBodyXml = prop.children();
                    break;
                case "Conditions": //筛选条件
                    this.ListCond = ConditionToJSON(prop);
                    break;
            }
        }
        this.ReLoadTable();
    }

    //////////////输出XML
    this.AppendItems = function (xml, items) {
        xml.Append("<Items>");
        xml.Append(items.ToXML());
        //for (var i = 0; i < items.length; i++) {
        //    var child = items[i];
        //    xml.Append(child.ToXML());
        //}
        xml.Append("</Items>");
    }

    this.ToGroup = function (xml, group) {
        xml.Append("<Group>");
        xml.Append(this.GetPropXML("Name", group.Name));
        xml.Append(this.GetTextXML("GroupBy", group.GroupField));
        xml.Append(this.GetPropXML("SortField", group.SortField));
        xml.Append(this.GetPropXML("SortType", group.SortType));
        if (group.Items != null && group.Items.length != 0) {
            this.AppendItems(xml, group.Items);
        }
        xml.Append("</Group>");
    }

    //this.ToReportRows = function (xml, name, rows) {
    //    if (rows != null && rows.length != 0) {
    //        xml.Append("<" + name + ">");
    //        for (var i = 0; i < rows.length; i++) {
    //            var row = rows[i];
    //            xml.Append("<ReportMember>");
    //            if (row.Items != null && row.Items.length != 0) {
    //                this.AppendItems(xml, row.Items);
    //            }
    //            xml.Append("</ReportMember>");
    //        }
    //        xml.Append("</" + name + ">");
    //    }
    //}

    //////////////更新行列的信息
    //this.FindControl = function (row, col) {
    //    for (var i = 0; i < this.ChildControls.length; i++) {
    //        var child = this.ChildControls[i];
    //        if (child.GridRow == row && child.GridCol == col) {
    //            return child;
    //        }
    //    }
    //    return null;
    //}

    this.RefreshData = function () {
        if (this.ChildControls && this.ChildControls.length > 0) {
            var row = this.ColumnGroups.length == 0 ? 1 : this.ColumnGroups.length
            var col = this.RowGroups.length == 0 ? 1 : this.RowGroups.length
            for (var i = 0; i < this.ChildControls.length; i++) {
                var child = this.ChildControls[i];
                if (child.GridRow == 0 && child.GridCol == 0)
                    this.TitleBodyXml = LoadXMLDom(child.ToXML());
                else if (child.GridRow > this.ColumnGroups.length - 1 && child.GridCol > this.RowGroups.length - 1)
                    this.ValueBodyXml = LoadXMLDom(child.ToXML());
                else if (child.GridRow == row && child.GridCol < col) {
                    if (this.RowGroups[child.GridCol])
                        this.RowGroups[child.GridCol].Items = this.ChildControls[i];
                }
                else {
                    if (this.ColumnGroups[child.GridRow])
                        this.ColumnGroups[child.GridRow].Items = this.ChildControls[i];
                }
            }
        }
    }

    this.ToValueBodyXML = function (xml) {
        xml.Append("<ValueBody>");
        for (var i = 0; i < this.ChildControls.length; i++) {
            var child = this.ChildControls[i];
            if (child.GridRow > this.ColumnGroups.length - 1 && child.GridCol > this.RowGroups.length - 1)
                xml.Append(child.ToXML());
        }
        xml.Append("</ValueBody>");
    }

    //CrossTable
    this.ToXML = function () {

        this.RefreshData();

        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        //行列定义
        this.ToRowColDefineXML(xml);

        //其他属性
        xml.Append(this.GetPropXML("DataSource", this.DataSource));

        //边框类型
        this.ToBorderXML(xml);

        //样式
        xml.Append("<Style>");
        xml.Append(this.RenderCommonStyleXML());
        xml.Append("</Style>");

        xml.Append("<Name>" + this.Name + "</Name>");

        //左上角子控件
        xml.Append("<TitleBody>");
        for (var i = 0; i < this.ChildControls.length; i++) {
            var child = this.ChildControls[i];
            if (child.GridRow == 0 && child.GridCol == 0)
                xml.Append(child.ToXML());
        }
        xml.Append("</TitleBody>");
        //add Control To Group


        //列分组
        xml.Append("<ColumnGroups>");
        for (var i = 0; i < this.ColumnGroups.length; i++) {
            this.ToGroup(xml, this.ColumnGroups[i]);
        }

        xml.Append("</ColumnGroups>");


        //行分组
        xml.Append("<RowGroups>");
        for (var i = 0; i < this.RowGroups.length; i++) {
            this.ToGroup(xml, this.RowGroups[i]);
        }
        xml.Append("</RowGroups>");

        //值控件
        this.ToValueBodyXML(xml);

        //////////////筛选条件
        if (this.ListCond != null && this.ListCond.length > 0) {
            xml.Append("<Conditions>");
            xml.Append(getConditionXML(this.ListCond));
            xml.Append("</Conditions>");
        }

        xml.Append(this.RenderEndXML());
        return xml.ToString();
    }
    this.MenuItems = new Array().concat(this.MenuItems);
    this.Create = function () {
        //this.MenuItems.Insert(0, {
        //    separator: true
        //}).Insert(0, {
        //    id: "m_LayoutTableProp",
        //    text: "表格属性",
        //    name: "LayoutTableProp",
        //    iconCls: "icon-edit"
        //}).Insert(0, {
        //    id: "m_LayoutTableCol",
        //    text: "表格列",
        //    name: "LayoutTableCol",
        //    children: [{
        //        id: "#m_AddColBefore",
        //        text: '<-在前面插入列',
        //        name: "AddColBefore",
        //        iconCls: 'icon-add'
        //    }, {
        //        id: "#m_AddColAfter",
        //        text: '在后面插入列->',
        //        name: "AddColAfter",
        //        iconCls: 'icon-add'
        //    }, {
        //        separator: true
        //    }, {
        //        id: "#m_ColAuto",
        //        text: '宽度自动增长',
        //        name: "ColAuto"
        //    }, {
        //        id: "#m_ColPixel",
        //        text: '宽度固定',
        //        name: "ColPixel"
        //    }, {
        //        id: "#m_ColStar",
        //        text: '宽度按比例',
        //        name: "ColStar"
        //    }, {
        //        separator: true
        //    }, {
        //        id: "#m_DeleteCol",
        //        text: '删除列',
        //        name: "DeleteCol",
        //        iconCls: "icon-remove"
        //    }]
        //}).Insert(0, {
        //    id: "m_LayoutTableRow",
        //    text: "表格行",
        //    name: "LayoutTableRow",
        //    children: [{
        //        id: "#m_AddRowBefore",
        //        text: '<-在前面插入行',
        //        name: "AddRowBefore",
        //        iconCls: 'icon-add'
        //    }, {
        //        id: "#m_AddRowAfter",
        //        text: '在后面插入行->',
        //        name: "AddRowAfter",
        //        iconCls: 'icon-add'
        //    }, {
        //        separator: true
        //    }, {
        //        id: "#m_RowAuto",
        //        text: '高度自动增长',
        //        name: "RowAuto"
        //    }, {
        //        id: "#m_RowPixel",
        //        text: '高度固定',
        //        name: "RowPixel"
        //    }, {
        //        id: "#m_RowStar",
        //        text: '高度按比例',
        //        name: "RowStar"
        //    }, {
        //        separator: true
        //    }, {
        //        id: "#m_DeleteRow",
        //        text: '删除行',
        //        name: "DeleteRow",
        //        iconCls: "icon-remove"
        //    }]
        //});
        this.Element = $("<table></table>").attr("cellpadding", "0")
                            .attr("cellspacing", "0")
                            .attr("title", (this.TypeText || "交叉表格") + "-" + this.ID);
        this.ApplyClass();

        this.CreateTable();
    }

    this.CreateTable = function () {
        //删除分组
        var delCol = this.RowDefines.length - this.ColumnGroups.length;
        if (this.RowDefines.length > 2) {
            for (var i = 0; i < delCol; i++) {
                this.RowDefines.pop();
            }
        }
        var delRow = this.ColDefines.length - this.RowGroups.length;
        if (this.ColDefines.length > 2) {
            for (var i = 0; i < delRow; i++) {
                this.ColDefines.pop();
            }
        }
        if (this.RowDefines == null || this.RowDefines.length == 0) {
            this.RowDefines = this.RowDefines || [];
            this.InitRowCol();
        }
        //添加分组
        var colLen = this.ColumnGroups.length + 1 - this.RowDefines.length;
        for (var i = 0; i < colLen; i++) {
            this.RowDefines.splice(this.RowDefines.length - 1, 0, new RowDefinition(new GridLength(22)));
        }
        var rowLen = this.RowGroups.length + 1 - this.ColDefines.length
        for (var i = 0; i < rowLen; i++) {
            this.ColDefines.splice(this.ColDefines.length - 1, 0, new ColumnDefinition(new GridLength(50)));
        }

        var rowCount = this.RowDefines.length;
        var colCount = this.ColDefines.length;
        for (var rowIndex = 0; rowIndex < rowCount ; rowIndex++) {
            var row = $("<tr></tr>");
            var rowDefine = this.RowDefines[rowIndex];
            row.css("height", rowDefine.Height.GetValue());
            for (var colIndex = 0; colIndex < colCount ; colIndex++) {
                var td = $("<td></td>");
                if (rowIndex == rowCount - 1) {
                    td.addClass("last-row-td");
                }
                if (colIndex == colCount - 1) {
                    td.addClass("last-col-td");
                }
                row.append(td);
            }
            this.Element.append(row);
        }

        this.AddHelperRow();
        this.CreateGroupField();
        this.BindCellResize(this.Element.find(">tbody>tr>td"));

    }
    //显示分组字段
    this.CreateGroupField = function () {
        //this.ChildControls = [];
        //var row = this.RowGroups.length;
        //var col = this.ColumnGroups.length;
        //var GroupFieldcell = null;
        //var Titalcell = null;
        //if (row > 0) {
        //    for (var i = row - 1; i >= 0; i--) {
        //        GroupFieldcell = new ReportTextBox();
        //        GroupFieldcell.Text = "[" + this.RowGroups[i].GroupField + "]";
        //        GroupFieldcell.TextAlign = "Center";
        //        GroupFieldcell.GridRow = col == 0 ? 1 : col; //列分组为空
        //        GroupFieldcell.GridCol = i;
        //        GroupFieldcell.GridRowSpan = 1;
        //        GroupFieldcell.GridColSpan = 1;
        //        GroupFieldcell.ReportMain = this.ReportMain;
        //        GroupFieldcell.CreateElement();
        //        this.ChildControls.push(GroupFieldcell);
        //    }
        //}
        //if (col > 0) {
        //    for (var colIndex = 0; colIndex < col; colIndex++) {
        //        var cell = new ReportTextBox();
        //        cell.Text = "[" + this.ColumnGroups[colIndex].GroupField + "]";
        //        cell.TextAlign = "Center";
        //        cell.GridRow = colIndex;
        //        cell.GridCol = row == 0 ? 1 : row;//行分组为空
        //        cell.GridRowSpan = 1;
        //        cell.GridColSpan = col - colIndex;
        //        cell.ReportMain = this.ReportMain;
        //        cell.CreateElement();
        //        this.ChildControls.push(cell);
        //    }
        //}

        if (this.TitleBodyXml && typeof (this.TitleBodyXml) == "object") {
            this.ExplainGroupControls(this.TitleBodyXml, this, "TitleBodyXml");
        }
        if (this.ValueBodyXml && typeof (this.ValueBodyXml) == "object") {
            this.ExplainGroupControls(this.ValueBodyXml, this, "ValueBodyXml");
        }
        for (var k = 0; k < this.ChildControls.length; k++) {
            var child = this.ChildControls[k];
            this.AddChild(child);
            child.MergeRowColSpan();
        }
    }
    //分组Items
    this.GetControl = function (node) {
        if (node != null && node != "") {
            var items = node;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var ctrl = this.ReportMain.CreateControl($(item));
                return ctrl;
            }
        }
    }
    //解析Title Or Body内容
    this.ExplainGroupControls = function (node, parentControl, type) {
        if (node != null && node != "") {
            var items = node;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var ctrl = this.ReportMain.CreateControl($(item));
                if (type == "TitleBodyXml") {
                    ctrl.GridRow = 0;
                    ctrl.GridCol = 0;
                    ctrl.GridRowSpan = this.ColumnGroups.length;
                    ctrl.GridColSpan = this.RowGroups.length;
                }
                else if (type == "ValueBodyXml") {
                    ctrl.GridRow = this.ColumnGroups.length;
                    ctrl.GridCol = this.RowGroups.length;
                    ctrl.GridRowSpan = 1;
                    ctrl.GridColSpan = 1;
                }
                this.AddChild(ctrl);
            }
        }
    }
    //重新计算元素行列位置
    this.ReLoadGroupControl = function () {
        this.ChildControls = [];
        var row = this.RowGroups.length;
        var col = this.ColumnGroups.length;
        if (row > 0) {
            for (var i = row - 1; i >= 0; i--) {
                var rowItems = this.RowGroups[i].Items;
                if (rowItems) {
                    rowItems.GridRow = col == 0 ? 1 : col; //列分组为空
                    rowItems.GridCol = i;
                    this.ChildControls.push(rowItems);
                }
            }
        }
        if (col > 0) {
            for (var colIndex = 0; colIndex < col; colIndex++) {
                var colItems = this.ColumnGroups[colIndex].Items;
                if (colItems) {
                    colItems.GridRow = colIndex;
                    colItems.GridCol = row == 0 ? 1 : row;//行分组为空
                    this.ChildControls.push(colItems);
                }
            }
        }
    }

    this.AddChild = function (ctrl) {
        //if (!isGroup) {     //只能添加 title/body内容
        var SelectedCell = this.SelectedCell || this.Element.find(">tbody > tr:eq(" + (ctrl.GridRow + 1) + ") > td:eq(" + ctrl.GridCol + ")");
        var rowIndex = SelectedCell.closest("tr").index();
        var colIndex = SelectedCell.index();
        if (rowIndex == this.RowDefines.length && colIndex == this.ColDefines.length - 1) {
            ctrl.GridRow = rowIndex - 1;
            ctrl.GridCol = colIndex;
            ctrl.GridRowSpan = 1;
            ctrl.GridColSpan = 1;
        }
        else if (rowIndex < this.RowDefines.length && colIndex < this.ColDefines.length - 1) {//辅助行
            ctrl.GridRow = 0;
            ctrl.GridCol = 0;
            ctrl.GridRowSpan = this.RowDefines.length - 1;
            ctrl.GridColSpan = this.ColDefines.length - 1;
        } else {
            // return null;
        }
        //}
        ctrl.MarginBottomWidth = 0;
        ctrl.MarginLeftWidth = 0;
        ctrl.MarginRightWidth = 0;
        ctrl.MarginTopWidth = 0;
        ctrl.IsCanChangeSize = false;
        if (!ctrl.Container)
            ctrl.Container = new ControlContainer(ctrl);
        ctrl.Container.DisableResize();
        ctrl.Container.MoveInTable();
        if (this.ReportMain.SelectedReportControl) {
            ctrl.GridCol = this.SelectedColIndex;
            ctrl.GridRow = this.SelectedRowIndex - 1; //减去辅助行
        }
        var cell = this.SelectedCell || this.Element.find(">tbody > tr:eq(" + (ctrl.GridRow + 1) + ") > td:eq(" + ctrl.GridCol + ")");
        var isDisplay = cell.is(":visible");
        ctrl.Container.RemoveSelectedStyle();
        ctrl.Container.Container.css({ width: 0, height: 0 });
        cell.append(ctrl.Container.Container);
        if (!this.ChildControls.Contains(ctrl)) {
            this.ChildControls.push(ctrl);
        }
        ctrl.ParentControl = this;
        ctrl.MergeRowColSpan();
        if (isDisplay) {
            ctrl.UpdateLayout();
        }
    }

    //////CrossTable
    var baseApplyCommonProps = this.ApplyCommonProps;
    this.ApplyCommonProps = function () {
        baseApplyCommonProps.call(this);
        this.Element.find(">tbody>tr:last").children().children(".ctrl-container").css({ height: 0 }); //最后行自适应
        this.Element.find(">tbody>tr>td:last-child").children(".ctrl-container").css({ width: 0 }); //最后列自适应
        this.Element.css("border", "");
        var color = this.TableBorderColor || "black";
        this.Element.css("border-color", color);
        this.Element.find(">tbody>tr>td").css("border-color", color);
        this.ApplyClass();
        if (this.ChildControls) {
            for (var i = 0; i < this.ChildControls.length; i++) {
                var child = this.ChildControls[i];
                var cell = child.Element.closest("td");
                child.Width = cell.is(":visible") ? cell.innerWidth() : NaN;
                child.Height = cell.is(":visible") ? cell.innerHeight() : NaN;
                child.UpdateLayout();
            }
        }
    }

    //前面插入一行,用于设置宽度(由于首行有合并列时,设置其它列的宽度无效)
    this.AddHelperRow = function () {
        var tr = $("<tr></tr>").addClass("tr-helper");
        for (var i = 0; i < this.ColDefines.length; i++) {
            var td = $("<td></td>");
            if (i == this.ColDefines.length - 1) {
                td.addClass("last-col-td");
            }
            else {
                td.css("width", this.ColDefines[i].Width.GetValue())
            }
            tr.append(td);
        }
        this.Element.prepend(tr);
    }

    this.BindCellResize = function (jq) {
        jq.resizable({
            handles: "e,s",
            onStartResize: function (e) {
                IsCellResizing = true;
                var d = e.data;
                if ((d.dir == "s" && !$(this).hasClass("last-row-td")) || (d.dir == "e" && !$(this).hasClass("last-col-td"))) {
                    var opts = $(this).resizable("options");
                    var ctrl = opts.Control;
                    var prox = $("<div></div>").css({ "z-index": 9999 }).addClass("mousemoveline");
                    if (d.dir == "s") {//上下
                        var pos = GetControlPosition(ctrl);
                        prox.addClass("mousemoveline-y").css({ width: ctrl.Width, left: pos.Left, top: -10000 });
                    }
                    else if (d.dir == "e") {//左右
                        var pos = GetTdResizeProxyPosition(ctrl, $(this));
                        prox.addClass("mousemoveline-x").css({ height: ctrl.Height, top: pos.Top, left: -10000 });
                        //prox.appendTo(ctrl.Container.Container);//这是一种方式,top:0
                    }
                    prox.appendTo(".report-designer");
                    d.MyProxy = prox;
                }
            },
            onResize: function (e) {
                var opts = $(this).resizable("options");
                var ctrl = opts.Control;
                //在父table内不可以改变大小
                if (ctrl.ParentControl && ($(this).hasClass("last-col-td") || $(this).hasClass("last-row-td"))) {
                    return false;
                }
                var d = e.data || {};
                var container = ctrl.Container.Container;
                var height = ctrl.Height + (d.height - d.startHeight) - 4;
                var pos = GetMouseAlias(e);
                if (d.dir == "s") {//垂直方向
                    if ($(this).hasClass("last-row-td")) {//最后一行,增加table高度
                        container.css({ height: height });
                        return false;
                    }
                    d.MyProxy.css({ top: pos.Y });
                    return false;
                }
                else if (d.dir == "e") {
                    if ($(this).hasClass("last-col-td")) {//左右方向,且是最后一格,增加table宽度
                        container.css({ width: (ctrl.Width + (d.width - d.startWidth) - 4) });
                        return false;
                    }
                    d.MyProxy.css({ left: pos.X });
                }
            },
            onStopResize: function (e) {
                var d = e.data || {};
                if (d.MyProxy) {
                    d.MyProxy.remove();
                }
                var opts = $(this).resizable("options");
                var ctrl = opts.Control;
                var col = $(this).index();
                var container = ctrl.Container.Container;
                var row = $(this).parent("tr").index();
                var rowspan = Z.V($(this).attr("rowspan"));
                if (rowspan > 1) {
                    row = row + rowspan - 1;
                }
                if (d.dir == "s") {//垂直方向
                    var tr = ctrl.Element.find(">tbody>tr:eq(" + row + ")");
                    var tds = tr.children();
                    if (rowspan > 1) {
                        tds = tds.add($(this));
                    }
                    ctrl.Element.find(">tbody>tr>td>.ctrl-container").css({ height: 0 });
                    //tds.children(".ctrl-container").css({ height: 0 }); //让它自适应
                    if ($(this).hasClass("last-row-td")) {//最后一行,增加table高度
                        if (!ctrl.ParentControl) {//在父table内不可以改变大小
                            var height = ctrl.Height + (d.height - d.startHeight);
                            ctrl.Height = height;
                            ctrl.UpdateLayout();
                        }
                        tds.css("height", "auto");
                        return;
                    }
                    var h = d.height;
                    var rowIndex = row;
                    while (rowspan-- > 1) {
                        var r = ctrl.Element.find(">tbody>tr:eq(" + (--rowIndex) + ")");
                        h -= r.outerHeight();
                    }
                    opts.Control.RowDefines[row - 1].Height.Value = h; //row-1,减去辅助行
                    tds.css({ height: "" });
                    tr.css({ height: h - 2 });
                    ctrl.UpdateLayout();
                }
                else if (d.dir == "e") {//左右方向
                    if ($(this).hasClass("last-col-td")) {//且是最后一格,增加table宽度
                        if (!ctrl.ParentControl) {//在父table内不可以改变大小
                            var width = ctrl.Width + (d.width - d.startWidth);
                            ctrl.Width = width;
                            var lastCol = ctrl.Element.find(">tbody>tr>td:last-child");
                            lastCol.children(".ctrl-container").css({ width: 0 }); //让它自适应
                            ctrl.UpdateLayout();
                        }
                        $(this).css("width", "auto");
                        return;
                    }
                    var w = d.width;
                    var colSpan = Z.V($(this).attr("colspan"));
                    if (colSpan > 1) {
                        col = col + colSpan - 1;
                        var colIndex = col;
                        var tr = ctrl.Element.find(">tbody>tr.tr-helper");
                        while (colSpan-- > 1) {
                            var td = tr.find("td:eq(" + (--colIndex) + ")");
                            w -= td.outerWidth();
                        }
                    }
                    opts.Control.ColDefines[col].Width.Value = w;
                    ctrl.Element.find(">tbody>tr.tr-helper>td:eq(" + col + ")").css({ width: w - 2 });
                    ctrl.UpdateLayout();
                }
            },
            Control: this
        });
    }

}
ReportCrossTable.prototype = new ReportLayoutTable();

var ReportGroup = function () {
    /// <summary>
    /// 分组名称
    /// </summary>
    this.Name = "";
    /// <summary>
    /// 宽度或高度
    /// </summary>
    this.Size = 0;
    /// <summary>
    /// 分组字段
    /// </summary>
    this.GroupField = "";
    /// <summary>
    /// 排序字段
    /// </summary>
    this.SortField = "";
    /// <summary>
    /// 排序类型
    /// </summary>
    this.SortType = "";

    /// <summary>
    /// 表达式条件
    /// </summary>
    //this.Function = null;

    //this.LeftRows = null;
    //this.OuterLeftRows = null;
    //this.TopRows = null;
    //this.OuterTopRows = null;
    //this.RightRows = null;
    //this.OuterRightRows = null;
    //this.BottomRows = null;
    //this.OuterBottomRows = null;
    this.Items = null;

}


//////////////图表
var ReportChart = function () {

    this.Chart = null;
    this.LegendTitle = null;

    this.isShowLegendTitle = false;

    this.Series = null;
    this.Keys = [];

    this.ChartType = "0";
    this.Type = "Chart";
    this.Width = 300;
    this.Height = 300;
    this.Halign = "Left";
    this.Valign = "Top";
    this.Title = "图表";
    //Test 
    this.ShowTitle = "0";
    this.Desc = "";
    this.TypeField = "";
    this.LegendField = "";
    this.ValueField = "";
    this.CountType = "0";
    this.LegendLocation = "0";

    this.ChartTypeIcons = ["icon-av_equalizer", "icon-editor_format_align_left", "icon-editor_show_chart",
                        "icon-editor_pie_chart", "icon-device_data_usage", "icon-device_signal_wifi_0_bar"];
    this.SetTypeIcon = function () {
        this.Element.find(".charttype-icon").removeClass().addClass("charttype-icon glyphicon " + this.ChartTypeIcons[Z.ToInt(this.ChartType)]);
    }

    this.Create = function () {
        //this.Element = $("<div></div>").addClass("el-chart").attr("title", "图表-" + this.ID).append("<img src=\"/image/chart.png\" />");
        this.Element = $("<div></div>").addClass("el-chart").attr("title", "图表-" + this.ID);
        var CharIcon = " <span class=\"charttype-icon glyphicon icon-editor_show_chart\"></span>";
        this.Element.append(CharIcon);
        this.SetTypeIcon();
        this.ExistSeries = (this.Series && this.Series.length > 0);
    }
    this.CreateDemoSource = function () {
    }

    //ReportChart
    this._BaseApplyCommonProps = this.ApplyCommonProps;
    this.ApplyCommonProps = function () {
        this._BaseApplyCommonProps();
        var $this = this;
        setTimeout(function () {
            var img = $this.Element.children("img");
            img.css({ "margin-top": (($this.Height - img.height()) / 2), "margin-left": (($this.Width - img.width()) / 2) });
        }, 0);
    }

    this.border_MouseLeftButtonDown = function (e) {
        if (EMW.Const.Window.IsDoubleClick) {
            this.ShowProp();
        }
    }

    //Chart
    this.Reload = function () {
        this.Element = null;
        this.Create();
        this.Chart.Title = this.Title;
        this.Chart.LegendTitle = this.LegendTitle;
        this.AddSeries();
        this.SetTypeIcon();
        this.UpdateLayout();
    }

    this.ToSerieXML = function (xml, seire) {
    }

    this.ToXML = function () {
        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        xml.Append(this.GetPropXML("Title", this.Title));
        xml.Append(this.GetPropXML("LegendTitle", this.LegendTitle));
        xml.Append(this.GetPropXML("IsShowLegendTitle", this.isShowLegendTitle));
        //Test 
        xml.Append(this.GetPropXML("ShowTitle", this.ShowTitle));
        xml.Append(this.GetPropXML("ChartType", this.ChartType));
        xml.Append(this.GetPropXML("Desc", this.Desc));
        xml.Append(this.GetPropXML("TypeField", this.TypeField));
        xml.Append(this.GetPropXML("LegendField", this.LegendField));
        xml.Append(this.GetPropXML("ValueField", this.ValueField));
        xml.Append(this.GetPropXML("CountType", this.CountType));
        xml.Append(this.GetPropXML("LegendLocation", this.LegendLocation));


        if (this.Series && this.Series.length > 0) {
            xml.Append("<Series>");
            for (var i = 0; i < this.Series.length; i++) {
                var kv = this.Series[i];
                xml.Append("<Item");
                if ((kv.Type && kv.Type != this.ChartType)) {
                    xml.Append(" Type =\"" + kv.Type + "\"");
                }
                xml.Append(">");
                if (kv.Legend) {
                    xml.Append("<Legend>").Append("<![CDATA[" + kv.Legend + "]]></Legend>");
                }
                if (kv.Value) {
                    xml.Append("<Value>").Append("<![CDATA[" + kv.Value + "]]></Value>");
                }
                xml.Append("</Item>");
            }
            xml.Append("</Series>");
        }
        if (this.Keys && this.Keys.length > 0) {
            xml.Append("<Keys>");
            for (var i = 0; i < this.Keys.length; i++) {
                var kv = this.Keys[i];
                xml.Append("<Item>");
                if (kv.Text) {
                    xml.Append("<Text>").Append("<![CDATA[" + kv.Text + "]]></Text>");
                }
                if (kv.Value) {
                    xml.Append("<Value>").Append("<![CDATA[" + kv.Value + "]]></Value>");
                }
                xml.Append("</Item>");
            }
            xml.Append("</Keys>");
        }
        xml.Append(this.GetPropXML("DataSource", this.DataSource));

        xml.Append("<Style>");
        xml.Append(this.RenderCommonStyleXML());
        xml.Append("</Style>");

        xml.Append("<Name>" + this.Name + "</Name>");
        xml.Append(this.RenderEndXML());

        return xml.ToString();
    }

    this.ExplainControl = function (node) {
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "Title":
                    this.Title = elem.text();
                    break;
                case "LegendTitle":
                    this.LegendTitle = elem.text();
                    break;
                case "ChartType":
                    this.ChartType = elem.text();
                    break;
                case "Series":
                    this.Series = this.ExplainSeries(elem);
                    break;
                case "Keys":
                    this.Keys = this.ExplainKeys(elem);
                    break;
                case "IsShowLegendTitle":
                    this.isShowLegendTitle = elem.text();
                    break;
                    break;
                case "DataSource":
                    this.DataSource = elem.text();
                    break;
                case "ShowTitle":
                    this.ShowTitle = elem.text();
                    break;
                case "ChartType":
                    this.ChartType = elem.text();
                    break;
                case "Desc":
                    this.Desc = elem.text();
                    break;
                case "TypeField":
                    this.TypeField = elem.text();
                    break;
                case "LegendField":
                    this.LegendField = elem.text();
                    break;
                case "ValueField":
                    this.ValueField = elem.text();
                    break;
                case "CountType":
                    this.CountType = elem.text();
                    break;
                case "LegendLocation":
                    this.LegendLocation = elem.text();
                    break;
            }
        }
    }

    this.ExplainSeries = function (elem) {
        var series = [];
        if (elem != null) {
            var elems = elem.children();
            for (var i = 0; i < elems.length; i++) {
                var item = $(elems[i]);
                var kv = { Value: item.children("Value").text(), Legend: item.children("Legend").text() };
                var type = item.attr("Type");
                if (type !== null && type !== undefined) {
                    kv.Type = type;
                }
                series.push(kv);
            }
        }
        return series;
    }

    this.ExplainKeys = function (elem) {
        var keys = [];
        if (elem != null) {
            var elems = elem.children();
            for (var i = 0; i < elems.length; i++) {
                var item = $(elems[i]);
                keys.push({ Value: item.children("Value").text(), Text: item.children("Text").text() });
            }
        }
        return keys;
    }
    this.ExplainLegendItems = function (node, serie) {
    }
}
ReportChart.prototype = new ReportControl();

var ReportChartSerie = function () {
}

var ReportLengendItem = function () {
    this.Title = null;
}

//////////////列表
var ReportList = function () {

    this.IsIReportPanel = true;
    /// <summary>
    /// 筛选条件
    /// </summary>
    this.ListCond = null;

    this.Groups = [];

    this.GridTable = null;

    this.IsCanHasChild = false;

    this.Type = "List";
    this.Width = 300;
    this.Height = 200;
    this.Halign = "Left";
    this.Valign = "Top";
    this.DefaultBackgroundColor = "White";
    this.IsCanHasChild = true;
    this.BorderLeftWidth = this.BorderTopWidth = this.BorderRightWidth = this.BorderBottomWidth = 1;
    this.BorderStyle = "dotted";
    this.ChildControls = [];

    //List
    this.AddChild = function (ctrl) {
    }

    this.RemoveChild = function (ctrl) {
        $(ctrl.Element).remove();
        this.ChildControls.Remove(ctrl);
    }
    //设置分组后调用
    this.ReLoadTable = function () {
    }
    //////////////选择单元格的位置
    this.SelectCell = function (e) {

    }

    this.Create = function () {
        this.Element = $("<div></div>").addClass("el-list").attr("title", "列表-" + this.ID).html("列表-" + this.ID);
    }

    //List
    this.ToXML = function () {
        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        xml.Append("<Style>");
        xml.Append(this.RenderCommonStyleXML());
        xml.Append("</Style>");
        xml.Append(this.GetPropXML("Name", this.Name));

        xml.Append(this.GetPropXML("DataSource", this.DataSource));

        //////////////筛选条件
        if (this.ListCond != null && this.ListCond.length > 0) {
            xml.Append("<Conditions>");
            xml.Append(getConditionXML(this.ListCond));
            xml.Append("</Conditions>");
        }
        if (this.Groups != null && this.Groups.length != 0) {
            xml.Append("<Groups>");
            for (var i = 0; i < this.Groups.length; i++) {
                var group = this.Groups[i];
                this.ToGroupXML(xml, group);
            }
            xml.Append("</Groups>");
        }

        //////////////子控件
        if (this.ChildControls != null && this.ChildControls.length != 0) {
            xml.Append("<Items>");
            for (var j = 0; j < this.ChildControls.length; j++) {
                var child = this.ChildControls[j];
                xml.Append(child.ToXML());
            }
            xml.Append("</Items>");
        }
        xml.Append(this.RenderEndXML());

        return xml.ToString();
    }

    //ReportList
    this.ExplainControl = function (node) {
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "Groups":
                    this.Groups = [];
                    var groupNodes = elem.children();
                    for (var j = 0; j < groupNodes.length; j++) {
                        var groupNode = groupNodes[j];
                        this.Groups.push(this.ExplainGroupXML($(groupNode)));
                    }
                    break;
                case "DataSource":
                    this.DataSource = elem.text();
                    break;
            }
        }
    }

    this.ExplainOther = function (node) {
        var items = node.children("Items");
        if (items != null) {
            this.ReportMain.ExplainControls(items, this);
        }
    }
}
ReportList.prototype = new ReportControl();

//////////////图像
var ReportImage = function () {

    this.ImageUrl = null;
    this.Field = null;

    /// <summary>
    /// 图片宽度和高度按比例
    /// </summary>
    this.SizeType = null;

    this.Type = "Image";
    this.Width = 100;
    this.Height = 100;
    this.Halign = "Left";
    this.Valign = "Top";
    this.DefaultBorderBottomWidth = 1;
    this.DefaultBorderLeftWidth = 1;
    this.DefaultBorderRightWidth = 1;
    this.DefaultBorderTopWidth = 1;

    //////////////重新加载图片
    this.baseUpdateLayout = this.UpdateLayout;
    this.Reload = function () {
        this.LoadImage();
        this.UpdateLayout();
    }

    //ReportImage
    this.UpdateLayout = function () {
        this.baseUpdateLayout();

        if (this.SizeType != "1") {
            this.Element.css({ width: this.Width - 4, height: this.Height - 4 });
        }
        else {
            var w = this.Width - 4;
            var h = this.Height - 4;
            if (this.Container) {
                // w = this.Container.Container.innerWidth();
                // h = this.Container.Container.innerHeight();
            }
            scaleImage.call(this, this.Element[0], w, h);
        }
        this.Container.Container.css("background", "white");
    }
    this.LoadImage = function () {
        if (this.ImageUrl) {
            this.Element.attr("src", this.ImageUrl);
        }
    }

    //按比例缩放图片
    var scaleImage = function (o, w, h) {
        var img = new Image();
        img.src = o.src;
        var width = this.Width;
        var height = this.Height;
        if (img.width > 0 && img.height > 0) {
            if (img.width / img.height >= w / h) {
                if (img.width > w) {
                    width = w;
                    height = (img.height * w) / img.width;
                }
                else {
                    width = img.width;
                    height = img.height;
                }
            }
            else {
                if (img.height > h) {
                    height = h;
                    width = (img.width * h) / img.height;
                }
                else {
                    width = img.width;
                    height = img.height;
                }
            }
        }

        marginTop = (h - height) / 2;
        marginLeft = (w - width) / 2;
        height = Math.floor(height);
        width = Math.floor(width);
        this.Element.css({ height: height, width: width, "margin-left": marginLeft, "margin-top": marginTop });
        this.Width = width;
        this.Height = height;
    }

    var clipImage = function (o, w, h) {
        var img = new Image();
        img.src = o.src;
        var width = this.Width;
        var height = this.Height;
        if (img.width > 0 && img.height > 0) {
            if ((img.width / img.height) >= (w / h)) {
                if (img.width > w) {
                    width = (img.width * h) / img.height;
                    height = h;
                    $(o).css("margin-left", "-" + ((o.width - w) / 2).toString() + "px");
                }
                else {
                    width = img.width;
                    height = img.height;
                }
            }
            else {
                if (img.height > h) {
                    height = (img.height * w) / img.width;
                    width = w;
                    $(o).css("margin-top", "-" + ((o.height - h) / 2).toString() + "px");
                }
                else {
                    width = img.width;
                    height = img.height;
                }
            }
        }
        height = Math.floor(height);
        width = Math.floor(width);
        this.Element.css({ height: height, width: width });
        this.Width = width;
        this.Height = height;
    }

    this.baseExcuteMenuCommand = this.ExcuteMenuCommand;
    this.ExcuteMenuCommand = function (commandname) {
        var $this = this;
        switch (commandname) {
            case "SelectImage":
                SelectImage(this, null);
                break;
            case "OriginalSize":
                this.ReSizeImage();
                break;
            default:
                this.baseExcuteMenuCommand(commandname);
                break;
        }
    }
    //图片原始大小
    this.ReSizeImage = function () {
        var src = this.Element.attr("src");
        if (src) {
            var img = new Image();
            img.src = src;
            this.Width = img.width;
            this.Height = img.Height;
            if (this.Container) {
                this.Container.Container.css({ height: "", width: "" });
            }
            this.Element.css({ "margin-left": "", "margin-top": "" });
            this.UpdateLayout();
        }
    }
    //////////////创建
    this.MenuItems = new Array().concat(this.MenuItems);
    this.Create = function () {
        this.MenuItems.Insert(0, {
            separator: true
        }).Insert(0, {
            id: "m_OriginalSize",
            text: "原始大小",
            name: "OriginalSize",
            iconCls: "icon-search"
        }).Insert(0, {
            id: "m_SelectImage",
            text: "选择相片",
            name: "SelectImage",
            iconCls: "icon-ok"
        });
        this.Element = $("<img />").attr("title", "图片-" + this.ID).attr("alt", "图片-" + this.ID).addClass("el-image");
        this.LoadImage();
    }

    this.ExplainControl = function (node) {
        var elems = node.children();
        for (var i = 0; i < elems.length; i++) {
            var elem = elems[i];
            var name = elem.nodeName;
            elem = $(elem);
            switch (name) {
                case "ImageUrl":
                    this.ImageUrl = elem.text();
                    break;
                case "SizeType":
                    this.SizeType = elem.text();
                    break;
                case "Field":
                    this.Field = elem.text();
                    break;
            }
        }
    }

    this.ToXML = function () {
        var xml = new StringBuilder();

        xml.Append(this.RenderBeginXML());

        xml.Append(this.GetPropXML("ImageUrl", this.ImageUrl));
        xml.Append(this.GetPropXML("SizeType", this.SizeType));
        xml.Append(this.GetPropXML("Field", this.Field));

        xml.Append("<Style>");
        xml.Append(this.RenderCommonStyleXML());
        // xml.Append(this.GetStylePropXML(this.Width, "width"));
        //xml.Append(this.GetStylePropXML(this.Height, "height"));
        xml.Append("</Style>");

        xml.Append(this.GetPropXML("Name", this.Name));

        xml.Append(this.RenderEndXML());

        return xml.ToString();
    }
}
ReportImage.prototype = new ReportControl();
ReportImage.prototype.DefaultSrc = "/Image/chatter/img.png";

var GridUnitType = {
    // 摘要:
    //     大小由内容对象的大小属性决定。
    Auto: 0,
    //
    // 摘要:
    //     该值以像素表示。
    Pixel: 1,
    //
    // 摘要:
    //     该值表示为可用空间的加权比例。
    Star: 2
}
var GridLength = function (value, type) {
    this.Value = value;
    this.GridUnitType = type || GridUnitType.Pixel;
    this.GetValue = function () {
        switch (this.GridUnitType) {
            case GridUnitType.Pixel:
                return this.Value || 0;
            default:
                return "100%";
        }
    }
}
GridLength.Auto = new GridLength(0, GridUnitType.Auto);

/****表格操作****/
var MergeRow = function (row, cell, rs) {
    var currentTable = row.closest("table");
    var rowSpan = GetValidSpan(rs);
    var rowIndex = row.index();
    var colIndex = cell.index();
    var rowSpanExist = GetRowSpan(cell);
    var colSpanExist = GetColSpan(cell);
    var addedRowSpan = rowSpan - rowSpanExist;
    if (addedRowSpan > 0) {//增加合并
        if (CheckMergeRow(currentTable, rowIndex, colIndex, rowSpan)) {
            var temp = addedRowSpan;
            var trIndex = rowIndex + rowSpanExist;
            while (temp-- > 0) {
                //TODO:colIndex不一定准确
                var mergeTr = GetTr(currentTable, trIndex);
                var temp2 = colSpanExist;
                var cellIndex = colIndex;
                while (temp2-- > 0) {
                    mergeTr.find(">td:eq(" + cellIndex + ")").hide();
                    cellIndex++;
                }
                trIndex++;
            }
            cell.attr("rowspan", rowSpan);
        } else { //更新属性值 ,merge Vale=max Allow
            if (ControlPropPanel.Items && ControlPropPanel.Items["GridRowSpan"])
                ControlPropPanel.Update("GridRowSpan", rowSpanExist);
        }
    }
    else if (addedRowSpan < 0) {//减少合并
        var temp = addedRowSpan;
        var trIndex = rowIndex + rowSpanExist - 1;
        while (temp++ < 0) {
            //var trIndex = rowIndex + rowSpanExist + addedRowSpan - temp;
            //TODO:colIndex不一定准确
            var tr = GetTr(currentTable, trIndex);
            var temp2 = colSpanExist;
            var cellIndex = colIndex;
            while (temp2-- > 0) {
                GetTd(tr, cellIndex).show();
                cellIndex++;
            }
            trIndex--;
        }
        cell.attr("rowspan", rowSpan);
    }
}

var MergeCell = function (row, cell, colSpan) {
    var rowIndex = row.index();
    var colIndex = cell.index();
    var colSpanExist = GetColSpan(cell);
    var addedColSpan = colSpan - colSpanExist;
    var rowSpanExist = GetRowSpan(cell);
    if (addedColSpan > 0) {
        if (CheckMergeCol(row, colIndex, colSpan)) {
            var mergeTr = row;
            var temp = addedColSpan;
            var cellIndex = colIndex + colSpanExist;
            while (temp-- > 0) {
                GetTd(mergeTr, cellIndex++).hide();
            }
            temp = rowSpanExist;
            while (temp-- > 1) {
                mergeTr = mergeTr.next();
                var temp2 = addedColSpan;
                cellIndex = colIndex + colSpanExist;
                while (temp2-- > 0) {
                    GetTd(mergeTr, cellIndex++).hide();
                }
            }
            cell.attr("colspan", colSpan);
        } else {//更新属性值 
            if (ControlPropPanel.Items && ControlPropPanel.Items["GridColSpan"])
                ControlPropPanel.Update("GridColSpan", colSpanExist);
        }
    }
    else if (addedColSpan < 0) {
        var temp = addedColSpan;
        var mergeTr = row;
        var cellIndex = colIndex + colSpanExist;
        while (temp++ < 0) {
            GetTd(mergeTr, --cellIndex).show();
        }
        temp = rowSpanExist;
        while (temp-- > 1) {
            mergeTr = mergeTr.next();
            var temp2 = addedColSpan;
            var cellIndex = colIndex + colSpanExist;
            while (temp2++ < 0) {
                GetTd(mergeTr, --cellIndex).show();
            }
        }
        cell.attr("colspan", colSpan);
    }
}

var GetRowSpan = function (cell) {
    return GetValidSpan(cell.attr("rowspan"));
}

var GetColSpan = function (cell) {
    return GetValidSpan(cell.attr("colspan"));
}

var GetValidSpan = function (v) {
    v = Z.SafeToInt(v);
    return v > 1 ? v : 1;
}

var GetTr = function (tb, i) {
    return tb.find(">tbody>tr:eq(" + i + ")");
}

var GetTd = function (tr, i) {
    return tr.find(">td:eq(" + i + ")");
}

var CheckMergeCol = function (tr, colIndex, colSpan) {
    var tds = tr.find(">td:gt(" + colIndex + ")");
    var canMergeCount = 1;
    for (var i = 0; i < tds.length; i++) {
        var td = $(tds[i]);
        if (td.children().length > 0) {
            break;
        }
        var cs = Z.SafeToInt(td.attr("colspan"));
        if (cs > 1) {
            break;
        }
        //if (td.is(":hidden")) {
        if (td.css("diplay") == 'none') {
            break;
        }
        canMergeCount++;
    }
    if (canMergeCount < colSpan) {//列数不够合并
        return false;
    }
    return true;
}

var CheckMergeRow = function (tb, rowIndex, colIndex, rowSpan) {
    var trs = tb.find(">tbody>tr:gt(" + rowIndex + ")");
    var canMergeCount = 1;
    for (var i = 0; i < trs.length; i++) {
        var td = GetTd($(trs[i]), colIndex);
        if (td.children().length > 0) {
            break;
        }
        var cs = Z.SafeToInt(td.attr("rowspan"));
        if (cs > 1) {
            break;
        }
        //if (td.is(":hidden")) {
        if (td.css("diplay") == 'none') {
            break;
        }
        canMergeCount++;
    }
    if (canMergeCount < rowSpan) {//列数不够合并1<1
        return false;
    }
    return true;
}
/***********Common Function****************/
var GetArgument = function (name) {
    /// <summary>获取(窗口)参数</summary>
    /// <param name="name" type="String">参数名</param>
    var wind = GetWindow();
    var val = null;
    if (wind) {
        val = wind[name];
        if (!val && wind.Arguments) {
            return wind.Arguments[name];
        }
    }
    return val;
}

var ConvertEmptyValue = function (value) {
    return (!value || value == "null" || value == "undefined" ? "" : value);
};

var LoadXMLDom = function (s) {
    //先转XML DOM,再转JQ对象
    var xmlDoc;
    if (!window.DOMParser) {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(s);
    }
    else {
        var parser = new DOMParser();
        xmlDoc = parser.parseFromString(s, "text/xml");
    }
    return $(xmlDoc.documentElement);
}

//保存数据源
var DataSourceToXML = function (DataSources) {
    if (DataSources == null || DataSources == []) return null;
    var xml = [];
    for (var ds = 0; ds < DataSources.length; ds++) {
        var name = DataSources[ds].Name;
        var dataSource = DataSources[ds].DataSource
        if (dataSource) {
            xml.push("<DataSource Name=\"" + name + "\">");
            var table;
            //主表
            if (dataSource.MainTable) {
                table = dataSource.MainTable;
                table.IsMainTable = 1;
                xml.push(tableToXML(table));
            }
            if (dataSource.Tables) {
                for (var i = 0; i < dataSource.Tables.length; i++) {
                    table = dataSource.Tables[i];
                    table.IsMainTable = 0;
                    xml.push(tableToXML(table));
                }
            }
            //条件
            if (dataSource.Conditions) {
                xml.push(ConditionToXML(dataSource.Conditions));
            }
            ////关系
            xml.push(RelationToXML(dataSource.Relations));

            // xml.push(ToOrderXml(dataSource));

            xml.push(" </DataSource>");
        }
    }
    return xml.join(String.Empty);
}

//JSON表数据转XML
var tableToXML = function (table) {
    var xml = [];
    var arr1 = ["Name", "ID", "AliasName", "Desc", "Image", "IsMainTable", "TableName"];
    var arr2 = ["Name", "AliasName", "ID", "Desc", "Accuracy", "FieldName", "InputType", "DBType", "IsAllowNull"]; //特殊处理
    xml.push("<Table");
    //表属性
    for (var i = 0; i < arr1.length; i++) {
        if (table[arr1[i]]) {
            xml.push(" ");
            xml.push(arr1[i] + "=\"" + table[arr1[i]] + "\"");
        }
    }
    xml.push(">");
    //字段
    for (var i = 0; i < table.Fields.length; i++) {
        var fields = table.Fields[i];
        xml.push("<Field");
        //字段属性
        for (var j = 0; j < arr2.length; j++) {
            var nn = arr2[j];
            var vv = fields[nn];
            if (vv != undefined && vv !== null) {
                xml.push(" " + nn + "=\"" + vv + "\"");
            }
        }
        xml.push(" />");
    }
    xml.push("</Table>");
    return xml.join("");
}

// Condition转XML 
var ConditionToXML = function (Conditions) {
    var xml = [];
    if (Conditions && Conditions.length > 0) {
        xml.push("<Conditions>");
        xml.push(getConditionXML(Conditions));
        xml.push("</Conditions>");
    }
    return xml.join("");
}

//递归获取xml节点
function getConditionXML(cond) {
    var ConditionXML = [];
    if (cond == null || cond.length == 0) return;
    for (var i = 0; i < cond.length; i++) {
        ConditionXML.push("<Item  Left=\"" + ConvertEmptyValue(cond[i].Left) + "\"  Oper=\"" + ConvertEmptyValue(cond[i].Oper) + "\"   Value=\"" + ConvertEmptyValue(cond[i].Right) + "\"   Desc=\"" + ConvertEmptyValue(cond[i].Desc) + "\">");
        if (cond[i].Conditions) {
            ConditionXML.push(getConditionXML(cond[i].Conditions));
        }
        ConditionXML.push("</Item>");
    }
    return ConditionXML.join("");
};

//关系
var RelationToXML = function (relations) {
    var xml = [];
    if (relations && relations.length > 0) {
        xml.push("<Relations>");
        $.each(relations, function (i, relation) {
            xml.push("<Item Target=\"" + relation.TargetTable + "\">");
            xml.push(getConditionXML(relation.Conditions));
            xml.push("</Item>");
        });
        xml.push("</Relations>");
    }
    return xml.join("");
}

//转换数据源为数组集合
var ConvertDS = function (node) {
    var DataSources = node.children();
    var DataSourcesData = [];
    for (var i = 0; i < DataSources.length; i++) {
        var DataSourceName = $(DataSources[i]).attr("Name");
        DataSourcesData.push({ Name: DataSourceName, DataSource: DataSourceToJSON($(DataSources[i])) });
    }
    return DataSourcesData;
};

//XML转JSON数据源
var DataSourceToJSON = function (xml) {
    var datasource; //数据源
    var keyvalue; //键值
    if (xml.find("Table").length > 0) {
        datasource = {};
        datasource.Tables = [];
        $.each(xml.find("Table"), function (i, table) {
            if ($(table).attr("IsMainTable") == "1") {
                //主表
                datasource.MainTable = tableToJSON(table);
            }
            else {
                //从表
                datasource.Tables.push(tableToJSON(table))
            }
        });
        datasource.Conditions = ConditionToJSON(xml.children("Conditions"));
        datasource.Relations = RelationToJSON(xml.children("Relations"));
    }
    return datasource;
}

//XML表数据转JSON
var tableToJSON = function (tableXml) {
    var table = {}, field;
    var arr1 = ["Name", "ID", "AliasName", "Desc", "IsMainTable", "TableName"];
    var arr2 = ["Name", "AliasName", "ID", "Desc", "Accuracy", "FieldName", "InputType", "DBType", "IsAllowNull"];
    //表信息
    for (var i = 0; i < arr1.length; i++) {
        table[arr1[i]] = $(tableXml).attr(arr1[i]);
    }
    //字段
    table.Fields = [];
    $.each($(tableXml).children(), function (k, f) {
        field = {};
        //字段信息
        for (var i = 0; i < arr2.length; i++) {
            field[arr2[i]] = $(f).attr(arr2[i]);
        }
        table.Fields.push(field)
    });
    return table;
};

//关系xml
var RelationToJSON = function (relaXML) {
    var relations = [];
    if (relaXML && relaXML.length > 0) {
        $.each($(relaXML).children(), function (i, item) {
            relations.push({
                TargetTable: $(item).attr("Target"),
                Type: $(item).attr("Type"),
                Conditions: ConditionToJSON($(item).children())//条件
            });
        });
    }
    return relations;
}

//条件xml
var ConditionToJSON = function (conXML) {
    var conditions = [];
    if (conXML && conXML.length > 0) {
        conditions = itemsToJSON(conXML.children());
    }
    return conditions;
};

var itemsToJSON = function (items) {
    var itemArr;
    if (items && items.length > 0) {
        itemArr = [];
        $.each(items, function (i, item) {
            itemArr.push({
                Left: $(item).attr("Left"),
                Oper: $(item).attr("Oper"),
                Right: $(item).attr("Value"),
                Desc: $(item).attr("Desc"),
                Conditions: itemsToJSON($(item).children())//数据源
            });
        });
    }
    return itemArr;
};

/*******控件的基本属性********/
//控件通用属性
var ControlCommonProperty = [
            {
                text: "基本", rows: [
                   { name: "Name", text: "名称", readOnly: true },
                   { name: "Width", text: "宽度", editor: "text" },
                   { name: "Height", text: "高度", editor: "text" }
                ]
            }, {
                text: "布局", rows: [
                   { name: "GridRow", text: "行", editor: "text", readOnly: true },
                   { name: "GridCol", text: "列", editor: "text", readOnly: true },
                   { name: "GridRowSpan", text: "行数", editor: "text" },
                   { name: "GridColSpan", text: "列数", editor: "text" },
                   { name: "MarginLeftWidth", text: "左外边距", editor: "text" },
                   { name: "MarginTopWidth", text: "上外边距", editor: "text" },
                   { name: "PaddingLeftWidth", text: "左内边距", editor: "text" },
                   { name: "PaddingTopWidth", text: "上内边距", editor: "text" },
                   { name: "PaddingRightWidth", text: "右内边距", editor: "text" },
                   { name: "PaddingBottomWidth", text: "下内边距", editor: "text" }
                ]
            }
];

var ControlProperty = {
    TextBox: [{
        text: "基本", rows: [
           //{
           //    name: "Text", text: "内容", editor: "text"
           //}
            {
                name: "Text", text: "内容", editor: function (data, item) { return setTextBoxFunc(data, item); }
                //, formatter: function (data, item) {
                //    var Text = data.Text;
                //    if (Text) {
                //        return Text;
                //    }
                //    return "";
                //}
            },
        ]
    }, {
        text: "文本", rows: [
           {
               name: "FontFamily", text: "字体", editor: "select", option: [{ value: "宋体", text: "宋体" },
              { value: "黑体", text: "黑体" }], textField: "text", valueField: "value"
           },
           {
               name: "FontSize", text: "大小", editor: "text"
           },
           {
               name: "Foreground", text: "字体颜色", editor: "text"
           },
           {
               name: "BackGroundColor", text: "背景颜色", editor: "text"

           },
           {
               name: "FontWeight", text: "粗体", editor: "select", option: [{ value: "Bold", text: "粗体" },
                                        { value: "Normal", text: "正常" }],
               textField: "text", valueField: "value", defautValue: "Normal"

           },
           {
               name: "FontStyle", text: "斜体", editor: "select", option: [{ value: "Italic", text: "斜体" },
                                        { value: "Normal", text: "正常" }],
               textField: "text", valueField: "value", defautValue: "Normal"

           },
           {
               name: "TextDecorations", text: "文本修饰", editor: "select", option: [{ value: "None", text: "无" },
                                        { value: "UnderLine", text: "下划线" },
                                        { value: "Line-Through", text: "删除线" },
                                        { value: "OverLine", text: "上划线" }]
               , textField: "text", valueField: "value", defaultValue: "None"

           },
           {
               name: "TextAlign", text: "水平对齐", editor: "select", option: [{ value: "Left", text: "左对齐" },
                                                                               { value: "Center", text: "居中对齐" },
                                                                               { value: "Right", text: "右对齐" }],
               textField: "text", valueField: "value", defaultValue: "Left"

           },
           {
               name: "TextValign", text: "居中对齐", editor: "select", option: [{ value: "Top", text: "上对齐" },
                                                                               { value: "Center", text: "居中对齐" },
                                                                               { value: "Bottom", text: "下对齐" }],
               textField: "text", valueField: "value", defaultValue: "Top"

           },
           {
               name: "IsWrap", text: "显示方式", editor: "checkbox", option: [{ value: "0", text: "自动换行" },
                                                                               { value: "1", text: "不换行" }],
               textField: "text", valueField: "value", defaultValue: 0

           }

        ]
    },
    {
        text: "边框", rows: [
           { name: "BorderLeftWidth", text: "左", editor: "text" },
           { name: "BorderTopWidth", text: "上", editor: "text" },
           { name: "BorderRightWidth", text: "右", editor: "text" },
           { name: "BorderBottomWidth", text: "下", editor: "text" },
           { name: "BorderColor", text: "颜色", editor: "text" },
        ]
    },
    {
        text: "其他", rows: [
           { name: "OutPut", text: "打印", editor: "checkbox" },
           { name: "Event", text: "事件", editor: "text" }
        ]
    }
    ],
    Image: [
        {
            text: "基本", rows: [
               {
                   name: "Field", text: "图片路径", editor: function (data, item) { return OpenFunc(data.Field, item); }
                   , formatter: function (data, item) {
                       return data.Field ? data.Field : "";
                   }
               },
               {
                   name: "ImageUrl", text: "图片", editor: function (data, item) { return SelectImage(data, item); }
                   , formatter: function (data, item) {
                       return data.ImageUrl ? data.ImageUrl : "未设置";
                   }
               },
               {
                   name: "SizeType", text: "缩放", editor: "select", option: [
                          { value: "1", text: "按比例缩放" },
                          { value: "0", text: "填满" },
                   ], textField: "text", valueField: "value", defaultValue: 0
               }
            ]
        }
    ],
    List: [
      {
          text: "基本", rows: [
             {
                 name: "DataSource", text: "数据源", editor: "select", optionCreator: function () { return GetDataSourceNames(); }, textField: "text", valueField: "value"
             },
              {
                  name: "ListCond", text: "筛选条件", editor: function (data, item) { return OpenCondition(data, item); }, formatter: function (data, item) {
                      var cond = data.ListCond;
                      if (cond && cond.length > 0) {
                          return "已设置";
                      }
                      return "未设置";
                  }
              }
              , {
                  name: "Groups", text: "分组", editor: function (data, item) { return GetTableGroup(data, item); }
                   , formatter: function (data, item) {
                       return data.Groups && data.Groups.length > 0 ? "已设置" : "未设置";
                   }
              }
          ]
      }
    ],
    LayoutTable: [
     {
         text: "基本", rows: [
           //{ name: "DataSource", text: "数据源", editor: "select", optionCreator: function () { return GetDataSourceNames(); }, textField: "text", valueField: "value" },
              {
                  name: "ListCond", text: "筛选条件", editor: function (data, item) { return OpenCondition(data, item); }, formatter: function (data, item) {
                      var cond = data.ListCond;
                      if (cond && cond.length > 0) {
                          return "已设置";
                      }
                      return "未设置";
                  }
              }
         ]
     }, {
         text: "边框", rows: [
                    {
                        name: "TableBorderStyle", text: "样式", editor: "select", option: [{ value: "Solid", text: "实线" },
                                { value: "Dotted", text: "虚线" }],
                        textField: "text", valueField: "value"
                    },
                    { name: "TableBorderColor", text: "颜色", editor: "text" },
                    {
                        name: "TableBorderType", text: "边框类型", editor: "select", option: [{ value: "0", text: "无边框" },
                                    { value: "1", text: "外边框" },
                                    { value: "2", text: "全部边框" },
                                    { value: "3", text: "内边框" },
                                    { value: "4", text: "下边框" }],
                        textField: "text", valueField: "value", defaultValue: 0
                    },
         ]
     }
    ],
    CrossTable: [
      {
          text: "基本", rows: [
                 { name: "DataSource", text: "数据源", editor: "select", optionCreator: function () { return GetDataSourceNames(); }, textField: "text", valueField: "value" },
              {
                  name: "ListCond", text: "筛选条件", editor: function (data, item) { return OpenCondition(data, item); }, formatter: function (data, item) {
                      var cond = data.ListCond;
                      if (cond && cond.length > 0) {
                          return "已设置";
                      }
                      return "未设置";
                  }
              },
             {
                 name: "RowGroups", text: "行分组", editor: function (data, item) { return CrossTableGroup(data, item); }
                   , formatter: function (data, item) {
                       return data.RowGroups && data.RowGroups.length > 0 ? "已设置" : "未设置";
                   }
             },
             {
                 name: "ColumnGroups", text: "列分组", editor: function (data, item) { return CrossTableGroup(data, item); }
                   , formatter: function (data, item) {
                       return data.ColumnGroups && data.ColumnGroups.length > 0 ? "已设置" : "未设置";
                   }
             }
          ]
      }
    ],
    Chart: [
     {
         text: "基本", rows: [
           { name: "DataSource", text: "数据源", editor: "select", optionCreator: function () { return GetDataSourceNames(); }, textField: "text", valueField: "value", defaultValue: 0 },
              {
                  name: "ListCond", text: "筛选条件", editor: function (data, item) { return OpenCondition(data, item); }, formatter: function (data, item) {
                      var cond = data.ListCond;
                      if (cond && cond.length > 0) {
                          return "已设置";
                      }
                      return "未设置";
                  }
              }
              //,{ name: "ExistSeries", text: "数据系列", editor: "text" }
         ]
     }
     //,
     //{
     //    text: "图表", rows: [
     //       { name: "Title", text: "标题", editor: "text" },
     //       { name: "LegendTitle", text: "图例标题", editor: "text" },
     //       { name: "ChartType", text: "类型", editor: "text" },
     //       { name: "Event", text: "事件", editor: "text" },
     //       { name: "isShowLegendTitle", text: "显示图例", editor: "text" }
     //    ]
     //}
    , {
        text: "图表", rows: [
          { name: "Name", text: "名称" },
            //{ name: "Title", text: "标题" },
            {
                name: "ShowTitle", text: "是否显示标题", editor: "select", textField: "text", valueField: "value",
                option: [{ "value": "1", "text": "显示" }, { "value": "0", "text": "不显示" }]
            },
            {
                name: "ChartType", text: "图表类型", editor: "select", option: [{ "value": "0", "text": "柱形图" },
                { "value": "1", "text": "水平柱形图" },
                { "value": "2", "text": "曲线" },
                { "value": "3", "text": "饼图" },
                { "value": "4", "text": "环形" },
                { "value": "5", "text": "漏斗" }], textField: "text", valueField: "value"
            },
           { name: "Desc", text: "说明" },
        ]
    }
    , {
        text: "数据", rows: [
                   {
                       name: "TypeField", text: "水平分类字段", editor: function (data, item) { return GetField(data, item); }, formatter: function (data, item) {
                           var TypeField = data.TypeField;
                           if (TypeField) {
                               return TypeField;
                           }
                           return "未设置";
                       }
                   },
                   {
                       name: "LegendField", text: "图例字段", editor: function (data, item) { return GetField(data, item); }, formatter: function (data, item) {
                           var LegendField = data.LegendField;
                           if (LegendField) {
                               return LegendField;
                           }
                           return "未设置";
                       }
                   },
                   {
                       name: "ValueField", text: "值字段", editor: function (data, item) { return GetField(data, item); }, formatter: function (data, item) {
                           var ValueField = data.ValueField;
                           if (ValueField) {
                               return ValueField;
                           }
                           return "未设置";
                       }
                   },
                   {
                       name: "CountType", text: "计算方式", editor: "select",
                       option: [{ "value": "0", "text": "计数(全部)" },
                           { "value": "1", "text": "计数(非空)" },
                           { "value": "2", "text": "求和" },
                           { "value": "3", "text": "平均" },
                           { "value": "4", "text": "最大" },
                           { "value": "5", "text": "最小", }], textField: "text", valueField: "value"
                   },
                  {
                      name: "LegendLocation", text: "图例位置", editor: "select", option:
                          [{ "value": "0", "text": "不显示" },
                              { "value": "1", "text": "左" },
                              { "value": "2", "text": "右" },
                              { "value": "3", "text": "下" },
                              { "value": "4", "text": "上" }], textField: "text", valueField: "value"
                  }]
    }
    ],
    Table: [
       {
           text: "基本", rows: [
              {
                  name: "RepeatX", text: "重复方式", editor: "select", option: [{ value: "0", text: "默认" },
                            { value: "1", text: "横向重复2次" },
                            { value: "2", text: "横向重复3次" },
                            { value: "3", text: "横向重复4次" }],
                  textField: "text", valueField: "value", defautValue: "0"
              },
              {
                  name: "BreakType", text: "分页方式", editor: "select", option: [{ value: "0", text: "默认" },
                            { value: "1", text: "按组设置分页" },
                            { value: "2", text: "设置每页显示行数" },
                            { value: "3", text: "按纸张大小分页" }],
                  textField: "text", valueField: "value", defautValue: "0"
              },
               {
                   name: "HeaderProxy", text: "表头", editor: "select", option: [{ value: "0", text: "无" },
                           { value: "1", text: "显示" },
                           { value: "Func", text: "表达式.." }], textField: "text", valueField: "value"
                               , formatter: function (data, item) {
                                   if (data.HeaderProxy == "Func") {
                                       return data.Header.Function;
                                   }
                                   return data.HeaderProxy == 0 ? "无" : "显示";
                               }
               },
               {
                   name: "FooterProxy", text: "表尾", editor: "select", option: [{ value: "0", text: "无" },
                            { value: "1", text: "显示" },
                            { value: "Func", text: "表达式.." }],
                   textField: "text", valueField: "value"
                   , formatter: function (data, item) {
                       if (data.FooterProxy == "Func") {
                           return data.Footer.Function;
                       }
                       return data.FooterProxy == 0 ? "无" : "显示";
                   }
               },
              {
                  name: "RepeatHeader", text: "每页表头方式", editor: "select", option: [{ value: "0", text: "不重复显示" },
                            { value: "1", text: "每页重复显示" }],
                  textField: "text", valueField: "value", defautValue: 0
              },
               {
                   name: "RepeatFooter", text: "每页表尾方式", editor: "select", option: [{ value: "0", text: "不重复显示" },
                              { value: "1", text: "每页重复显示" }],
                   textField: "text", valueField: "value", defautValue: 0
               }
           ]
       }, {
           text: "数据", rows: [
              { name: "DataSource", text: "数据源", editor: "select", optionCreator: function () { return GetDataSourceNames(); }, textField: "text", valueField: "value" },
              {
                  name: "ListCond", text: "筛选条件", editor: function (data, item) { return OpenCondition(data, item); }, formatter: function (data, item) {
                      var cond = data.ListCond;
                      if (cond && cond.length > 0) {
                          return "已设置";
                      }
                      return "未设置";
                  }
              },
             {
                 name: "Groups", text: "分组", editor: function (data, item) { return GetTableGroup(data, item); }
                   , formatter: function (data, item) {
                       return data.Groups && data.Groups.length > 0 ? "已设置" : "未设置";
                   }
             },
              {
                  name: "OrderField", text: "排序字段", editor: function (data, item) { return GetOrderFieldList(data, item); }
                  , formatter: function (data, item) {
                      var OrderField = data.OrderField;
                      if (OrderField) {
                          return OrderField;
                      }
                      return "未设置";
                  }
              },
              {
                  name: "OrderType", text: "排序方式", editor: "select", option: [{ value: "0", text: "升序" },
                              { value: "1", text: "降序" }], textField: "text", valueField: "value"
              },
              { name: "MaxRow", text: "显示行数", editor: "text" },
              { name: "DisplayCond", text: "显示条件", editor: "text" }
           ]
       },
        {
            text: "边框", rows: [
               {
                   name: "TableBorderStyle", text: "样式", editor: "select",
                   option: [{ value: "Solid", text: "实线" }, { value: "Dotted", text: "虚线" }],
                   textField: "text", valueField: "value"
               },
               { name: "TableBorderColor", text: "颜色", editor: "text" },
                {
                    name: "TableBorderType", text: "边框类型", editor: "select",
                    option: [{ value: "0", text: "无边框" },
                            { value: "1", text: "外边框" },
                            { value: "2", text: "全部边框" },
                            { value: "3", text: "内边框" },
                            { value: "4", text: "下边框" }],
                    textField: "text", valueField: "value", defautValue: 0
                }
            ]
        }
    ]
}


//添加控件共用属性
var GetControlProperty = function (cp) {
    var TempText = [];
    cp = ControlCommonProperty.concat(cp);
    for (var i = 0; i < cp.length; i++) {
        if (TempText.indexOf(cp[i].text) < 0) {
            TempText.push(cp[i].text);
        }
    }
    var tempCP = new Array();;
    for (var j = 0; j < TempText.length; j++) {
        tempCP.push({ text: TempText[j], rows: [] });
        for (var i = 0; i < cp.length; i++) {
            if (cp[i].text == TempText[j]) {
                for (var k = 0; k < cp[i].rows.length; k++) {
                    tempCP[j].rows.push(cp[i].rows[k]);
                }
            }
        }
    }
    return tempCP;
};
ControlProperty.TextBox = GetControlProperty(ControlProperty.TextBox);
ControlProperty.Image = GetControlProperty(ControlProperty.Image);
ControlProperty.List = GetControlProperty(ControlProperty.List);
ControlProperty.LayoutTable = GetControlProperty(ControlProperty.LayoutTable);
ControlProperty.CrossTable = GetControlProperty(ControlProperty.CrossTable);
ControlProperty.Chart = GetControlProperty(ControlProperty.Chart);
ControlProperty.Table = GetControlProperty(ControlProperty.Table);

//数据源控件
var CreateFieldControl = function (field) {
    var label = new ReportTextBox();
    label.ReportMain = this.ReportMain;
    label.Text = "[" + field + "]"; //FastReport 数据字段需标识
    label.CreateElement();
    ReportMain.AddChild(label);
    return label;
};

/*************属性面板相关操作******************/
//根据报表控件类型获取对应的属性
var GetCpByReportType = function (ctrl) {
    return ControlProperty[ctrl.Type];
};
//控件属性面板
var ShowControlAttr = function (ct) {
    if (ct.Type != "Image" && ct.Type != "TextBox") {
        if (ct.DataSource == null || ct.DataSource == "") {
            if (ReportMain.DataSources && ReportMain.DataSources.length > 0) {
                ct.DataSource = ReportMain.DataSources[0].Name;
            }
        }
    }
    ControlPropPanel.Bind(GetCpByReportType(ct), ct);
    EMW.UI.RightPanel.Show({
        Width: 300,
        Content: $("#ReportAttrPanel")
    });
};

//刷新设计面板
var ControlPropertyChanged = function (item, elem, oldValue) {
    switch (item.name) {
        case "HeaderProxy":
            setTable(item, elem, elem.Header);
            break;
        case "FooterProxy":
            setTable(item, elem, elem.Footer);
            break;
        case "DataSource":
            SetReportTableDataSource(item, elem, oldValue);
            break;
        case "GridRowSpan": //合并单元格
            var rowSpan = Z.SafeToInt(ControlPropPanel.GetText(item));
            rowSpan = rowSpan > 0 ? rowSpan : 0
            elem.GridRowSpan = rowSpan;
            elem.MergeRowColSpan();
            break;
        case "GridColSpan":
            var colSpan = Z.SafeToInt(ControlPropPanel.GetText(item));
            colSpan = colSpan > 0 ? colSpan : 0
            elem.GridColSpan = colSpan;
            elem.MergeRowColSpan();
            break;
        case "ChartType":
            elem.ChartType = Z.SafeToInt(ControlPropPanel.GetValue(item));
            elem.SetTypeIcon();
            break;
        default:
            break;
    }
    elem.UpdateLayout();
};

/************数据表操作*************/
//表头表尾表达式
var setTable = function (item, elem, table) {
    var selectValue = ControlPropPanel.GetValue(item);
    switch (selectValue) {
        case "0":
            table.IsShow = false;
            break;
        case "1":
            table.IsShow = true;
            table.Function = String.Empty;
            break;
        default:
            table.IsShow = true;
            var dia = EMW.UI.Dialog({
                title: "设置脚本",
                url: "/pages/table/ReportFunction.html",
                height: 600,
                OnOK: function (e) {
                    table.Function = e;
                    ControlPropPanel.Update(item, selectValue);
                }
            });
            dia.Script = table.Function;
            dia.ReportMain = ReportMain;
            break;
    }
    elem.ReLoadTable();

}

//设置文本框表达式
var setTextBoxFunc = function (ctrl, item) {
    var dia = EMW.UI.Dialog({
        title: "设置脚本",
        url: "/pages/table/ReportFunction.html",
        height: 600,
        OnOK: function (data) {
            ctrl.Text = data;
            ControlPropPanel.Update(item, data);
            ctrl.UpdateLayout();
        }

    });
    dia.Script = ctrl.Text;
    dia.ReportMain = ReportMain;
}
//表达式
var OpenFunc = function (elemobj, item) {
    var dia = EMW.UI.Dialog({
        title: "设置脚本",
        url: "/pages/table/ReportFunction.html",
        height: 600,
        OnOK: function (e) {
            elemobj = e;
            ControlPropPanel.Update(item, elemobj);
        }
    });
    dia.Script = elemobj;
    dia.ReportMain = ReportMain;
}

//ReportTable数据源
var SetReportTableDataSource = function (item, elem, oldValue) {
    elem.datasource = ControlPropPanel.GetValue(item);
}

//获取ReportTable Json数据源
var GetDataSourceNames = function () {
    var dom = [];
    var name = "";
    for (var i = 0; i < ReportMain.DataSources.length; i++) {
        name = ReportMain.DataSources[i].Name
        dom.push({ value: name, text: name });
    }
    return dom;
}

//数据表条件设置
var OpenCondition = function (data, item) {
    if (!data.DataSource) return;
    var ds = GetDataSourceByName(data.DataSource).DataSource;
    if (!ds) return;
    var win = EMW.UI.Dialog({
        url: "/pages/public/conditionbuilder.html",
        title: "条件设置",
        width: 800,
        height: 600,
        OnOK: function (cond) {
            data.ListCond = cond;
            ControlPropPanel.Update(item, cond);
        },
        coverTop: false
    });
    win.DataSource = ds;
    win.Conditions = data.ListCond
    win.Tables = ds.Tables;
    win.TemplateID = TemplateID;

}

//排序字段设置
var GetOrderFieldList = function (data, item) {
    if (!data.DataSource) return;
    var DataSource = GetDataSourceByName(data.DataSource).DataSource;
    var TableDom = GetTableTree(DataSource, data.OrderField);
    var div = $("<div class='tree' style='height:100%;'></div>");
    div.Tree({ data: TableDom })
    var win = EMW.UI.Dialog({
        Width: 300,
        title: "选择排序字段",
        content: div,
        OnOK: function (e) {
            var elem = div.Tree().GetSelected();
            if (elem.nodeType != "Filed") return false;
            data.OrderField = elem.name;
            ControlPropPanel.Update(item, data.OrderField);
        }
    });

}

//选择图片 
var SelectImage = function (data, item) {
    var win = EMW.UI.Window({
        url: "Pages/Public/UploadImage.html",
        title: "上传图片",
        width: 438,
        height: 504,
        OnOK: function (ImgAddress) {
            if (ImgAddress) {
                var userpath = "/Resource/" + (EMW.Global.User ? EMW.Global.User.CompanyCode : "emw") + "/UserImage/";
                data.ImageUrl = userpath + ImgAddress;
                data.Field = data.ImageUrl;
                ControlPropPanel.Update("ImageUrl", data.ImageUrl);
                ControlPropPanel.Update("Field", data.Field);
                data.Reload();
            }
        }
    });
}

//交叉表分组设置
var CrossTableGroup = function (data, item) {
    data.RefreshData();
    var loadGroups = null;
    if (item.name == "ColumnGroups")
        loadGroups = data.ColumnGroups;
    else
        loadGroups = data.RowGroups;
    var win = EMW.UI.Dialog({
        url: "/pages/Table/ReportGroup.html",
        title: item.text,
        width: 800,
        height: 600,
        OnOK: function (groups) {
            if (item.name == "ColumnGroups")
                data.ColumnGroups = groups;
            else
                data.RowGroups = groups;
            data.ReLoadGroupControl();
            data.ReLoadTable();
            ControlPropPanel.Update(item.name, groups);
        }
    });
    win.ReportMain = ReportMain;
    win.Groups = loadGroups;
}

//数据表分组设置
var GetTableGroup = function (data, item) {
    if (!data.DataSource) return false;
    var loadGroups = data.Groups;
    var GroupRowCount = data.GroupsRowCount();
    var win = EMW.UI.Dialog({
        url: "/pages/Table/ReportTableGroup.html",
        title: item.text,
        width: 550,
        height: 600,
        OnOK: function (groups) {
            data.Groups = groups;
            data.UpdateFooterRowIndex(GroupRowCount);
            data.ReLoadTable();
            ControlPropPanel.Update(item.name, groups);

        }
    });
    win.ReportMain = ReportMain;
    win.Groups = loadGroups;
    win.DataSource = data.DataSource;
}

//选择数据源字段
var GetField = function (data, item) {
    if (!data.DataSource) return false;
    var DataSource = GetDataSourceByName(data.DataSource).DataSource;
    var TableDom = GetTableTree(DataSource, data[item.name]);
    var div = $("<div class='tree' style='height:100%;'></div>");
    div.Tree({ data: TableDom })
    var win = EMW.UI.Dialog({
        width: 300,
        title: "选择字段",
        content: div,
        OnOK: function (e) {
            var elem = div.Tree().GetSelected();
            if (elem.nodeType != "Filed") return false;
            data[item.name] = elem.name;
            ControlPropPanel.Update(item, elem.name);
            return elem.name;
        }
    });

}

  

posted @ 2017-02-15 11:13  麦籽  阅读(18)  评论(0)    收藏  举报