function DBReader()
{

}
/*当前数据库类型*/
DBReader.CurrentDataType="access";
/*数据库类型*/
DBReader.DataType={
    access:"access",
    sql:"sql"
};
/*清空实体字段值*/
DBReader.clearEntity=function(_entity)
{
    for(var p in _entity.Fields)
    {
        _entity.Fields[p]=null;
    }
}
/*销毁实体*/
DBReader.DisposeEntity=function(_entity)
{
    for(var p in _entity.Fields)
    {
        _entity.Fields[p]=null;
    }
/*    _entity.ItemEntityFieldXML="";
     for(var p in _entity)
//    {
//        p=null;
//    }
//    _entity=null;
*/
     _entity=null;
    CollectGarbage();
}
/*解析实体*/
DBReader.resolution=function(_entity)
{    
	var ColumnsAttribute=new Array();
    for(var p in _entity.ColumnsAttribute)
    {
        ColumnsAttribute.push(_entity.ColumnsAttribute[p]);
    }
	var FieldsSet=new Array();
    for(var p in _entity.Fields)
    {
        FieldsSet.push(_entity.Fields[p]);
    }
    _entity.FieldsSet=FieldsSet;
    _entity.ColumnsSet=ColumnsAttribute;
};
/*解析xml*/
DBReader.resolutionEntityXML=function(_entity)
{
    try
    {
        var strFieldXML=new StringBuffer();
        strFieldXML.appendLine('<?xml version=\"1.0\" encoding=\"gb2312\" ?>');
        var KeyField="ID";
        if(typeof(_entity.KeyField)!="undefined" && _entity.KeyField!="" && _entity.KeyField!="undefined")
        {
            KeyField=_entity.KeyField;
        }
        strFieldXML.appendLine('<DataTable id="'+_entity.TableName+'" KeyField="'+KeyField+'"><row>');
        
        for(var i=0;i<_entity.ColumnsSet.length;i++)
        {
            var fields=_entity.ColumnsSet[i].split(App.Config.split);
            if(_entity.Fields[fields[0]]!=null)
            {
                strFieldXML.appendLine('<'+fields[0]+' DataType="'+fields[1]+'"');
                if(fields[2]=="column")
                {
                    strFieldXML.appendLine(' iscolumn="true"');
                }
                else
                {
                    strFieldXML.appendLine(' iscolumn="false"');
                }
                strFieldXML.appendLine('>'+_entity.Fields[fields[0]]+'</'+fields[0]+'>');
            }
        }
        strFieldXML.appendLine('</row></DataTable>');
        _entity.FieldXML=strFieldXML.toString();
        strFieldXML=null;
        KeyField=null;
    }
    catch(e)
    {
        alert("RXML"+e.message);
    }
    CollectGarbage();
};
/*实体ID集合*/
DBReader.IDGroup="";
/*解析子实体xml*/
DBReader.resolutionItemEntityXML=function (_entity,_Index,_strMainTableName,_Action)
{
    var strFieldXML=new StringBuffer();
    var KeyField="ID";
    if(_entity!=null && _entity.KeyField!=null && _entity.KeyField!=undefined && _entity.KeyField!="" && _entity.KeyField!="undefined")
    {
        KeyField=_entity.KeyField;
    }
    strFieldXML.appendLine('<ItemDataTable id="'+_entity.TableName+'" index="'+_Index+'" action="'+_Action+'" KeyField="'+KeyField+'"><row>');
    
    for(var i=0;i<_entity.ColumnsSet.length;i++)
    {
        var fields=_entity.ColumnsSet[i].split(App.Config.split);
        if(_Action!="update" || _entity.Fields[fields[0]]!=null)
        {
            strFieldXML.appendLine('<'+fields[0]+' DataType="'+fields[1]+'"');
            if(fields[2]=="column")
            {
                strFieldXML.appendLine(' iscolumn="true"');
            }
            else
            {
                strFieldXML.appendLine(' iscolumn="false"');
            }
            strFieldXML.appendLine('>'+_entity.Fields[fields[0]]+'</'+fields[0]+'>');
        }
    }
    for(var p in _entity.LinkFields)
    {
        var fields=_entity.LinkFields[p].split(App.Config.split);
        if(fields[0]==_strMainTableName)
        {
            strFieldXML.appendLine('<LinkField Field="'+p+'" LinkTable="'+_strMainTableName+'" LinkColumn="'+fields[1]+'">-1</LinkField>');
            break;
        }
    }
    strFieldXML.appendLine('</row></ItemDataTable>');
    return strFieldXML.toString();
}
/*组织实体查询条件值XML*/
DBReader.getWhereValueXML=function(_entity){
    var strWhereValueXML=new StringBuffer();
    strWhereValueXML.appendLine('<?xml version=\"1.0\" encoding=\"gb2312\" ?>');
    strWhereValueXML.appendLine('<WhereValueSet id="'+_entity.TableName+'"><row>');
    
    for(var i=0;i<_entity.WhereValue.length;i++)
    {
        var fields=_entity.WhereValue[i].split(':');
        if(fields[1].indexOf('\'')!=-1)
        {
            strWhereValueXML.appendLine('<'+fields[0]+' ValueType="ftString">'+fields[1]+'</'+fields[0]+'>');
        }
        else
        {
            strWhereValueXML.appendLine('<'+fields[0]+' ValueType="object">'+fields[1]+'</'+fields[0]+'>'); 
        } 
    }
    strWhereValueXML.appendLine('</row></WhereValueSet>');
    
    _entity.WhereValueXML=strWhereValueXML.toString();
    strWhereValueXML.clear();
};
/*执行指定SQL语句*/
DBReader.execSql=function(SqlString){
    return  window.external.execSql(SqlString);
};
/*获取数据表*/
DBReader.getTable=function(_entity){
    /*DBReader.resolution(_entity);*/
    getWhereValueXML(_entity);
    return  window.external.DataHelper_getTable(_entity);
};
/*查询实体*/
DBReader.SelectOne=function(_entity){
    /*DBReader.resolution(_entity);*/
    DBReader.getWhereValueXML(_entity);
    return window.external.DataHelper_select(_entity);
};
/*查询实体集合*/
DBReader.SelectList=function(_entity){
/*    DBReader.resolution(_entity);*/
    getWhereValueXML(_entity);
   return window.external.DataHelper_select(_entity);
};
/*查询数据*/
DBReader.selectSql=function(Sql,TableName){
    return window.external.DataHelper_selectSql(Sql,TableName);
};
/*查询数据*/
DBReader.selectSqlForJson=function(Sql){
    return window.external.DataHelper_selectJson(Sql);
};
/*获取实体XML*/
DBReader.getEntityXML=function(_entity)
{ 
/*    DBReader.resolution(_entity);*/
    DBReader.resolutionEntityXML(_entity);
    _entity.ItemEntityFieldXML="<?xml version=\"1.0\" encoding=\"gb2312\" ?><ItemEntityList>"+_entity.ItemEntityFieldXML+"</ItemEntityList>";
};
/*释放数据集资源*/
DBReader.Dispose=function(_dataObj){
    try
    {
        if(_dataObj!=null)
        {
            window.external.DataHelper_Dispose(_dataObj);
            _dataObj=null;
        }
    }
    catch(e)
    {
        _dataObj=null;
    }
    CollectGarbage();
};
/*判断数据集是否为空*/
DBReader.DObjectIsNull=function(drObj)
{
    var blIsOK=true;
    if(drObj==null || typeof(drObj)!="object" || drObj==undefined)/* || drObj.ActiveConnection==null || drObj.ActiveConnection==undefined)*//*远程连接的情况下连接对象为空*/
    {
        blIsOK=true;
    }
    else
    {
        blIsOK=false;
    }
    return blIsOK;
};
/*新增实体*/
DBReader.Insert=function(_entity){
    DBReader.IDGroup="";
    DBReader.getEntityXML(_entity);
    var IsOK=window.external.DataHelper_insert(_entity,DBReader);
    DBReader.UpdateEntityFieldXML(_entity);
    DBReader.UpdateItemEntityFieldXML(_entity);
/*    _entity.ItemEntityFieldXML="";*/
    return IsOK;
};
/*更新实体*/
DBReader.Update=function(_entity){
    DBReader.IDGroup="";
    DBReader.getEntityXML(_entity);
    var IsOK= window.external.DataHelper_update(_entity,DBReader);
    DBReader.UpdateEntityFieldXML(_entity);
    DBReader.UpdateItemEntityFieldXML(_entity);
    /*_entity.ItemEntityFieldXML="";*/
    return IsOK;
};
/*删除实体*/
DBReader.Delete=function(_entity){
    DBReader.IDGroup="";
    DBReader.getEntityXML(_entity);
    var IsOK= window.external.DataHelper_delete(_entity,DBReader);
    DBReader.UpdateEntityFieldXML(_entity);
    DBReader.UpdateItemEntityFieldXML(_entity);
    _entity.ItemEntityFieldXML="";
    return IsOK;
};
/*更新实体原来的字段XML值——写入最新的ID值*/
DBReader.UpdateEntityFieldXML = function(_entity) {
    if (DBReader.IDGroup != "") {
        var IDGroupValue = DBReader.IDGroup.split('|');
        var KeyField='ID';
        if(_entity!=null && _entity.KeyField!=null && _entity.KeyField!="" && _entity.KeyField!="undefined")
        {
            KeyField=_entity.KeyField;
        }
        var MainID = 0;
        for (i = 0; i < IDGroupValue.length; i++) {
            if (IDGroupValue[i] != '') {
                var TempeValue = IDGroupValue[i].split('*');
                if (TempeValue[2] == '-1') {
                    MainID = TempeValue[1];
                    try {
                        eval('_entity.Fields.'+KeyField+' = MainID');
                    }
                    catch (e) {

                    }
                    break;
                }
            }
        }

        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(_entity.FieldXML);
        var xmlRows = xmlDoc.selectSingleNode("DataTable").childNodes[0].childNodes;
        var xmlRow = null;
        if (xmlRows != null) {
            for (var i = 0; i < xmlRows.length; i++) {
                if (xmlRows[i].nodeName.toUpperCase() == KeyField.toUpperCase()) {
                    xmlRows[i].text = MainID;
                    break;
                }
            }
        }
        _entity.FieldXML = xmlDoc.xml;
    }
};
/*更新实体原来的明细表字段XML值——写入最新的ID值*/
DBReader.UpdateItemEntityFieldXML=function(_entity)
{
    if(DBReader.IDGroup!="")
    {
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(_entity.ItemEntityFieldXML);
        var xmlRows=xmlDoc.selectSingleNode("ItemEntityList").childNodes;
        var IDGroupValue=DBReader.IDGroup.split('|');
        var KeyField='ID';
        for(i=0;i<IDGroupValue.length;i++)
        {
            if(IDGroupValue[i]!='')
            {
                var TempeValue=IDGroupValue[i].split('*');
                var ItemTableName = TempeValue[0];
                var ItemEntityID = TempeValue[1];
                var ItemIndex=TempeValue[2];
                
                var xmlRow=null;
                if(xmlRows!=null)
                {
                    for(var n=0;n<xmlRows.length;n++)
                    {
                        if(xmlRows[n].getAttribute("index")==ItemIndex && xmlRows[n].getAttribute("id")==ItemTableName)
                        {
                            if(xmlRows[n].getAttribute("KeyField")!=null && xmlRows[n].getAttribute("KeyField")!="" && xmlRows[n].getAttribute("KeyField")!="undefined")
                            {
                                KeyField=xmlRows[n].getAttribute("KeyField");
                            }
                            var RowNode=xmlRows[n].childNodes[0];
                            for(var j=0;j<RowNode.childNodes.length;j++)
                            {
                                if(RowNode.childNodes[j].nodeName.toUpperCase()==KeyField.toUpperCase())
                                {
                                    RowNode.childNodes[j].text=ItemEntityID;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        _entity.ItemEntityFieldXML=xmlDoc.xml;
    }
};
/*获取指定明细实体键值*/
DBReader.setItemEntityKeyFieldValue=function(_entity,_ItemEntity)
{
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(_entity.ItemEntityFieldXML);
        var xmlRows=xmlDoc.selectSingleNode("ItemEntityList").childNodes;
        
        var xmlRow=null;
        if(xmlRows!=null)
        {
            for(var n=0;n<xmlRows.length;n++)
            {
                var isGetValue=false;
                if(xmlRows[n].getAttribute("id")==_ItemEntity.TableName)
                {
                    var RowNode=xmlRows[n].childNodes[0];
                    for(var j=0;j<RowNode.childNodes.length;j++)
                    {
                        if(RowNode.childNodes[j].nodeName.toUpperCase()==_ItemEntity.KeyField.toUpperCase())
                        {
                            eval("_ItemEntity.Fields."+_ItemEntity.KeyField+"=RowNode.childNodes[j].text;");
                            isGetValue=true;
                            break;
                        }
                    }
                }
                if(isGetValue==true)
                {
                    break;
                }
            }
        }
};
/*获取查询语句分页模式*/
DBReader.GetJsonPagerListString=function(txtSql,conditon,OrderString,KeyFieldString,pagesize,pageindex,flag)
{
    var selectSql=txtSql;/*.toUpperCase();*/
    var tmpArr=selectSql.split('SELECT');
    var SelectField=tmpArr[1];
    tmpArr=SelectField.split('FROM');
    SelectField=tmpArr[0];
    var SelectTable=tmpArr[1];
    /*
//    tmpArr=SelectTable.split('WHERE');
//    var strCondition="";
//    var arrLen=tmpArr.length;
//    if(tmpArr.length>1)
//    {
//        strCondition=tmpArr[tmpArr.length-1];
//        arrLen=arrLen-2;
//    }
//    for(var i=0;i<arrLen;i++)
//    {
//        SelectTable+=tmpArr[i];
//    }
//    alert(SelectField);
//    alert(strCondition);
//    alert(SelectTable);
*/
    tmpArr=OrderString.split(',');
    var lastOrdertype="";
    var arrLen=tmpArr.length;
    var OrderStringValue="";
    if(tmpArr.length>1)
    {
        lastOrdertype=tmpArr[tmpArr.length-1];
        arrLen=arrLen-1;
        for(var i=0;i<arrLen;i++)
        {
            OrderStringValue+=tmpArr[i];
        }
        OrderStringValue+=",";
    }
    else
    {
        lastOrdertype=tmpArr[0];
    }
    lastOrdertype=lastOrdertype.toUpperCase();
    OrderStringValue+=lastOrdertype.replace("DESC","").replace("ASC","");
    
    var orderType=0;
    if(lastOrdertype.indexOf('DESC')!=-1)
    {
        orderType=1;
    }
    
    var execSqlstr="exec eOA_CMB_GetPagerData '"+SelectTable+"','"+SelectField+"',"+pagesize+","+pageindex+",'"+KeyFieldString+"','"+conditon+"','"+OrderStringValue+"',"+orderType;
    
    var obj = DBReader.selectSql(execSqlstr, 'eOA_CMB_GetPagerData'); 
    if (obj == null || obj == undefined)
        return '[{"result" :"2","returnval" :"连接数据库失败！"}]';
    var rowCount = parseInt(obj.RecordCount);
    if (rowCount == 0) {
        DBReader.Dispose(obj);
        return '[{"result" :"0","returnval" :"暂时没有结果"}]';
    }
    var result = new StringBuffer();
    var fieldsCount = parseInt(obj.Fields.Count);
    
    result.appendLine('[{"result" :"1","returnval" :"操作成功", "pageIndex":"' + pageindex + '", "recordcount":"' + rowCount + '","table":[');
    obj.MoveFirst();
    for (var i = 0; i < rowCount; i++) {
        if (i != 0)
            result.appendLine(',');
        result.appendLine('{');
        for (n = 0; n < fieldsCount; n++) {
            if (n !== 0)
                result.appendLine(",");
            if (obj.Fields(n).Type == 135) {
                if (obj.Fields(n).Value == "" || obj.Fields(n).Value == null || obj.Fields(n).Value == undefined)
                    result.appendLine('"' + obj.Fields(n).Name.replace(/'"'/g, "'") + '"' + ':"null"');
                else {
                    var dt = new Date(obj.Fields(n).Value);
                    if (flag) {
                        result.appendLine('"' + obj.Fields(n).Name + '"' + ':"' + dt + '"');
                    }
                    else {
                        result.appendLine('"' + obj.Fields(n).Name + '"' + ':"' + dt.Format("yyyy-MM-dd hh:mm:ss") + '"');
                    }
                }
            }
            else {
                result.appendLine('"' + obj.Fields(n).Name + '"' + ':"' + obj.Fields(n).Value + '"');
            }
        }
        result.appendLine('}')
        obj.MoveNext();
    }
    result.appendLine(']}]');
    DBReader.Dispose(obj);
    return result.toString();
};
/*获取列表分页对象
执行sql返回数据列表的json
*/
DBReader.GetListJsonDataForPager=function(txtSql,tableName,pageCount) 
{
    var obj = DBReader.selectSql(txtSql, tableName);
    var result = new StringBuffer();
    if (DBReader.DObjectIsNull(obj))
    {
        DBReader.Dispose(obj);
        result.appendLine('[{"result" :"2","returnval" :"连接数据库失败！"}]');
    }
    else
    {
        var rowCount = parseInt(obj.RecordCount);
        if (rowCount == 0) 
        {
            DBReader.Dispose(obj);
            result.appendLine('[{"result" :"0","returnval" :"暂时没有结果"}]');
        }
        else
        {
            var fieldsCount = parseInt(obj.Fields.Count);
            result.appendLine('[{"result" :"1","returnval" :"操作成功", "pageIndex":"' + pageCount + '", "recordcount":"' + rowCount + '","table":[');
            obj.MoveFirst();
            for (var i = 0; i < rowCount; i++) 
            {
                if (i != 0)
                {
                    result.appendLine(',');
                }
                result.appendLine('{');
                for (n = 0; n < fieldsCount; n++) 
                {
                    if (n !== 0)
                    {
                        result.appendLine(",");
                    }
                    if (obj.Fields(n).Type == 135) 
                    {
                        /*处理时间值*/
                        if (obj.Fields(n).Value == "" || obj.Fields(n).Value == null || obj.Fields(n).Value == undefined)
                        {
                            result.appendLine('"' + obj.Fields(n).Name.replace(/'"'/g, "'") + '"' + ':""');
                        }
                        else 
                        {
                            var dt = new Date(obj.Fields(n).Value);                            
                            result.appendLine('"' + obj.Fields(n).Name + '"' + ':"' + dt.Format("yyyy-MM-dd") + '"');
                            dt=null;
                        }
                    }
                    else 
                    {
                        if (obj.Fields(n).Value == null)
                        {
                            result.appendLine('"' + obj.Fields(n).Name.replace(/'"'/g, "'") + '"' + ':""');
                        }
                        else
                        {
                        
/*                            if(obj.Fields(n).Name=="FName" || obj.Fields(n).Name=="Content")*/
/*                            {*/
                                result.appendLine('"' + obj.Fields(n).Name + '"' + ':"' + unescape(obj.Fields(n).Value) + '"');
/*                            }*/
/*                            else*/
/*                            {*/
/*                                result.appendLine('"' + obj.Fields(n).Name + '"' + ':"' + strToString(obj.Fields(n).Value.toString().replace(/\\/g,"\\\\")) + '"');*/                                
/*                            }*/
                        }
                    }
                }
                result.appendLine('}')
                obj.MoveNext();
            }
            result.appendLine(']}]');
            fieldsCount=null;
            DBReader.Dispose(obj);
        }
    }
    CollectGarbage();
    return result.toString();
}
/*获取服务器时间*/
DBReader.ServerTime=function()
{
    var strServerTime=null;
    if(DBReader.CurrentDataType==DBReader.DataType.sql)
    {
        /*sql获取服务器器时间*/
        var getServerTimeSql="declare @date as datetime;set @date=getdate();select year(@date) as _year,month(@date) as _month,day(@date) as _day,CONVERT(varchar(12) , @date, 108 ) as _Time,CONVERT(varchar(20) , @date, 120 ) as _FullTime";
        var dataObj=null;
        try
        {
            dataObj=DBReader.selectSql(getServerTimeSql,"Temp");
            if(DBReader.DObjectIsNull(dataObj)==false)
            {
                var strFullTime=dataObj.Fields("_FullTime").value;
                var dt=new Date(Date.parse(strFullTime.replace(/-/g,"/")));
                strServerTime=dt;/*.Format("yyyy-MM-dd hh:mm:ss");*/
                dt=null;
                strFullTime=null;
            }
        }
        catch(e)
        {
            /*alert(e.message);*/
        }
        DBReader.Dispose(dataObj);
    }
    else if(DBReader.CurrentDataType==DBReader.DataType.access)
    {
        /*access获取服务器时间*/
        var getServerTimeSql="SELECT now() as _Time";
        var dataObj=null;
        try
        {
            var strJson=DBReader.selectSqlForJson(getServerTimeSql);
            if(strJson!=null)
            {
                dataObj=eval("[{"+strJson+"}]");
                if(dataObj[0].result=="1")
                {
                    var strFullTime=dataObj[0].table[0]._Time;
                    var dt=new Date(Date.parse(strFullTime.replace(/-/g,"/")));
                    strServerTime=dt;/*.Format("yyyy-MM-dd hh:mm:ss");*/
                    dt=null;
                    strFullTime=null;
                }
            }
            strJson=null;
        }
        catch(e)
        {
            /*alert(e.message);*/
        }
        getServerTimeSql=null;
        dataObj=null;
    }
    CollectGarbage();
    return strServerTime;
};
/*从json数据中获取指定字段的值，该json数据的数据个数只有一行数据*/
DBReader.getFieldValueFromJsonData=function(dataObj,FieldName,curID)
{
    var fieldValue=null;
    try
    {
            var RowObj;
            if(curID!=undefined && curID!="")
            {
                 RowObj=dataObj[0].table[curID];
            }
            else
            {
                RowObj=dataObj[0].table[0];
            }
            eval("fieldValue=RowObj."+FieldName+";");
    }
    catch(e)
    {
        alert(e.message);
    }
    CollectGarbage();
    return fieldValue;
};
/*ftp主目录*/
DBReader.ftpPath=function()
{
    var ftpPathValue="";
    var dataObj=null;
    try
    {
        var strSql="exec eOA_Sys_Select 'T_MYINFO','INFOTXT','AND INFOTYPE=''FTPPath'''";
        dataObj=DBReader.selectSql(strSql,"SelectData");
        if(DBReader.DObjectIsNull(dataObj)==false)
        {
            if(dataObj.RecordCount>0)
            {
                ftpPathValue=dataObj.Fields("INFOTXT").value;
            }
        }
        strSql=null;
    }
    catch(e)
    {
        
    }
    DBReader.Dispose(dataObj);
    CollectGarbage();
    return ftpPathValue;
}
/*格式化服务器时间，只适合格式化服务器时间*/
Date.prototype.ServerFormat = function(format) {
    var o = {
        "M+": this.getMonth()+1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "w": "0123456".indexOf(this.getDay()),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
          RegExp.$1.length == 1 ? o[k] :
            ("00" + o[k]).substr(("" + o[k]).length));
    }
    return format;
};