// 标题 : 基于DataGrid的通用查询
// 版本号 : 1.0
// 最后一次更新时间 : 2013-08-07
// 描述 : 基于EasyUI的DataGrid通用查询JS脚本文件，代码生成时需要引用此JS文件


var count = 0;
var fieldUrl = "";
// 创建筛选控件
function CreateFilter(url) {
    var element = '<div class="title">筛选:</div> <form id="filter"><div> <input name="Field0" id="txtField0" style="width:120px" /><input name="Exp0" id="txtExp0" style="width:80px" /><div style="display: inline-block" id="divValue0"><input type="text" id="Value0" name="" onchange="txtChange(this)" /></div><input type="hidden" id="hidValue0" name="Value0" /><input name="Oper0" id="txtOper0" style="width:80px" /><a href="javascript:void(0)" onclick="removeExp(this)" id="remove0">删除</a></div></form><div class="searchbtn"><input type="button" value="追加条件" onclick="AppendExp();" /><input type="button" value="查询" onclick="SubmitExp();" /></div>'
    $("#filterBar").append(element);

    fieldUrl = url;

    BindData(count);
}


// 创建筛选表达式
function CreateExp(num) {
    var expElement = '<div> <input name="Field' + num + '" id="txtField' + num + '"  style="width:120px"/> <input name="Exp' + num + '" id="txtExp' + num + '"  style="width:80px"/> <div style="display: inline-block" id="divValue' + num + '"> <input type="text" id="Value' + num + '" name="" onchange="txtChange(this)"  /> </div> <input type="hidden" id="hidValue' + num + '" name="Value' + num + '" /> <input name="Oper' + num + '" id="txtOper' + num + '"  style="width:80px"/> <a href="javascript:void(0)" onclick="removeExp(this)" id="remove' + num + '">删除</a> </div>';
    $("#filter").append(expElement);
    BindData(num);
}

// 绑定数据
function BindData(num) {
    // 绑定数据字段
    $("#txtField" + num).combobox({
        valueField: 'ColumnName',
        textField: 'ColumnNoteText',
        url: fieldUrl,
        onSelect: function (e) {
            var type = e.ColumnTypeName;    // 数据类型
            var inputDiv = $("#divValue" + num);    // 输入元素所在层
            inputDiv.empty();   // 移除输入元素
            inputDiv.append('<input type="text" id="Value' + num + '" name="" onchange="txtChange(this)"  />'); // 追加输入元素
            var input = $("#Value" + num);  // 输入元素

            if (type == 'Int32') {
                // 数据类型为整形
                input.numberspinner({
                    editable: true,
                    required: true,
                    onSpinUp: function () {
                        var c = input.numberspinner('getValue');
                        $("#hidValue" + num).val(c);
                    },
                    onSpinDown: function () {
                        var c = input.numberspinner('getValue');
                        $("#hidValue" + num).val(c);
                    },
                });
            } else if (type == 'DateTime') {
                // 数据类型为日期类型
                input.datebox({
                    onSelect: function (e) {
                        var date = new Date(e);
                        var year = date.getFullYear();
                        var month = date.getMonth() + 1;
                        var day = date.getDate();
                        var c = this;
                        $(input).val(year + '-' + month + '-' + day);
                        $("#hidValue" + num).val(year + '-' + month + '-' + day);
                    }
                });
            } else if (type == 'Boolean') {
                // 数据类型为布尔型
                input.combobox({
                    valueField: 'id',
                    textField: 'text',
                    data: [{
                        "id": "True",
                        "text": "真"
                    }, {
                        "id": "False",
                        "text": "假"
                    }],
                    onSelect: function (e) {
                        $(input).val(e.id);
                        $("#hidValue" + num).val(e.id);
                    }
                });
            }
        }
    });

    // 绑定操作符
    $("#txtExp" + num).combobox({
        valueField: 'id',
        textField: 'text',
        data: [{
            "id": "Equals",
            "text": "等于"
        }, {
            "id": "NotEquals",
            "text": "不等于"
        }, {
            "id": "Like",
            "text": "包含",
        }, {
            "id": "NotLike",
            "text": "不包含"
        }, {
            "id": "GreaterThan",
            "text": "大于"
        }, {
            "id": "LessThan",
            "text": "小于"
        }, {
            "id": "GreaterThanEquals",
            "text": "大于等于"
        }, {
            "id": "LessThanEquals",
            "text": "小于等于"
        }, {
            "id": "IsNull",
            "text": "为空"
        }, {
            "id": "IsNotNull",
            "text": "非空"
        }],

        onSelect: function (e) {
            var a = this.id;
            a = a.match(/\d+/g);
            var valueText = "Value" + a;
            $("#" + valueText).attr('title', e.id);
            var hidValueText = "hidValue" + a;
            //if (e.id == 'like' || e.id == 'notlike') {
            //    $("#" + hidValueText).val('%' + $("#" + valueText).val() + '%');
            //} else {
            //    $("#" + hidValueText).val($("#" + valueText).val());
            //}

            if (e.id == 'IsNull' || e.id == 'IsNotNull') {
                $("#div" + valueText).hide();
                $("#" + hidValueText).attr('disabled', 'disabled');
            } else {
                $("#div" + valueText).show();
                $("#" + hidValueText).removeAttr('disabled');
            }

        }
    });

    // 绑定连接符
    $("#txtOper" + num).combobox({
        valueField: 'id',
        textField: 'text',
        data: [{
            "id": "and",
            "text": "而且"
        },
        {
            "id": "or",
            "text": "或者"
        }]
    });
}

// 验证表达式
function ValidateExp() {
    // 前3项不能为空
    // 1. Field
    var fieldArr = $('input[name*="Field"]');
    for (var i = 0; i < fieldArr.length; i++) {
        var item = fieldArr[i];
        if ($(item).val() == '') {
            return false;
        }
    }

    // 2. Exp
    var expArr = $('input[name*="Exp"]');
    for (var i = 0; i < expArr.length; i++) {
        var item = expArr[i];
        if ($(item).val() == '') {
            return false;
        }
    }
    // 3. Value
    var valueArr = $('input[name*="Value"]');
    for (var i = 0; i < valueArr.length; i++) {
        var item = valueArr[i];
        if ($(item).val() == '' || $(item).val() == '%%') {
            var dis = $(item).attr("disabled");
            return dis;
        }
    }
    return true;
}


// 追加表达式
function AppendExp() {
    var filterDiv = $("#filter");
    filterDiv.height("auto");
    filterDiv.css("overflow", "visible");
    count++;
    CreateExp(count);
}

// 提交表达式
function SubmitExp() {

    // 提交之前验证表单元素的值
    if (!ValidateExp()) {
        alert('表达式中 "字段", "操作符", "值" 必填 否则请删除该条件');
        return false;
    }

    var filterDiv = $("#filter");
    filterDiv.height("33px");
    filterDiv.css("overflow", "hidden");

    var where = ' and ';
    var str = $("#filter").serialize();
    filterDiv.children().remove();
    count = 0;
    CreateExp(count);

    str = decodeURIComponent(str);

    str = str.replace('isNull', ' is null ');
    str = str.replace('isNotNull', ' is not null ');
    str = str.replace('notlike', ' not like ');

    var arr = str.split('&');

    var where = "";
    var itemWhere = "";
    var count = 0;
    for (var i = 0; i < arr.length; i++) {
        var property = arr[i];
        var propertyArr = property.split('=');
        var field = propertyArr[0];
        field = field.substr(0, field.length - 1);
        field = field.replace("Field", "ColumnName");
        field = field.replace("Exp", "QueryCondition");
        field = field.replace("Value", "ColumnValue");
        field = field.replace("Oper", "QueryConnector");
        var value = propertyArr[1];
        if (value == '') {
            value = "none";
        }
        var jsonObjItem = '"' + field + '":"' + value + '"';
        itemWhere += jsonObjItem + ',';
        if (count == 3) {
            where += '{' + itemWhere.substr(0, itemWhere.length - 1) + '},';
            count = -1;
            itemWhere = "";
        }

        count++;
    }
    where = '[' + where.substr(0, where.length - 1) + ']';

    $("#grid1").datagrid("reload", { "ConditionExpression": where });
    var pager = $('#grid1').datagrid("getPager");
    $(pager).pagination({
        onSelectPage: function (pageNumber, pageSize) {
            $('#grid1').datagrid('reload', { PageIndex: pageNumber, PageSize: pageSize, "ConditionExpression": where });
        }
    });
}

// 值字段改变
function txtChange(e) {
    var title = $(e).attr('title');
    var num = e.id.substr(e.id.length - 1, 1);
    if (title == 'like' || title == 'notlike') {
        $('#hidValue' + num).val('%' + $(e).val() + '%');
    } else {
        $('#hidValue' + num).val($(e).val());
    }
}

// 移除表达式
function removeExp(e) {
    var divCount = $(e).parent().parent().children().length;
    if (divCount <= 1) {
        return;
    } else {
        $(e).parent().remove();
    }
}
