

function outSpan(value) {
    if (value == null || 'undefined' == typeof (value)) value = '';
    else
        value = ('' + value).toXmlStr();
    return '<span title="' + value + '">' + value + '</span>';
}






//TemplateData
function TemplateData() {
    var self = this;

    //控件jquery对象
    self.jqGrid;

    /**
     *
     * @param isReload bool型，为true则reload，否则直接load
     */
    self.getLst = function (isReload) {
        if (true == isReload) {
            self.jqGrid.datagrid("reload");
        } else {
            self.jqGrid.datagrid("load");
        }
    };


    self.refreshAfterChange = function (id) {
        self.getLst(true);
    }

    var dataProvider;
    var filterAtFields;

    self.init = function (param) {
        //param = {
        //    gridConfig: {},
        //    jqGrid: $(''),
        //    dataProvider: null,
        //    filterAtFields: {}
        //}

        self.jqGrid = param.jqGrid;
        dataProvider = param.dataProvider;
        filterAtFields = param.filterAtFields;

        //gridConfig.width = 1200;
        //gridConfig.height = Math.max($(document).height() - 400, 430);


        var gridConfig = getInitGridConfig();

        //合并toolbar
        if (gridConfig.toolbar && param.gridConfig.toolbar) {
            param.gridConfig.toolbar = gridConfig.toolbar.concat(param.gridConfig.toolbar);
        }


        $.extend(gridConfig, param.gridConfig);

        self.jqGrid.datagrid(gridConfig);

        var p = self.jqGrid.datagrid('getPager');
        if (p) {
            $(p).pagination({
                beforePageText: '第',
                afterPageText: '页    共 {pages} 页',
                displayMsg: "当前显示 {from} - {to} 条数据   共 {total} 条数据"
            });
        }
    };


    self.getRow = function (id) {

        let rows = self.getRows();
        if (!rows) return null;
        let idField = controller.controllerConfig.idField;

        return rows.find(row => row[idField] == id);
    };


    self.getRows = function () {
        return self.jqGrid.datagrid('getRows');
    };



    //初始化gridConfig
    function getInitGridConfig() {
        var gridConfig = {
            title: '数据列表',
            iconCls: 'icon-tip',
            nowrap: true,
            autoRowHeight: false,
            striped: true,
            loadMsg: "正在载入数据，请稍等……",
            fitColumns: false,
            pagination: true,
            singleSelect: true,
            multiSort: true,
            toolbar: [{
                text: '刷新',
                iconCls: 'icon-reload',
                handler: function () {
                    self.getLst();
                }
            }],
            loader: function (param, success, error) {
                //success(data)：当检索数据成功时调用该回调函数
                var filterRules = [];
                var queryParam = {
                    "page": {
                        "pageSize": param.rows,
                        "pageIndex": param.page
                    },
                    "filter": { condition: "and", rules: filterRules },
                    "sort": []
                };

                //(x.1)filter
                autoTemp.Field.getFilter(filterRules, filterAtFields);
                if (!filterRules.length) queryParam.filter = null;

                //(x.2)sort
                if (param.sort) {
                    //sort  "name,age"
                    //order "asc,asc"
                    var sort = param.sort.split(',');
                    var order = param.order.split(',');
                    for (var t in sort) {
                        queryParam.sort.push({ "field": sort[t], "asc": order[t] == 'asc' });
                    }
                } else {
                    if (controllerConfig?.listConfig?.defaultSort) {
                        queryParam.sort = controllerConfig.listConfig.defaultSort;
                    }
                }

                function onSuccess(apiRet) {
                    if (!theme.alertApiReturn(apiRet)) {
                        error();
                        return;
                    }

                    //{"total":500,"rows":[]}
                    var data = { "total": apiRet.data.totalCount, "rows": apiRet.data.items };
                    success(data);
                }

                dataProvider.getList(queryParam, onSuccess);
            },

            rownumbers: true,
            rowStyler: function (index, row) {
                return 'height:30px;vertical-align:middle;';
            }
        };


        //(x.x)toolbar 添加
        if (controller.getPermit('insert')) {
            gridConfig.toolbar.push('-');
            gridConfig.toolbar.push({
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    var dialogParam = {
                        init: function () {
                            var iframe = this.iframe.contentWindow;
                            iframe.window.event_afterSave = function () { self.getLst(true); };
                        }
                    };
                    var search = location.search;
                    search += search ? '&' : '?';
                    search += 'mode=insert';
                    theme.popDialog('item.html' + search, '添加', null, null, dialogParam);
                }
            });
        }

        return gridConfig;
    }

}






//TemplateTree
function TemplateTree() {
    var self = this;

    //控件jquery对象
    self.jqGrid;


    /**
     *
     * @param isReload bool型，为true则reload，否则直接load
     */
    self.getLst = function (isReload) {
        if (true == isReload) {
            self.jqGrid.treegrid("reload");
        } else {
            self.jqGrid.treegrid("load");
        }
    };


    self.refreshAfterChange = function (id) {
        var pNode = self.jqGrid.treegrid('getParent', id);
        var pid = null;
        if (null != pNode) {
            pid = pNode[idField];
        }

        if (null != pid) {
            self.jqGrid.treegrid('reload', pid);

        } else {
            self.jqGrid.treegrid("reload");
        }
    }

    var dataProvider;
    var filterAtFields;
    var idField;
    var pidField;
    var rootPidValue = '0';

    self.init = function (param) {
        //param = {
        //    gridConfig: {},
        //    jqGrid: $(''),
        //    dataProvider: null,
        //    filterAtFields: {}
        //}

        self.jqGrid = param.jqGrid;
        dataProvider = param.dataProvider;
        filterAtFields = param.filterAtFields;

        idField = param.gridConfig.idField;
        pidField = param.controllerConfig.pidField;
        if (param.controllerConfig.rootPidValue != null)
            rootPidValue = param.controllerConfig.rootPidValue;

        //gridConfig.width = 1200;
        //gridConfig.height = Math.max($(document).height() - 400, 430);

        var gridConfig = getInitGridConfig();

        //合并toolbar
        if (gridConfig.toolbar && param.gridConfig.toolbar) {
            param.gridConfig.toolbar = gridConfig.toolbar.concat(param.gridConfig.toolbar);
        }

        $.extend(gridConfig, param.gridConfig);

        addAutoTemp_row_menu();

        self.jqGrid.treegrid(gridConfig);

        var p = self.jqGrid.datagrid('getPager');
        if (p) {
            $(p).pagination({
                beforePageText: '第',
                afterPageText: '页    共 {pages} 页',
                displayMsg: "当前显示 {from} - {to} 条数据   共 {total} 条数据"
            });
        }
    };

    self.getRow = function (id) {
        return self.jqGrid.treegrid('find', id);
    };


    self.getRows = function () {
        return self.jqGrid.treegrid('getData');
    };

    //初始化gridConfig
    function getInitGridConfig() {
        var gridConfig = {
            title: '数据列表',
            iconCls: 'icon-tip',
            nowrap: true,
            autoRowHeight: false,
            striped: true,
            loadMsg: "正在载入数据，请稍等……",
            fitColumns: false,
            pagination: true,
            singleSelect: true,
            multiSort: true,

            animate: true,
            remoteSort: true,
            lines: true,

            toolbar: [{
                text: '刷新',
                iconCls: 'icon-reload',
                handler: function () {
                    self.getLst();
                }
            }],
            onBeforeLoad: function (row, param) {
                if (row) {
                    //not root
                    param.isRoot = false;
                    param.pid = row[idField];
                }
                else {
                    //is root
                    param.isRoot = true;
                }
            },
            loader: function (param, success, error) {
                //success(data)：当检索数据成功时调用该回调函数。

                var filterRules = [];
                var queryParam = {
                    "filter": { condition: "and", rules: filterRules },
                    "sort": []
                };


                //(x.1) root or not root
                var isRoot = true;
                if (param.isRoot) {
                    //is root
                    queryParam.page = { pageSize: param.rows, pageIndex: param.page };
                    queryParam.arg = { isRoot: true, pid: rootPidValue };
                    // filterRules.push({ field: pidField, operator: "=", value: rootPidValue });
                    filterRules.push({ condition: "or", rules: [{ field: pidField, operator: "=", }, { field: pidField, operator: "=", value: rootPidValue }] });
                } else {
                    //not root
                    isRoot = false;
                    queryParam.arg = { isRoot: false, pid: param.pid };
                    filterRules.push({ field: pidField, operator: "=", value: param.pid });
                }


                //(x.2)filter
                if (isRoot && filterAtFields && filterAtFields.length != 0) {
                    autoTemp.Field.getFilter(filterRules, filterAtFields);
                }

                //(x.3)sort
                if (param.sort) {
                    //sort  "name,age"
                    //order "asc,asc"
                    var sort = param.sort.split(',');
                    var order = param.order.split(',');
                    for (var t in sort) {
                        queryParam.sort.push({ "field": sort[t], "asc": order[t] == 'asc' });
                    }
                } else {
                    if (controllerConfig?.listConfig?.defaultSort) {
                        queryParam.sort = controllerConfig.listConfig.defaultSort;
                    }
                }

                function onSuccess(apiRet) {
                    if (!theme.alertApiReturn(apiRet)) {
                        error();
                        return;
                    }

                    var rows = apiRet.data.items;
                    for (var t in rows) {
                        var row = rows[t];
                        if (row._childrenCount != 0)
                            rows[t].state = 'closed';
                    }

                    if (isRoot) {
                        success({ "total": apiRet.data.totalCount, "rows": rows });
                    } else {
                        success(rows);
                    }
                }
                dataProvider.getList(queryParam, onSuccess);
            },
            rownumbers: true,
            rowStyler: function (index, row) {
                return 'height:30px;vertical-align:middle;';
            }
        };

        //(x.x)toolbar 添加
        if (controller.getPermit('insert')) {
            gridConfig.toolbar.push('-');
            gridConfig.toolbar.push({
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    var dialogParam = {
                        init: function () {
                            var iframe = this.iframe.contentWindow;
                            iframe.window.event_afterSave = function () {
                                self.getLst(true);
                            };
                        }
                    };
                    var search = location.search;
                    search += search ? '&' : '?';
                    search += 'mode=insert';
                    theme.popDialog('item.html' + search, '添加', null, null, dialogParam);
                }
            });
        }


        return gridConfig;
    }


    function addAutoTemp_row_menu() {

        //添加操作列的操作
        //添加子数据
        if (controller.getPermit('insert')) {
            controller.addRowButton({
                text: '添加子数据',
                onclick: function (id) {
                    var dialogParam = {
                        init: function () {
                            var iframe = this.iframe.contentWindow;
                            iframe.window.event_afterSave = function () {
                                var treeNode = $('#dl').treegrid('find', id);
                                if (null == treeNode) {
                                    self.jqGrid.treegrid('reload');
                                } else {
                                    if (!treeNode._childrenCount) {
                                        treeNode._childrenCount = 1;
                                        treeNode.state = "closed";
                                        self.jqGrid.treegrid('refresh', id);
                                    }
                                    self.jqGrid.treegrid('reload', id);
                                }
                            };
                        }
                    };
                    var search = location.search;
                    search += search ? '&' : '?';
                    search += 'mode=insert&pid=' + id;
                    theme.popDialog('item.html' + search, '添加子数据', null, null, dialogParam);
                }
            });
        }

        //刷新
        controller.addRowButton({
            text: '刷新',
            onclick: function (id) {
                self.jqGrid.treegrid('reload', id);
            }
        });
    }


}
