package zr.zrpower.ejb.sys;

import zr.zrpower.common.util.*;
import zr.zrpower.common.db.*;
import zr.zrpower.entity.sys.BPIP_USER;
import zr.zrpower.entity.sys.BPIP_USER_PHOTO;
import zr.zrpower.entity.sys.SessionUser;
import java.util.ArrayList;

/**
  * <p> public FunctionMessage  AddUser(BPIP_USER mUser)             //保存添加新用户</p>
  * <p> public boolean  DeleteUser(String userID)                    //删除用户</p>
  * <p> public FunctionMessage  EditUser(BPIP_USER mUser)            //修改用户</p>
  * <p> public BPIP_USER  GetUserInfo(String userID)                 //获取用户的详细信息（除密码以外）</p>
  *  <p> public BPIP_USER[]  GetUserList(String UNITID)         //获取用户列表</p>
  *  <p>public FunctionMessage  Login(String loginID, String pw, String IP)//用户登录</p>
  *  <p>public boolean  StopUser(String userID)                      //用户停用 </p>
  *  <p> public boolean  unStopUser(String userID)                   //解除用户停用</p>
  *  <p> public boolean  ResetPassword(String userID, String pw)     //重设密码</p>
  *  <p> public String GetUserLoginID(String userID)                 //获取用户登录名</p>
  *  <p> public boolean  CheckPw(String strUserID, String strPw)     //检查用户口令</p>
  *  <p> public String GetUserUNITID(String userID)                  //获取用户所在单位编号</p>
  *  <p> public String GetUserUNITName(String userID)                //获取用户所在单位名称</p>
  *  <p> public String GetUserName(String userID)                    //获取用户真实姓名</p>
  *  <p> public byte[] GetUserPhoto(String userID)                   //获取用户照片</p>
  *  <p> public byte[] GetUserSelfFace(String userID)                //获取用户自定义头像</p>
  *  <p> public byte[] GetUserIdiograph(String userID)               //获取用户签名</p>
  *  <p> public String[][] GetUserArrary(String DepID)</p>
  *  <p> public String GetUserTypeImg(String sType,String Path)      //获取用户类型图片</p>
  *  <p> public String GetUserState(String sType)                    //获取用户状态</p>
  *  <p> public boolean  ChangeAppCon(String userID,int PageSize,String WindowType)//更改应用配置 </p>
  *  <p> public BPIP_USER[]  GetDeptUserList(String strUnit)         //根据部门编号得到某部门的列表</p>
  *  <p> public String GetShowUnitUserList(String strUnitID,String strListName,String strUserimage,String ico,String strtype)//根据单位编号生成单位下的用户列表
*/
public class UserService
  {
  public zr.zrpower.common.util.SysPreperty ObjSysPreperty = new zr.zrpower.common.util.SysPreperty();
  String DataBaseType = ObjSysPreperty.getProperty().DataBaseType;//数据库类型
  static private Log log;
  dbEngine dbengine;
  static private int clients=0;

  public UserService()
  {
    dbengine = new dbEngine(SysPreperty.getProperty().MainDataSource,SysPreperty.getProperty().IsConvert);
    dbengine.initialize();
    if (clients<1)
    {
      log = new Log();
      log.SetLogForClass("UserServicesBean");
      log.SetLogFile("UserEjb.log");
    }
    clients++;
  }


  //============================================================================
  //保存添加新用户
  //传入参数：UserInfo mUser  用户实体类
  //  返回值：boolean  保存是否成功
  //============================================================================
  public String  AddUser(BPIP_USER mUser) {
    StringWork mString = new StringWork();
    String Rvalue = "";

     try {
      //如果传入的用户实体不为空，构建新数据行，提交给数据库控制类执行插入数据库操作。
      if (mUser != null) {
        String  strSQL = "";

        strSQL = "Select UserID From BPIP_USER Where LoginID='" +
            mUser.getLOGINID()+ "'";
        dbSet mdbset = dbengine.QuerySQL(strSQL);
        if ((mdbset != null)||mUser.getLOGINID().equals("pip")) {
          mdbset = null;
        }
        else {
          strSQL = "Select Max(UserID) as maxid From BPIP_USER Where UserID like '"+mUser.getUNITID()+"%'";
          dbSet mdbset1 = dbengine.QuerySQL(strSQL);
          String userid = mUser.getUNITID()+"0001";


          if (mdbset1 != null) {
            if (mdbset1.RowCount() > 0) {
              if(mdbset1.Row(0).Column("maxid").getString().length()==16){
                 userid = mUser.getUNITID()+ mString.NewID(mdbset1.Row(0).Column("maxid").getString().substring(12));
              }
            }
            mdbset1 = null;
          }


         mUser.setPAGESIZE(18);
         mUser.setWINDOWTYPE("1");

         mUser.setLOGINTIME(0);
         mUser.setLOGINPW(MD5.toMD5(mUser.getLOGINPW()));
         mUser.setUSERSTATE("0");
         mUser.setUSERID(userid);


         dbRow[] dbUser;
         if(mUser.getUserPhoto()!=null){
            BPIP_USER_PHOTO mUserPhoto = mUser.getUserPhoto();
            mUserPhoto.setUSERID(userid);
            dbUser = new dbRow[2];
            dbUser[0] = mUser.getData();
            dbUser[1] = mUserPhoto.getData();
            dbUser[0].setDataMode(dbMode.NEW);
            dbUser[1].setDataMode(dbMode.NEW);
         }else{
            dbUser = new dbRow[1];
            dbUser[0] = mUser.getData();
            dbUser[0].setDataMode(dbMode.NEW);
         }

          if (dbengine.UpdateAll(dbUser)) {
            Rvalue = userid;
          }
        }

      }

    }
    catch (Exception ex) {
      log.WriteErrorLog("AddUser", ex.toString());
    }

    return Rvalue;
  }

  //删除用户
  public boolean  DeleteUser(String userID) {
    boolean returnValue = false; //定义返回值
    try {
      if (userID != null) {
        String[] strSQL = new String[3];
        strSQL[0] = "delete from BPIP_USER  Where UserID='"+userID+"'";
        strSQL[1] = "delete from BPIP_USER_PHOTO  Where UserID='"+userID+"'";
        strSQL[2] = "delete from BPIP_USER_REMOVE  Where UserID='"+userID+"'";
        returnValue = dbengine.ExecuteSQLs(strSQL);
      }
    }
    catch (Exception ex) {
      log.WriteErrorLog("DeleteUser", ex.toString());
    }

    return returnValue;
  }

  //编辑用户
  public FunctionMessage  EditUser(BPIP_USER mUser) {
    FunctionMessage fm = new FunctionMessage(1);
     String strSQL = "";
    //没有照片记录插入
    strSQL = "Select USERID From BPIP_USER_PHOTO Where UserID = '"+mUser.getUSERID()+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);

    if(dbset==null){
          strSQL = "Insert into BPIP_USER_PHOTO(USERID) values('"+mUser.getUSERID()+"')";
          dbengine.ExecuteSQL(strSQL);
    }
    //

    try {
      //如果传入的用户实体不为空，构建新数据行，提交给数据库控制类执行更新数据库操作。
      if (mUser != null) {
        strSQL = "Select UserID From BPIP_USER Where LoginID='"+
            mUser.getLOGINID() + "' and UserID<>'" + mUser.getUSERID()+ "'";
        dbSet mdbset = dbengine.QuerySQL(strSQL);
        if (mdbset != null) {
          fm.setMessage("已有用户使用【" + mUser.getLOGINID() + "】这个登录名了，请另用一个新登录名！");
          mdbset = null;
        }
        else {
          if(mUser.getLOGINPW()!=null){
             if(mUser.getLOGINPW()!=""){
                mUser.setLOGINPW(MD5.toMD5(mUser.getLOGINPW()));
             }
          }

          dbRow[] dbUser;
          if(mUser.getUserPhoto()!=null){
            BPIP_USER_PHOTO mUserPhoto = mUser.getUserPhoto();
            mUserPhoto.setUSERID(mUser.getUSERID());
            dbUser = new dbRow[2];
            dbUser[0] = mUser.getData();
            dbUser[1] = mUserPhoto.getData();
            dbUser[0].setDataMode(dbMode.EDITED);
            dbUser[1].setDataMode(dbMode.EDITED);
         }else{
            dbUser = new dbRow[1];
            dbUser[0] = mUser.getData();
            dbUser[0].setDataMode(dbMode.EDITED);
         }

          if (dbengine.UpdateAll(dbUser,null,null)) {
            fm.setResult(true);
            fm.setMessage(FunctionMessage.MSG_SUCCEED_SAVE);
          }
          else {
             fm.setMessage(FunctionMessage.MSG_ERROR_DATASERVER);
          }

        }

      }
      else {
        fm.setMessage(FunctionMessage.MSG_NOT_SAVE_DATA);
      }
    }
    catch (Exception ex) {
      log.WriteErrorLog("EditUser", ex.toString());
    }

    return fm;
  }

  //获取用户的详细信息（除密码以外）
  public BPIP_USER  GetUserInfo(String userID) {
    BPIP_USER returnValue = null;
    String  strSQL= "";
    strSQL = "Select * From BPIP_USER Where UserID = '"+userID+ "'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        returnValue = new BPIP_USER();
        returnValue.fullData(dbset.Row(0));
      }
      dbset = null;
    }
    return returnValue;
  }

  public String[][] GetUserArrary(String DepID){
    String[][] resultValue = null;
    String  strSQL= "";
    strSQL = "Select UserID,Name From BPIP_USER Where UserState='0'  And UNITID ='"+DepID+ "' Order By ORBERCODE,UserID";
    dbSet set = dbengine.QuerySQL(strSQL);
    if (set != null) {
      if (set.RowCount() > 0) {
        resultValue = new String[set.RowCount()][2];
        for (int i = 0; i < set.RowCount(); i++) {

          resultValue[i][0] = set.Row(i).Column("UserID").getString();
          resultValue[i][1] = set.Row(i).Column("Name").getString();

        }
      }
      set = null;
    }
    return resultValue;
  }

  //获取用户列表
  //传入参数：单位编号
  public BPIP_USER[]  GetUserList(String UNITID) {
    BPIP_USER[] returnValue = null;
    String strSQL = "";
    if (UNITID.length()==0)
    {
      strSQL = "Select * From BPIP_USER where UNITID in (select min(UNITID) from BPIP_UNIT) Order By ORBERCODE,UserID";
    }
    else
    {
      strSQL = "Select * From BPIP_USER where UNITID='"+UNITID+"' Order By ORBERCODE,UserID";
    }
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        returnValue = new BPIP_USER[dbset.RowCount()];
        for (int i = 0; i < dbset.RowCount(); i++) {
          returnValue[i] = new BPIP_USER();
          returnValue[i].fullData(dbset.Row(i));
        }
      }
      dbset = null;
    }
    return returnValue;
  }

  //获取某部门的用户列表
  //传入参数：strUnit   单位编号
   public BPIP_USER[]  GetDeptUserList(String strUnit){
     BPIP_USER[] returnValue = null;
     String  strSQL= "";
     strSQL = "Select * From BPIP_USER where UNITID ='"+strUnit+"' Order By ORBERCODE,UserID";
     dbSet dbset = dbengine.QuerySQL(strSQL);
     if (dbset != null) {
       if (dbset.RowCount() > 0) {
         returnValue = new BPIP_USER[dbset.RowCount()];
         for (int i = 0; i < dbset.RowCount(); i++) {
           returnValue[i] = new BPIP_USER();
           returnValue[i].fullData(dbset.Row(i));
         }
       }
       dbset = null;
     }
     return returnValue;
   }

  //用户登录
  public FunctionMessage  Login(String loginID, String pw) {
    FunctionMessage fm = new FunctionMessage();       //定义返回值
    dbSet dbset = null;                               //定义数据库返回数据集
    fm.setResult(false);
    fm.setMessage("发生异常，请与管理员联系！");
    String   strSQL= "";

    try {
      //检查是否系统内建帐号PIP
      if (loginID.equals("pip")) {

        if (!pw.equals("pip"))
        {
          fm.setResult(false);
          fm.setMessage("用户密码错误，请重新登录！");
        }
        else {
          SessionUser su = new SessionUser();
          su.setName("系统内建用户");
          su.setLCODE("000000");

          su.setUnitID(dbset.Row(0).Column("UNITID").getString());
          su.setUnitName(dbset.Row(0).Column("UNITNAME").getString());
          su.setUserID("0000000000000000");
          su.setFace("1");

          su.setUserCSS("Blue.css");
          su.setUserImage("blueimg");
          su.setUserIndexColor("#8DAAF4");

          su.setUserPageSize(18);
          su.setUserWINDOWTYPE("1");
          su.setWebEditCss("coolblue");

          su.setCustom1("");
          su.setCustom2("");
          su.setCustom3("");
          su.setCustom4("");
          su.setCustom5("");

          fm.setResult(true);
          fm.setMessage("0000000000000000");
          fm.setValue(su);

          dbset = null;
        }
      }
      else {
        strSQL = "Select a.UserState,a.LOGINID,a.NAME,a.LCODE,a.UNITID,a.LoginPW,a.USERID,a.USERIMAGE,a.WINDOWTYPE,a.PAGESIZE,b.UNITNAME,b.UNITNAME From BPIP_USER  a left join BPIP_UNIT b on a.UNITID=b.UNITID  Where LoginID='"+loginID.trim()+"' or NAME='"+loginID.trim()+"'";
        dbset = null;
        dbset = dbengine.QuerySQL(strSQL);
        if (dbset == null) {
          fm.setResult(false);
          fm.setMessage("登录用户["+loginID.trim()+"]不存在，请检查输入的用户名是否正确。！");
        }
        else if (dbset.RowCount() == 0) {
          fm.setResult(false);
          fm.setMessage("登录用户["+loginID.trim()+"]不存在，请检查输入的用户名是否正确。！");
        }
        else if (dbset.Row(0).Column("UserState").getString().equals("1")) {
          fm.setResult(false);
          fm.setMessage("该用户已经被管理员禁止使用，如有问题请于当地管理员联系。");
        }
        else if (dbset.RowCount() == 1) {

          String strIsLogin = "0";
          if (dbset.Row(0).Column("LoginPW").getString().equals(MD5.toMD5(pw)) || pw.equals("autologinpassword"))
          {
               strIsLogin = "1";
          }

          if (strIsLogin.equals("1"))
          {

          SessionUser su = new SessionUser();
          su.setLoginID(dbset.Row(0).Column("LOGINID").getString());
          su.setName(dbset.Row(0).Column("NAME").getString());
          su.setLCODE(dbset.Row(0).Column("LCODE").getString());

          su.setUnitID(dbset.Row(0).Column("UNITID").getString());
          su.setUnitName(dbset.Row(0).Column("UNITNAME").getString());
          su.setUserID(dbset.Row(0).Column("USERID").getString());
          su.setFace(dbset.Row(0).Column("USERIMAGE").getString());


          //有一些有特殊自定义参数时设置
          su.setCustom1("");
          su.setCustom2("");
          su.setCustom3("");
          su.setCustom4("");
          su.setCustom5("");
          //-------------------------


          su.setUserCSS("Blue.css");
          su.setUserImage("blueimg");
          su.setUserIndexColor("#8DAAF4");

          if("6".equals(dbset.Row(0).Column("WINDOWTYPE").getString())){
        	  su.setUserWINDOWTYPE("6");
          }else{
        	  su.setUserWINDOWTYPE(dbset.Row(0).Column("WINDOWTYPE").getString());
          }
          su.setUserPageSize(dbset.Row(0).Column("PAGESIZE").getInteger());
          su.setWebEditCss("coolblue");


             if (dbset.Row(0).Column("WINDOWTYPE").getString().equals("1"))
             {
               su.setUserCSS("Blue.css");
               su.setUserImage("blueimg");
               su.setUserIndexColor("#8DAAF4");
               su.setWebEditCss("coolblue");
             }
             if (dbset.Row(0).Column("WINDOWTYPE").getString().equals("2"))
                {su.setUserCSS("Public.css");
                 su.setUserImage("publicimg");
                 su.setUserIndexColor("#94DD77");
                 su.setWebEditCss("green");
             }
             if (dbset.Row(0).Column("WINDOWTYPE").getString().equals("3"))
                {
                  su.setUserCSS("Yellow.css");
                  su.setUserImage("yellowimg");
                  su.setUserIndexColor("#F4CEA7");
                  su.setWebEditCss("yellow");
             }
             if (dbset.Row(0).Column("WINDOWTYPE").getString().equals("4"))
                 {
                   su.setUserCSS("Window.css");
                   su.setUserImage("windowimg");
                   su.setUserIndexColor("#C6C6C6");
                   su.setWebEditCss("light");
              }
              if (dbset.Row(0).Column("WINDOWTYPE").getString().equals("5"))
                 {
                   su.setUserCSS("nBlue.css");
                   su.setUserImage("nblueimg");
                   su.setUserIndexColor("#7C85A2");
                   su.setWebEditCss("light");
              }if (dbset.Row(0).Column("WINDOWTYPE").getString().equals("6"))
              {
            	  su.setUserCSS("html5.css");
            	  su.setUserImage("6");
            	  su.setUserIndexColor("#C6C6C6");
                  su.setWebEditCss("light");
             }

          fm.setResult(true);
          fm.setMessage(dbset.Row(0).Column("UserID").getString());

          fm.setValue(su);
          String  sSql= "";
          sSql = "Update BPIP_USER Set LoginTime=LoginTime+1 Where UserID='"+dbset.Row(0).Column("UserID").getString()+"'";

          dbengine.ExecuteSQL(sSql);

          }else
          {
              fm.setResult(false);
              fm.setMessage("用户密码错误，请重新登录！");
          }

        }
        else {
          fm.setResult(false);
          fm.setMessage("用户密码错误，请重新登录！");
        }
        dbset = null;
      }
    }
    catch (Exception ex) {
      log.WriteErrorLog("Login",ex.toString());
      fm.setResult(false);
          fm.setMessage("验证登录信息失败！\n详细错误信息如下:\n  "+ex.toString());
    }


       return fm;
  }

  //用户停用
  public boolean  StopUser(String userID) {
    boolean returnValue = false; //定义返回值
    String  strSQL= "";
    ArrayList arrList_UserList = new ArrayList();
     userID += ",";
      try
          {
            arrList_UserList = GetArrayList(userID, ",");
          }
      catch(Exception ex)
          {
            log.WriteLog(ex.getMessage());
          }
      if(arrList_UserList.size()>0){
         for (int i = 0; i < arrList_UserList.size(); i++) {
            strSQL = "Update BPIP_USER set UserState=1 Where UserID='"+arrList_UserList.get(i).toString().trim()+"'";
            returnValue = dbengine.ExecuteSQL(strSQL);
            }
          }
    return returnValue;
  }

  //解除用户停用
  public boolean  unStopUser(String userID) {
    String  strSQL= "";
    boolean returnValue = false; //定义返回值
    ArrayList arrList_UserList = new ArrayList();
          userID += ",";
       try
           {
             arrList_UserList = GetArrayList(userID, ",");
           }
        catch(Exception ex)
           {
             log.WriteLog(ex.getMessage());
           }
      if(arrList_UserList.size()>0){
         for (int i = 0; i < arrList_UserList.size(); i++) {
             strSQL = "Update BPIP_USER set UserState=0 Where UserID='"+arrList_UserList.get(i).toString().trim()+"'";
             returnValue = dbengine.ExecuteSQL(strSQL);
           }
         }
    return returnValue;
  }

  //重设密码
  public  boolean  ResetPassword(String userID, String pw) {
    String  strSQL= "";
    boolean returnValue = false; //定义返回值
    ArrayList arrList_UserList = new ArrayList();
         userID += ",";
       try
          {
            arrList_UserList = GetArrayList(userID, ",");
          }
          catch(Exception ex)
          {
            log.WriteLog(ex.getMessage());
          }
     if(arrList_UserList.size()>0){
         for (int i = 0; i < arrList_UserList.size(); i++) {
        //如果不是系统内建帐号
        String StrUserid =arrList_UserList.get(i).toString().trim();
        if(!StrUserid.equals("0000000000000000")){
          strSQL = "Update BPIP_USER set LoginPW='"+
                                  MD5.toMD5(pw)+ "' Where UserID='"+StrUserid+
                                  "'";
                 returnValue = dbengine.ExecuteSQL(strSQL);
        }

      }
    }
    return returnValue;
  }
  //重设密码
    public  boolean  ResetPassword1(String userID, String pw) {
      String  strSQL= "";
      boolean returnValue = false; //定义返回值
      ArrayList arrList_UserList = new ArrayList();
           userID += ",";
         try
            {
              arrList_UserList = GetArrayList(userID, ",");
            }
            catch(Exception ex)
            {
              log.WriteLog(ex.getMessage());
            }
       if(arrList_UserList.size()>0){
           for (int i = 0; i < arrList_UserList.size(); i++) {
          //如果不是系统内建帐号
           String StrUserid =arrList_UserList.get(i).toString().trim();
            pw =GetUserLoginID(StrUserid);
          if(!StrUserid.equals("0000000000000000")){
            strSQL = "Update BPIP_USER set LoginPW='"+ MD5.toMD5(pw)+ "' Where UserID='" +StrUserid+"'";
                   returnValue = dbengine.ExecuteSQL(strSQL);
          }
        }
      }
      return returnValue;
  }
  //获取用户登录名
  public String GetUserLoginID(String userID) {
     String strSQL= "";
     if(userID==null)return null;
    //如果是系统内建用户
    if(userID.equals("0000000000000000"))return "pip";
    String returnValue = null;
    strSQL = "Select LoginID  From BPIP_USER Where UserID = '"+userID+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if(dbset!=null){
      if (dbset.RowCount() > 0) {
        returnValue = dbset.Row(0).Column("LoginID").getString();
      }
      dbset = null;
    }
     return returnValue;
  }
  //获取用户真实姓名
  public String GetUserName(String userID) {
     if(userID==null)return null;
    //如果是系统内建用户
    if(userID.equals("0000000000000000"))return "系统内建用户";
    String returnValue = null;
    String strSQL= "";
    strSQL = "Select Name  From BPIP_USER Where UserID = '"+userID+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if(dbset!=null){
      if (dbset.RowCount() > 0) {
        returnValue = dbset.Row(0).Column("Name").getString();
      }
      dbset = null;
    }
     return returnValue;
  }
  //获取用户照片
  public byte[] GetUserPhoto(String userID){
    byte[] returnValue = null;
    String strSQL= "";
    strSQL = "Select USERPHOTO  From BPIP_USER_PHOTO Where UserID = '"+userID+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if(dbset!=null){
      if (dbset.RowCount() > 0) {
        returnValue = dbset.Row(0).Column("USERPHOTO").getBlob();
      }
      dbset = null;
    }
    return returnValue;
  }
  //获取用户自定义头像
  public byte[] GetUserSelfFace(String userID){
    byte[] returnValue = null;
    String  strSQL= "";
    strSQL = "Select USERIMAGE  From BPIP_USER_PHOTO Where UserID = '"+userID+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if(dbset!=null){
      if (dbset.RowCount() > 0) {
        returnValue = dbset.Row(0).Column("USERIMAGE").getBlob();
      }
      dbset = null;
    }
     return returnValue;
  }
  //获取用户签名
  public byte[] GetUserIdiograph(String userID){
    byte[] returnValue = null;
    String  strSQL= "";
    strSQL = "Select IDIOGRAPH  From BPIP_USER_PHOTO Where UserID = '"+userID+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if(dbset!=null){
      if (dbset.RowCount() > 0) {
        returnValue = dbset.Row(0).Column("IDIOGRAPH").getBlob();
      }
      dbset = null;
    }
     return returnValue;
  }

  //获取用户所在单位编号
  public String GetUserUNITID(String userID) {
      if(userID==null)return null;
      String returnValue = null;
      String  strSQL= "";

      strSQL = "Select UNITID From BPIP_USER Where UserID = '"+userID+"'";
      dbSet dbset = dbengine.QuerySQL(strSQL);
      if (dbset != null) {
        if (dbset.RowCount() > 0) {
          returnValue = dbset.Row(0).Column("UNITID").getString();
        }
        dbset = null;
      }
     return returnValue;
  }
  //获取用户所在单位名称
  public String GetUserUNITName(String userID) {
     if(userID==null)return null;
     String returnValue = null;
      String strSQL= "";
    //如果是系统内建用户
    if(userID.equals("0000000000000000")){
          returnValue = "管理单位";
    }else{
      strSQL = "Select b.UNITID From BPIP_USER a Left Join BPIP_UNIT b on a.UNITID=b.UNITID Where a.UserID = '"+
          userID +"'";
      dbSet dbset = dbengine.QuerySQL(strSQL);
      if (dbset != null) {
        if (dbset.RowCount() > 0) {
          returnValue = dbset.Row(0).Column("UNITNAME").getString();
        }
        dbset = null;
      }
    }
     return returnValue;
  }
  //检查用户口令
  public boolean  CheckPw(String strUserID, String strPw) {
    if(strUserID==null||strPw==null)return false;
    boolean result = false;
    String strSQL= "";
    strSQL = "Select Name From BPIP_USER Where (UserID='"+
                strUserID+"' or NAME='"+
                strUserID+"') and LoginPW = '"+MD5.toMD5(strPw)+"'";

    dbSet dbset = dbengine.QuerySQL(strSQL);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        result = true;
      }
      dbset = null;
    }
    return result;
  }

   /**
    * 获取用户类型图片
    * @param sType String  用户类型代码
    * @param Path String   图片路径
    * @return String       详细用户类型图片路径
    */
   public String GetUserTypeImg(String sType,String Path) {
     String returnValue= "";
    try {
      int iType = Integer.parseInt(sType);
      switch (iType) {
        case 0:
          returnValue="<img src=\""+Path+
              "zrsysmanage/images/user1.gif\" width=\"16\" height=\"15\" align=\"absmiddle\">";
          break;
        case 1:
          returnValue="<img src=\""+Path+
              "zrsysmanage/images/user2.gif\" width=\"16\" height=\"15\" align=\"absmiddle\">";
          break;
        case 2:
          returnValue="<img src=\""+Path+
              "zrsysmanage/images/user3.gif\" width=\"16\" height=\"15\" align=\"absmiddle\">";
          break;
        case 3:
          returnValue="<img src=\""+Path+
              "zrsysmanage/images/user4.gif\" width=\"16\" height=\"15\" align=\"absmiddle\">";
          break;
      }
    }
    catch (NumberFormatException ex) {
      log.WriteErrorLog("",ex.toString());
    }
     return returnValue.toString();
   }

  /**
   * 获取用户状态
   * @param sType String   用户状态代码
   * @return String        用户状态名称
   */
  public String GetUserState(String sType) {
    String returnValue = "未知状态";
    int iType = Integer.parseInt(sType);
    switch (iType) {
      case 0:
        returnValue = "使用中";
        break;
      case 1:
        returnValue = "已停用";
        break;
    }
    return returnValue;
  }

  /**
  * 更改应用配置
  * @param PageSize int   表单每页显示的记录数
  * @param WindowType     界面样式
  * @return boolean      更改是否成功
  */
  public boolean  ChangeAppCon(String userID,int PageSize,String WindowType) {
    boolean returnValue = false; //定义返回值
    String strsql = "";
    try {
      if (userID != null) {
        strsql = "Update BPIP_USER set PAGESIZE="+String.valueOf(PageSize)+" , WINDOWTYPE ='"+WindowType+"'  Where UserID='"+userID+"'";
        returnValue=dbengine.ExecuteSQL(strsql);
      }
    }
    catch (Exception ex) {
      log.WriteErrorLog("ChangeAppCon:", ex.toString());
      returnValue=false;
    }
    return returnValue;
  }

   /**
    * 功能：根据单位编号生成单位下的用户列表
    * @param strUnitID 单位编号
    * @param strListName 列表名称
    * @param strUserimage 用户图片文件夹
    * @param ico 图标
    * @param strtype 类型
    * @return returnValue 返回生成的用户列表
    */
   public String GetShowUnitUserList(String strUnitID,String strListName,String strUserimage,String ico,String strtype){
     String strNo = "";
     String strName = "";
     StringBuffer  returnValue= new   StringBuffer();
     String strSQL= "";
     int k = 0;
     int row = 0;
     String strcheck = "";
     String strchecked = "";
     if (strtype.equals("1")) {
       strcheck = "radio";
     }
     else {
       strcheck = "checkbox";
     }
     returnValue.append("<table cellSpacing='0' cellPadding='0' border='0' width='100%'>\r\n");
     if (strUnitID.lastIndexOf("all") > -1) {//当前单位及下属单位
        strUnitID = strUnitID.substring(0,strUnitID.length()-4);
        StringWork sw = new StringWork();
        strUnitID = sw.CutLastZero(strUnitID,2);
        strSQL = "Select a.USERID,a.NAME,b.UNITNAME From BPIP_USER a left join BPIP_UNIT b on a.UNITID=b.UNITID where  a.USERSTATE='0'  and a.UNITID like '"+strUnitID+"%' order by b.UNITID,a.orbercode,a.NAME";
     }else
     {
         //检测去0后的单位下人数
         String strUnitID1 = strUnitID.substring(0,strUnitID.length()-4);
         StringWork sw = new StringWork();
         strUnitID1 = sw.CutLastZero(strUnitID,2);
         strSQL = "Select count(USERID) as num From BPIP_USER  where USERSTATE='0'  and  UNITID like '"+strUnitID1+"%'";
         dbSet dbset0 = dbengine.QuerySQL(strSQL);
         int rownum = 0;
         if (dbset0 != null && dbset0.RowCount()>0)
         {
              rownum = dbset0.Row(0).Column("num").getInteger();
         }
         if (rownum<450)//450个用户以下可以一次选择
         {
             strSQL = "Select a.USERID,a.NAME,b.UNITNAME From BPIP_USER a left join BPIP_UNIT b on a.UNITID=b.UNITID where   a.USERSTATE='0' and a.UNITID like '"+strUnitID1+"%' order by b.UNITID,a.orbercode,a.NAME";

         }else
         {
             strSQL = "Select a.USERID,a.NAME,b.UNITNAME From BPIP_USER a left join BPIP_UNIT b on a.UNITID=b.UNITID where   a.USERSTATE='0'  and a.UNITID='"+strUnitID+"' order by b.UNITID,a.orbercode,a.NAME";
         }
     }
     String YdeptName = "";
     String deptName = "";
     dbSet dbset1 = dbengine.QuerySQL(strSQL);
     if (dbset1 != null){
        if (dbset1.RowCount()>0)
        {
           for (int i = 0; i < dbset1.RowCount(); i++) {

               strchecked = "";

         strNo = dbset1.Row(i).Column("USERID").getString();
         strName = dbset1.Row(i).Column("NAME").getString();
         deptName = dbset1.Row(i).Column("UNITNAME").getString();

         if (strNo.length() > 0) {

             if (!strtype.equals("1")) {
                strListName = strListName + strNo;
             }
             //----
             if (!YdeptName.equals(deptName))
             {
                 returnValue.append("<tr><td colspan='3'>"+deptName+"</td></tr>\r\n");
                 if (row>0)
                 {
                   if (k==1)
                  {
                    returnValue.append("<td></td><td></td>\r\n");
                  }
                  if (k==2)
                  {
                    returnValue.append("<td></td>\r\n");
                  }
                  k=3;
                 }
             }
             //----
             row = row +1;
             k = k + 1;
             if (k == 4) {
                k = 1;
             }
             if (k == 1)
             {
                returnValue.append("<tr>\r\n");
             }

             returnValue.append("<td align='left' height='25' style='cursor:pointer ' onclick=\"selectOnclick('"+strNo)
                 .append("');\"><input type='"+strcheck+"' "+strchecked+" onclick=\"selectOnclick('")
                 .append(strNo+"');\" name='"+strListName+"' id='"+strNo+"' value='")
                 .append(strName+"'>"+"<img src='"+SysPreperty.getProperty().AppUrl+"zrsysmanage/images/")
                 .append(strUserimage+"/"+ico+"' border='0' align='absmiddle'>"+strName)
                 .append("</td>");

             if (k == 3) {
                 returnValue.append("</tr>\r\n");
             }

             YdeptName = deptName;
           }
           //-----------------
          }
        }
        dbset1 = null;
     }
    if (k==1)
     {
       returnValue.append("<td></td><td></td></table>\r\n");
     }
     if (k==2)
     {
       returnValue.append("<td></td></table>\r\n");
     }
     if (k==3)
      {
        returnValue.append("</table>\r\n");
      }
     return returnValue.toString();
   }

   /**
        * 获取所有已经停用的用户
        * @param  UnitID String  行政区划
        * @return BPIP_USER[]
   */
   public BPIP_USER[] GetRecoveryUserList() {
         BPIP_USER[] resultValue = null;
         String strSQL= "";
         strSQL = "Select A.USERID,A.LOGINID,A.NAME,A.LOGINTIME,A.USERSTATE,B.UNITNAME AS UNITID From BPIP_USER A Left Join BPIP_UNIT B on A.UNITID=B.UNITID Where  A.UserState='1' Order By A.UserID";
         dbSet set = dbengine.QuerySQL(strSQL);
         if (set != null) {
           if (set.RowCount() > 0) {
             resultValue = new BPIP_USER[set.RowCount()];
             for (int i = 0; i < set.RowCount(); i++) {
               resultValue[i] = new BPIP_USER();
               resultValue[i].fullData(set.Row(i));
             }
           }
           set = null;
         }
         return resultValue;
     }
     /**
     * 功能或作用：彻底删除用户
     * @param
     * @return 返回
     */
    public boolean DelAllUser(String strMenu_No) {
      boolean strResult = false;
      ArrayList arrList_strMenu_No = new ArrayList();

       try{
             arrList_strMenu_No = GetArrayList(strMenu_No+",", ",");
           }catch(Exception ex)
           {
             log.WriteLog(ex.getMessage());
           }
       if(arrList_strMenu_No.size()>0){
         String[]  strSq1s =new String[5];
         for (int i = 0; i < arrList_strMenu_No.size(); i++) {
           strSq1s[0] = "delete from BPIP_USER_PHOTO  Where UserID='"+arrList_strMenu_No.get(i).toString()+"'";
           strSq1s[1] = "delete from BPIP_USER_REMOVE Where UserID='"+arrList_strMenu_No.get(i).toString()+"'";
           strSq1s[2] = "delete from BPIP_USER_ROLE  Where UserID='"+arrList_strMenu_No.get(i).toString()+"'";
           strSq1s[3] = "delete from BPIP_USER_IDEA  Where USER_NO='"+arrList_strMenu_No.get(i).toString()+"'";
           strSq1s[4] = "delete from BPIP_USER where USERID = '"+arrList_strMenu_No.get(i).toString()+"'";
           strResult = dbengine.ExecuteSQLs(strSq1s);
         }
       }
       return strResult;
   }
      /**
       * 功能或作用：还原用户
       * @param
       * @return 返回
       */
   public boolean RestoreUser(String strMenu_No) {
        boolean strResult = false;
        String strSql= "";
        ArrayList arrList_strMenu_No = new ArrayList();
         try
             {
               arrList_strMenu_No = GetArrayList(strMenu_No+",", ",");
             }catch(Exception ex)
             {
               log.WriteLog(ex.getMessage());
             }
         if(arrList_strMenu_No.size()>0){
           for (int i = 0; i < arrList_strMenu_No.size(); i++) {
             strSql = "Update BPIP_USER set UserState='0' where UserID = '"+
                 arrList_strMenu_No.get(i).toString()+"'";
             strResult = dbengine.ExecuteSQL(strSql);
           }
         }
         return strResult;
   }
   /**
   * 功能或作用：分析规则字符串，生成数组
   * @param strItems 字符串
   * @param strItemMark 标识符
   * @return 返回数组
   */
   public ArrayList GetArrayList(String strItems, String strItemMark) {
      int intItemLen, i = 0, n = 0;
      String strItem;
      ArrayList strList = new ArrayList();
      intItemLen = strItems.length();
      while (i < intItemLen) {
        n = strItems.indexOf(strItemMark, i);
        strItem = strItems.substring(i, n);
        strList.add(strItem);
        i = n + 1;
      }
      return strList;
}
/**
       * 功能：角色列表
       * @param strROLELEVEL 单位编号
       * @param strListName  列表名称
       * @param strUserimage 用户图片文件夹
       * @param ico 图标
       * @return returnValue 返回生成的角色列表
       */
public String GetShowUserRoleList(String strListName,String strUserimage,String ico){
	    if("6".equals(strUserimage)){
	    	strUserimage="windowimg";
	    }
        String strNo = "";
        String strName = "";
        String  strSQL= "";
        StringBuffer  returnValue= new   StringBuffer();
        int k = 0;
        String strcheck = "";
        String strchecked = "";
        strcheck = "checkbox";
        returnValue.append("<table cellSpacing='0' cellPadding='0' border='0' width='100%'>\r\n");
         strSQL = "Select ROLEID,ROLENAME From BPIP_ROLE  order by ROLENAME";
         dbSet dbset1 = dbengine.QuerySQL(strSQL);
        if (dbset1 != null){
           if (dbset1.RowCount()>0)
           {
              for (int i = 0; i < dbset1.RowCount(); i++) {
                if (i == 0) {
                    strchecked = "";
                 }
                else {
                    strchecked = "";
                  }
                strNo = String.valueOf(dbset1.Row(i).Column("ROLEID").getInteger());
                strName = dbset1.Row(i).Column("ROLENAME").getString();
                if (strNo.length() > 0) {
                    k = k + 1;
                    if (k == 4) {
                       k = 1;
                    }
                    if (k == 1)
                    {
                       returnValue.append("<tr>\r\n");
                    }
                    returnValue.append("<td align='left' height='25' style='cursor:pointer ' onclick=\"selectOnclick('"+strNo+"');\"><input type='"+strcheck+"' "+
                         strchecked+" onclick=\"selectOnclick('"+strNo+"');\" name='"+strListName+"'id='"+strNo+ "'value='" +strName+ "'>");
                    returnValue.append("<img src='"+
                        SysPreperty.getProperty().AppUrl+"zrsysmanage/images/"+strUserimage+"/"+
                           ico+"' border='0' align='absmiddle'>");
                    returnValue.append(strName+"</td>");
                    if (k == 3) {
                        returnValue.append("</tr>\r\n");
                    }
                }
              //-----------------
             }
           }
           dbset1 = null;
        }
        if (k==1)
        {
          returnValue.append("<td></td><td></td></table>\r\n");
        }
        if (k==2)
        {
          returnValue.append("<td></td></table>\r\n");
        }
        if (k==3)
         {
           returnValue.append( "</table>\r\n");
         }
        return returnValue.toString();
   }



  //更新当前用户的在线时间
  public void UpUserOnlineDate(String strUserID) {
            String  strSql  = "";
            strSql = "update BPIP_USER set ONLINEDATE=sysdate where USERID='"+strUserID+"'";
            dbengine.ExecuteSQL(strSql);
  }
  /**
    * 功能：得到服务器的总人数
    * @return int
*/
public int GetSysSaverPNumber() {
          int returnvalue = 1;
          String strSql = "";
          //在线更新时间小于3分钟的为在线人员
          if (DataBaseType.equals("2"))//mssql
          {
           strSql = "Select count(*) as pnumber From BPIP_USER where datediff(n,ONLINEDATE,getdate())<3";
          }else
          {
           strSql = "Select count(*) as pnumber From BPIP_USER where (sysdate-ONLINEDATE)*1440<3";
          }

          dbSet mdbset = dbengine.QuerySQL(strSql);
          if (mdbset != null){
             returnvalue = mdbset.Row(0).Column("pnumber").getInteger();
             mdbset = null;
         }
       return returnvalue;
}
     /**
       * 功能：得到登录服务器的人员列表
       * PageSize 每页显示的记录数
       * Page 第几页
       */
       public BPIP_USER[] GetLoginUserList(int PageSize,int Page){
              BPIP_USER[] returnValue = null;
              String  strSQL= "";
              //在线更新时间小于3分钟的为在线人员
              if (DataBaseType.equals("2"))//mssql
              {
                strSQL = "SELECT * FROM (SELECT C.*, ROWNUM RN FROM (Select USERID,NAME,LOGINID,UNITID From BPIP_USER  where datediff(n,ONLINEDATE,getdate())<3 Order By USERID) "+" C WHERE ROWNUM <= "+
                      String.valueOf(PageSize * Page)+") WHERE RN > "+String.valueOf( (Page - 1) * PageSize);
              }
              else
              {
                strSQL = "SELECT * FROM (SELECT C.*, ROWNUM RN FROM (Select USERID,NAME,LOGINID,UNITID  From BPIP_USER  where (sysdate-ONLINEDATE)*1440<3 Order By USERID) "+" C WHERE ROWNUM <= "+
                      String.valueOf(PageSize * Page)+") WHERE RN > "+String.valueOf( (Page - 1) * PageSize);
              }

              dbSet dbset = dbengine.QuerySQL(strSQL);
              if (dbset != null) {
                 if (dbset.RowCount() > 0) {
                   returnValue = new BPIP_USER[dbset.RowCount()];
                   for (int i = 0; i < dbset.RowCount(); i++) {
                       returnValue[i] = new BPIP_USER();
                       returnValue[i].fullData(dbset.Row(i));

                   }
                }
                dbset = null;
             }
             return returnValue;
    }

    /**
        * 创建页面导航链接
        * @param currentPage int
        * @return String
        */
         public String CreatePage(int intPageSize,int intPage){
                String resultStr = "";
                int intRowCount = 0;
                String strsql = "";
                if (DataBaseType.equals("2"))//mssql
                {
                  strsql = "Select count(*) as RCount1 From BPIP_USER where datediff(n,ONLINEDATE,getdate())<3";

                }
                else
                {
                  strsql = "Select count(*) as RCount1 From BPIP_USER where (sysdate-ONLINEDATE)*1440<3";

                }

                dbSet ds = dbengine.QuerySQL(strsql);
                if (ds == null) {
                  intRowCount = 0;
                }
                else {
                  intRowCount = ds.Row(0).Column("RCount1").getInteger();
                }
                resultStr = CreatePageMenu(intPageSize, intRowCount,intPage);
                return resultStr;
        }
        /**
         * 功能或作用：实现翻页
         * @param PageSize 一页的记录数
         * @param FileUrl 文件名
         * @param intRowCount 总的记录数
         * @param intPage 当前页
         * @Return PageMenu 执行后返回一个PageMenu字符串
         */
        private String CreatePageMenu(int intPageSize, int intRowCount, int intPage) {
          StringBuffer PageMenu = new StringBuffer();
          PageMenu.append("&nbsp;");
          int intPageCount = 0, i, sum1 = 0, sum2 = 0, sum3 = intRowCount;
          while ( ( (intRowCount - intPageSize) > 0) || (intRowCount > 0)) {
            intPageCount++;
            intRowCount = intRowCount - intPageSize;
          }
          if (intPage > intPageCount) {
            intPage = intPageCount;
          }
          if (intPageCount > 1) {
            sum1 = intPage - 1;
            if (sum1 < 1) {
              sum1 = 1;
            }
            sum2 = intPage + 1;
            if (sum2 > intPageCount) {
              sum2 = intPageCount;
            }
            PageMenu.append(
                "<a href='javascript:recordfrm.page.value=\"1\";recordfrm.submit();'>首页</a>");
            PageMenu.append("&nbsp;&nbsp;<a href='javascript:recordfrm.page.value=\"").
                append(
                    String.valueOf(sum1)+"\";recordfrm.submit();'>上一页</a>");
            PageMenu.append("&nbsp;&nbsp;<a href='javascript:recordfrm.page.value=\"").
                append(
                    String.valueOf(sum2)+"\";recordfrm.submit();'>下一页</a>");
            PageMenu.append("&nbsp;&nbsp;<a href='javascript:recordfrm.page.value=\"").
                append(
                    String.valueOf(intPageCount)+
                        "\";recordfrm.submit();'>末页</a>&nbsp;&nbsp;");

            PageMenu.append("<select size='1' class='PageStyle'  Onchange='javascript:recordfrm.page.value=this.value;recordfrm.submit();'>");
            for (i = 1; i <= intPageCount; i++) {
              if (intPage == i) {
                PageMenu.append("<option value='"+i+
                    "' selected >第"+i+"页</option>");
              }
              else {
                PageMenu.append("<option value='"+i+"' >第"+i).
                    append(
                        "页</option>");
              }
            }
            PageMenu.append("</select>");

            PageMenu.append("&nbsp;&nbsp;页次："+intPage+"/"+
                intPageCount+"&nbsp;&nbsp;共"+sum3+"人在线&nbsp;&nbsp;");
          }
          else {
            PageMenu.append("&nbsp;&nbsp;共"+sum3+"人在线&nbsp;&nbsp;");
          }

          String checkboxStr;

          checkboxStr = ""; //不需要checkbox
          String FontPageMenu = PageMenu.toString();
          PageMenu.delete(0, PageMenu.length()); //清空
          PageMenu.append("<TD width='20%'>"+checkboxStr+
              "<TD align='right'>"+
                  FontPageMenu);
          return PageMenu.toString();
      }


}
