package zr.zrpower.ejb.sys;

import java.io.File;
import zr.zrpower.common.util.Log;
import zr.zrpower.common.db.*;
import zr.zrpower.common.util.SysPreperty;
import zr.zrpower.common.util.StringWork;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;


public class SeManageService
  {
  static private Log log;
  dbEngine dbengine;
  static private int clients=0;
  public SeManageService()
  {
    dbengine = new dbEngine(SysPreperty.getProperty().MainDataSource,
                              SysPreperty.getProperty().IsConvert);
    dbengine.initialize();

    if (clients<1)
    {
      log = new Log();
      log.SetLogForClass("SeManageService");
      log.SetLogFile("SeManageEjb.log");

    }
    clients++;
  }


  /**
   * 功能：得到系统附件列表
   * @param strFLOWID 流程标识
   * @param strFORMID 表单ID值
   * @return returnValue 返回附件列表
   */
  public String GetSysFileNameList(String strFLOWID, String strFORMID) {
     String strResult= "";
     String  strSql= "";
     String  strALLPath= "";

    strSql = "SELECT ID,FILENAME,FILEPATH,YNAME from BPIP_ATT WHERE FLOWID = '" +
        strFLOWID + "' and FORMID = '" + strFORMID + "'";
    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        int intList = 0;
        for (int i = 0; i < dbset.RowCount(); i++) {
          intList++;
          strALLPath = dbset.Row(i).Column("FILEPATH").getString()+"/"+ dbset.Row(i).Column("FILENAME").getString();

          strResult = strResult+intList + "、<a href='../../serverfile.do?type=6&file=" +
              strALLPath +"&name="+dbset.Row(i).Column("YNAME").getString()+"'  target=_blank title='下载'>" + dbset.Row(i).Column("YNAME").getString();
          strResult = strResult+ "</a><br>";
        }
      }
      dbset = null;
    }
    else {
       strResult = strResult+ "<font class='AlertSign'>〖无附件〗</font>";
    }
    return strResult;
  }



  /**
   * 功能：新建文件夹
   * @param strPath 文件夹的路径
   * @return return 返回是否成功
   */
  public boolean CreateFileFoler(String strPath) {
    boolean exists = (new File(strPath)).exists();
    if (exists) {
      return false;
    }
    else {
      try {
        File f = new File(strPath);
        f.mkdir();
      }
      catch (SecurityException e) {
        System.out.println(e);
      }
    }
    return true;
  }


  /**
   * 功能：增加系统附件记录
   * @param strFLOWID 流程标识
   * @param strFORMID 表单ID
   * @param strAID 活动ID
   * @param strFileName 文件名
   * @param strUserID 用户ID
   * @param strUserID 用户附件ID
   * @param strpTitle 原文件标题
   * @return return 返回是否成功
   */
  public boolean SysAttFileAdd(String strFLOWID, String strFORMID,
                               String strAID, String strFileName,
                               String strUserID,
                               String strUserFileID,String strpTitle) {
    String strALLPath= SysPreperty.getProperty().UploadFilePath +
        "/AttManage/" + strUserID + "/" + strUserFileID + "/" + strFileName;

    File objFile = new File(strALLPath.toString());
    long filesize = objFile.length();
    filesize = filesize / 1024;
    String strID = "";

    String strNum ="";
    try {
       strNum = myGetRandom(4);
    } catch (Exception ex) {
       strNum = "0";
    }
    strID = "A"+GlobalID()+strNum;

    if (strID.length()>18)
    {
       strID = strID.substring(0,18);
    }

    String  strSql= "";
    strSql = "INSERT INTO BPIP_ATT(ID,FLOWID,FORMID,AID,FILEID,FILENAME,FILESIZE,FILEPATH,FILEUSERNO,ENTERDATE,YNAME)"
           +" VALUES('" + strID + "','" + strFLOWID + "','" +
        strFORMID + "','" + strAID + "','" + strUserFileID + "','" +
        strFileName + "','" +
        filesize + "','" + strUserID + "/" + strUserFileID + "','" + strUserID +
        "',sysdate,'"+strpTitle+"')";
    return dbengine.ExecuteSQL(strSql);
  }

  private String myGetRandom(int i) {
           Random s = new Random();
           if (i == 0)
           { return "";}
           String revalue = "";
           for (int k = 0; k < i; k++) {
                revalue = revalue + s.nextInt(9);
           }
           return revalue;
  }
  private String GlobalID(){
         String strResult="";
         java.util.Date dt = new java.util.Date();
         long lg = dt.getTime();
         Long ld = new Long(lg);
         strResult = ld.toString();
         return strResult;
 }

  /**
   * 功能：显示系统附件列表
   * @param strFLOWID 流程标识
   * @param strFORMID 表单ID
   * @param strUserID 用户ID
   * @return return 返回附件列表
   */
  public String ShowSysAttFile(String strFLOWID, String strFORMID,
                               String strUserID) {
    String strID = "", strNAME = "";
    String returnValue= "";
    returnValue = "<select name='attlist' style='width:322'>\r\n";
    String strSql= "";
    if (strUserID.length() > 0) {
      strSql = "select ID,YNAME from BPIP_ATT where FLOWID='" + strFLOWID +
          "' and FORMID='" + strFORMID + "' and FILEUSERNO='" + strUserID + "'";
    }
    else {
      strSql = "select ID,YNAME from BPIP_ATT where FLOWID='" + strFLOWID +
          "' and FORMID='" + strFORMID + "'";
    }

    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        for (int i = 0; i < dbset.RowCount(); i++) {
          strID = dbset.Row(i).Column("ID").getString();
          strNAME = dbset.Row(i).Column("YNAME").getString();
          returnValue = returnValue + "<option value='" + strID + "'>" +
              strNAME + "</option>\r\n";
        }
      }
      dbset = null;
    }
    returnValue = returnValue + "</select>\r\n";
    return returnValue;
  }



  /**
   * 功能：删除系统附件记录
   * @param strFileID 附件ID
   * @return return 返回是否成功
   */
  public boolean SysAttFileDel(String strFileID) {
    String strSql= "";
    String strALLPath1= "";
    String strALLPath = "";
    strALLPath1 = SysPreperty.getProperty().UploadFilePath+"/AttManage";
    strSql = "select FILEPATH,FILENAME from BPIP_ATT where ID='" + strFileID + "'";
    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        strALLPath = strALLPath1 + "/" +
            dbset.Row(0).Column("FILEPATH").getString() + "/" +
            dbset.Row(0).Column("FILENAME").getString();
      }
      dbset = null;
    }

    //删除服务器上的文件
    File file = new File(strALLPath.toString());
    file.delete();
    //删除数据库里的记录
    strSql = "delete From BPIP_ATT where ID='" + strFileID + "'";
    return dbengine.ExecuteSQL(strSql);
  }



  /**
   * 功能：根据文件ID得到系统附件服务器上的完整路径
   * @param strFileID 附件ID
   * @return return 返回完整路径
   */
  public String SysAttFileAllPath(String strFileID) {
     String strSql= "";
     String strALLPath= "";
     String strALLPath1="";
     strALLPath1 = SysPreperty.getProperty().UploadFilePath+"/AttManage";

    strSql = "select FILEPATH,FILENAME from BPIP_ATT where ID='" + strFileID + "'";
    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        strALLPath = strALLPath1+ "/" +
            dbset.Row(0).Column("FILEPATH").getString() + "/" +
            dbset.Row(0).Column("FILENAME").getString();
      }
      dbset = null;
    }
    return strALLPath.toString();
  }



  /**
   * 功能：根据文件ID得到系统附件的文件名称
   * @param strFileID 附件ID
   * @return return 返回完整路径
   */
  public String GetSysAttFileName(String strFileID) {
    String strSql= "";
    String strName = "";
    strSql = "select FILENAME from BPIP_ATT where ID='" + strFileID + "'";
    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        strName = dbset.Row(0).Column("FILENAME").getString();
      }
      dbset = null;
    }
    return strName;
  }

  /**
   * 功能或作用：格式化日期时间
   * @param DateValue 输入日期或时间
   * @param DateType 格式化 EEEE是星期, yyyy是年, MM是月, dd是日, HH是小时, mm是分钟,  ss是秒
   * @return 输出字符串
   */
  public String FormatDate(String DateValue, String DateType) {
    String Result;
    SimpleDateFormat formatter = new SimpleDateFormat(DateType);
    try {
      Date mDateTime = formatter.parse(DateValue);
      Result = formatter.format(mDateTime);
    }
    catch (Exception ex) {
      Result = ex.getMessage();
    }
    if (Result.equalsIgnoreCase("1900-01-01")) {
      Result = "";
    }
    return Result;
  }

  /**
   * 功能或作用：得到待选择用户的列表
   * @param strType 1本单位人员 2所有人员
   * @param strUnitID 单位ID
   * @return 返回用户选择列表
   */
  public String GetAllTrueNameLst(String strType, String strUnitID) {
    String strTrueName = "";
    int intID = 0;
    int intCount = 0;
    String  strResult= "";
    String  strSql= "";
    String  mSql= "";
    StringWork mString = new StringWork();
    String strTmpUnitID = mString.CutLastZero(strUnitID, 2);
    if (strType.equals("1")) {
      strSql = "SELECT UNITID,UNITNAME FROM BPIP_UNIT where (UNITID ='" +
          strUnitID + "' or UNITID LIKE '%" + strTmpUnitID +
          "%') and UNITID in (Select UNITID from BPIP_USER) order by UNITID";
    }
    else {
      strSql = "SELECT UNITID,UNITNAME FROM BPIP_UNIT where UNITID in (Select UNITID from BPIP_USER) order by UNITID ";
    }
    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        for (int i = 0; i < dbset.RowCount(); i++) {
          strResult = strResult + "<tr height='23'><td>&nbsp;" +
          dbset.Row(i).Column("UNITNAME").getString() + "</td></tr>";
          mSql = "Select LOGINID,USERID,NAME,USERSTATE from BPIP_USER where USERSTATE='0'  and UNITID='" +
          dbset.Row(i).Column("UNITID").getString() + "' order by ORBERCODE,USERID";
          dbSet dbset1 = dbengine.QuerySQL(mSql);
          if (dbset1 != null) {
            if (dbset1.RowCount() > 0) {
              intCount = 0;
              for (int j = 0; j < dbset1.RowCount(); j++) {
                intID++;

                if (intCount == 0) {
                  strTrueName = dbset1.Row(j).Column("NAME").getString();
                  strResult = strResult + "<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;<input type='checkbox' name='record" +
                      intID + "' value='" +dbset1.Row(j).Column("USERID").getString() + "," +
                      strTrueName + "'>" +
                      strTrueName;
                }
                else {
                  strTrueName = dbset1.Row(j).Column("NAME").getString();
                  strResult = strResult +"&nbsp;&nbsp;<input type='checkbox' name='record" +
                      intID + "' value='" +
                      dbset1.Row(j).Column("USERID").getString() + "," +
                      strTrueName + "'>" +
                      strTrueName;
                }
                intCount++;

                if (intCount == 6) {
                  intCount = 0;
                  strResult = strResult +"</td></tr>";
                }
              }
              if (intCount < 6) {
                strResult = strResult +"</td></tr>";
              }
            }
            dbset1 = null;
          }
        }
      }
      dbset = null;
    }
    return strResult;
  }


  /**
   * 功能或作用：得到待选择用户的列表
   * @param strType 1本单位人员 2所有人员
   * @param strUnitID 单位ID
   * @return 返回用户选择列表
   */
  public String GetUserNameLst(String strUnitID, String strImage, String strIco) {
    String strTrueName = "";
    int k = 0;
    String strchecked = "0";
    String  strResult= "";
    String  strSql= "";
    String  mSql= "";
    dbSet dbset1 = null;

    strSql = "SELECT UNITID,UNITNAME FROM BPIP_UNIT where (UNITID ='" +
        strUnitID + "') and UNITID in (Select UNITID from BPIP_USER) order by UNITID";

    dbSet dbset = dbengine.QuerySQL(strSql);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        for (int i = 0; i < dbset.RowCount(); i++) {
          strResult =  strResult + "<tr height='23'><td colspan='3' align='left'>" +
              dbset.Row(i).Column("UNITNAME").getString() + "</td></tr>";
          mSql = "Select LOGINID,USERID,NAME,USERSTATE from BPIP_USER where USERSTATE='0'  and UNITID='" +
              dbset.Row(i).Column("UNITID").getString() + "' order by ORBERCODE,USERID";
          dbset1 = dbengine.QuerySQL(mSql);
          if (dbset1 != null) {
            if (dbset1.RowCount() > 0) {

              for (int j = 0; j < dbset1.RowCount(); j++) {
                if (j == -1) {
                  strchecked = "checked";
                }
                else {
                  strchecked = "";
                }
                k = k + 1;
                if (k == 4) {
                  k = 1;
                }
                if (k == 1) {
                  strResult =  strResult + "<tr>\r\n";
                }

                strTrueName = dbset1.Row(j).Column("NAME").getString();
                strResult =  strResult + "<td align='left' height='25' style='cursor:pointer ' onclick=\"javascript:document.getElementById('"+dbset1.Row(j).Column("USERID").getString()+"').checked='checked';\"><input type='radio' name='record" +
                    strchecked + "' value='" +
                    dbset1.Row(j).Column("USERID").getString() + "' id='" +
                    dbset1.Row(j).Column("USERID").getString() + "'>" +
                    "<img src='" +
                    SysPreperty.getProperty().AppUrl + "zrsysmanage/images/" + strImage +
                    "/" +
                    strIco + "' border='0' align='absmiddle'>" + strTrueName +
                    "</td>";

                if (k == 3) {
                   strResult =  strResult + "</tr>\r\n";
                }

              }
              if (k == 1) {
                strResult =  strResult + "<td></td><td></td></tr>\r\n";
              }
              if (k == 2) {
                strResult =  strResult + "<td></td></tr>\r\n";
              }

            }
            dbset1 = null;
          }
        }
      }
      dbset = null;
    }

    return strResult;
  }

  /**
   * 功能或作用：取出最大的记录流水号
   * @param TableName 数据库表名
   * @param FieldName 数据库字段名称
   * @param FieldLen 数据库字段长度
   * @Return MaxNo 执行后返回一个MaxNo字符串
   */
  private String GetMaxFieldNo(String TableName, String FieldName, int FieldLen) {
    String MaxNo = "";
    String  strSQL= "";
    int LenMaxNo = 0;
    strSQL = "SELECT MAX(" + FieldName + ") AS MaxNo FROM " + TableName;
    try {
      dbSet dbset = dbengine.QuerySQL(strSQL.toString());
      if (dbset != null) {
        if (dbset.RowCount() > 0) {
          MaxNo = dbset.Row(0).Column("MaxNo").getString();

          if (MaxNo.length() > 0) {
            MaxNo = String.valueOf(Integer.parseInt(MaxNo) + 1);
            LenMaxNo = MaxNo.length();
            MaxNo = "0000000000000000000000000" + MaxNo;
          }
          else {
            MaxNo = "00000000000000000000000001";
            LenMaxNo = 1;
          }
        }
        else {
        }
        dbset = null;
      }
      else {
      }
      MaxNo = MaxNo.substring(25 - FieldLen + LenMaxNo);
    }
    catch (Exception ex) {
      System.err.println(ex.getMessage());
    }
    return MaxNo;
  }


  /**
   * 功能或作用：获取当前服务器日期（字符型）
   * @return 当前日期（字符型）
   */
  public String GetDateAsStr() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    String mDateTime = formatter.format(cal.getTime());
    return (mDateTime);
  }
  /**
   * 功能：得到已经上传的附件数
   * @param strFLOWID 流程标识
   * @param strFORMID 表单ID
   * @return returnValue 返回附件数
   */
  public int GetAttNum(String strFLOWID, String strFORMID) {
    int returnValue = 0;
    String strsql = "";
    strsql = "Select count(ID) as NUM From BPIP_ATT where FLOWID ='"+strFLOWID+"' and FORMID='"+strFORMID+"'";
    dbSet dbset = dbengine.QuerySQL(strsql);
    if (dbset != null && dbset.RowCount() > 0) {
        returnValue = dbset.Row(0).Column("NUM").getInteger();
        dbset=null;//赋空值
    }
    return returnValue;
  }

  /**
    * 获取整个目下的文件的大小
    * @param f File
    * @return long
    */
   public long getFileSize (String f)
   {
       File objFile = new File(f.toString());
       long filesize = objFile.length();
       filesize = filesize / 1024;
       return filesize;
   }

}
