package zr.zrpower.ejb.sys;

import zr.zrpower.common.util.*;
import zr.zrpower.common.db.*;
import zr.zrpower.entity.sys.BPIP_UNIT;
import java.util.ArrayList;

/**
 * <p>Title: ZRPower</p>
 * <p>Description: ZRPowerEJB服务</p>
 * <p>Copyright: Copyright (c) 2015</p>
 * <p>Company: </p>
 */
public class UnitService
  {
  static private Log log;
  dbEngine dbengine;
  static private int clients=0;

  public UnitService()
  {
    dbengine = new dbEngine(SysPreperty.getProperty().MainDataSource,
                              SysPreperty.getProperty().IsConvert);
    dbengine.initialize();

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

    }
    clients++;
  }


  /**
   * 保存新单位信息
   * @param Unit BPIP_UNIT   新单位信息实体
   * @return FunctionMessage  保存是否成功,成功或是失败消息
   */
  public FunctionMessage AddUnit(BPIP_UNIT Unit) {
    FunctionMessage fm = new FunctionMessage(1);
    String  strSQL = "";
    try {
      //如果传入的单位实体不为空，构建新数据行，提交给数据库控制类执行插入数据库操作。
      if (Unit != null) {
          strSQL = "Select UnitName From BPIP_Unit Where UnitID='"+
            Unit.getUNITID()+"'";
        dbSet mdbset = dbengine.QuerySQL(strSQL);
        if (mdbset != null) {
          fm.setMessage("已有单位使用【"+Unit.getUNITID()+"】这个编号了，请输入一个新单位代码！");
          mdbset = null;
        }
        else {
            Unit.setSTATE("0"); //设置单位状态为未删除
            dbRow row = Unit.getData();
            if (dbengine.ExecuteInsert(row)) {
              fm.setResult(true);
              fm.setMessage(FunctionMessage.MSG_SUCCEED_SAVE);
            }
            else {
              fm.setMessage(FunctionMessage.MSG_ERROR_DATASERVER);
            }
            row = null;
        }
      }
    }
    catch (Exception ex) {
      log.WriteErrorLog("保存新单位信息", ex.toString());
      fm.setMessage(FunctionMessage.MSG_ERROR_APPSERVER);
    }
    return fm;
  }

  /**
   * 删除单位
   * @param DepID String
   */
  public boolean  DeleteUnit(String UnitID) {
     boolean revalue = true;
    StringWork sw = new StringWork();
    String  strSQL = "";
    try {
      if (UnitID != null) {
        //检查要删除的单位下是否有下级单位
        strSQL = "Select count(*) as UnitCount From BPIP_Unit Where State<>'1' and UnitID like '"+ sw.CutLastZero(UnitID, 2)+"%'";
        dbSet dsTmp = dbengine.QuerySQL(strSQL);
        int iDepCount = dsTmp.Row(0).Column("UnitCount").getInteger();
        if (iDepCount < 2) {
          //检查要删除的单位是否有活动用户
          strSQL = "Select count(*) as userCount From BPIP_USER Where USERSTATE<>'1' and UnitID='"+ UnitID+"'";
          dsTmp = null;
          dsTmp = dbengine.QuerySQL(strSQL);
          int iUserCount = dsTmp.Row(0).Column("userCount").getInteger();
          if (iUserCount < 1) {
            strSQL = "Update BPIP_UNIT set State='1' Where UnitID='"+ UnitID+"'";
            if (dbengine.ExecuteSQL(strSQL)) {
              log.WriteLog("单位编号为:"+UnitID+"，已被成功删除！");
            }

          }
          else {
              log.WriteLog("删除失败，该单位有"+Integer.toString(iUserCount - 1)+"个用户，系统不允许删除！");
              revalue = false;
          }
        }
        else {
              log.WriteLog("删除失败，该单位有"+Integer.toString(iDepCount - 1)+"个下级单位，系统不允许删除！");
              revalue = false;
        }
        dsTmp = null;
      }

    }
    catch (Exception ex) {
      log.WriteErrorLog("删除单位", ex.toString());
      revalue = false;
    }

    return revalue;
  }

  /**
   * 编辑单位
   * @param Unit BPIP_UNIT  单位信息实体
   * @return boolean        保存是否成功,成功或是失败消息
   */
  public boolean UpdateUnit(BPIP_UNIT Unit) {
    boolean returnValue = false; //定义返回值
    try {
      //如果传入的单位实体不为空，构建新数据行，提交给数据库控制类执行更新数据库操作。
      if (Unit != null) {
        dbRow row = Unit.getData();
        returnValue = dbengine.ExecuteEdit(row,"UnitID='"+Unit.getUNITID()+"'");
        row = null;
      }
      else {
        log.WriteLog("编辑单位", "编辑失败，单位资料为空 ");
      }
    }
    catch (Exception ex) {
      log.WriteErrorLog("编辑单位", ex.toString());
    }
    return returnValue;
  }

  /**
   * 根据单位编号获取单位名称
   * @param UnitID String   单位编号
   * @return String
   */
  public String GetUnitName(String UnitID) {
    String returnValue = null;
    String strSQL = "";
    strSQL = "Select UnitName  From BPIP_UNIT Where UnitID = '"+UnitID+"'";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if (dbset != null && dbset.RowCount() > 0) {
      returnValue = dbset.Row(0).Column("UnitName").getString();
      dbset = null;
    }
    return returnValue;
  }


  /**
   * 根据单位编号获取单位信息
   * @param UnitID String
   * @return BPIP_UNIT
   */
  public BPIP_UNIT GetUnit(String UnitID) {
    BPIP_UNIT returnValue = null;
    String  strSQL = "";
    strSQL = "Select * From BPIP_UNIT Where UnitID = '"+UnitID+
        "' Order By UnitID";
    dbSet dbset = dbengine.QuerySQL(strSQL);
    if (dbset != null) {
      if (dbset.RowCount() > 0) {
        returnValue = new BPIP_UNIT();
        returnValue.fullData(dbset.Row(0));
      }
      dbset = null;
    }
    return returnValue;
  }


/**
     * 获取所有已经删除的单位
     * @param  UnitID String  行政区划
     * @return BPIP_UNIT[]
*/
public BPIP_UNIT[] GetRecoveryUnitList() {
      BPIP_UNIT[] resultValue = null;
      String  strSQL = "";
      strSQL = "Select * From BPIP_UNIT Where  State='1'  Order By ORDERCODE,UnitID";
      dbSet set = dbengine.QuerySQL(strSQL);
      if (set != null) {
        if (set.RowCount() > 0) {
          resultValue = new BPIP_UNIT[set.RowCount()];
          for (int i = 0; i < set.RowCount(); i++) {
            resultValue[i] = new BPIP_UNIT();
            resultValue[i].fullData(set.Row(i));
          }
        }
        set = null;
      }
      return resultValue;
  }
  /**
  * 功能或作用：彻底删除单位
  * @param
  * @return 返回
  */
 public boolean DelUnit(String strMenu_No) {
   boolean strResult = false;
   ArrayList arrList_strMenu_No = new ArrayList();
   String  strSQL = "";
    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 = "Select UserID  From BPIP_USER Where UnitID = '"+arrList_strMenu_No.get(i).toString()+"'";
         dbSet dbset = dbengine.QuerySQL(strSQL);
         if (dbset != null && dbset.RowCount() > 0) {
           for(int j=0;j<dbset.RowCount();j++) {
            String[] strSq1s = new String[4];
            strSq1s[0] = "delete from BPIP_USER_PHOTO  Where UserID='"+dbset.Row(j).Column("UserID").getString()+"'";
            strSq1s[1] = "delete from BPIP_USER_REMOVE Where UserID='"+dbset.Row(j).Column("UserID").getString()+"'";
            strSq1s[2] = "delete from BPIP_USER_ROLE  Where UserID='"+dbset.Row(j).Column("UserID").getString()+"'";
            strSq1s[3] = "delete from BPIP_USER_IDEA  Where USER_NO='"+dbset.Row(j).Column("UserID").getString()+"'";
            strResult = dbengine.ExecuteSQLs(strSq1s);
           }
           dbset = null;
         }
        String[] strSq12s = new String[2];
        strSq12s[0] = "delete from BPIP_USER where UNITID = '"+arrList_strMenu_No.get(i).toString()+"'";
        strSq12s[1] = "delete from BPIP_UNIT where UNITID = '"+arrList_strMenu_No.get(i).toString()+"'";
        strResult = dbengine.ExecuteSQLs(strSq12s);
      }
    }
     return strResult;

}
   /**
    * 功能或作用：还原单位单位
    * @param
    * @return 返回
    */
public boolean RestoreUnit(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_UNIT set State='0' where UNITID = '"+
              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;
}

//得到显示树(new)
 public BPIP_UNIT[] GetNewTreeShowList() {
       BPIP_UNIT[] resultValue = null;
       String strSQL = "";
       strSQL = "Select * From BPIP_UNIT  Where  State='0' Order By ORDERCODE,UnitID";
       dbSet set = dbengine.QuerySQL(strSQL);
       if (set != null && set.RowCount() > 0) {
           resultValue = new BPIP_UNIT[set.RowCount()];
           for (int i = 0; i < set.RowCount(); i++) {
             resultValue[i] = new BPIP_UNIT();
             resultValue[i].fullData(set.Row(i));
           }
           set = null;
       }
       return resultValue;
  }
//得到树显示的一级部门--
public BPIP_UNIT[] GetTreeShowList() {
      BPIP_UNIT[] resultValue = null;
      String strSQL = "";
      strSQL = "Select * From BPIP_UNIT  Where  State='0' And UnitID like '%0000000000' Order By ORDERCODE,UnitID";
      dbSet set = dbengine.QuerySQL(strSQL);
      if (set != null && set.RowCount() > 0) {
          resultValue = new BPIP_UNIT[set.RowCount()];
          for (int i = 0; i < set.RowCount(); i++) {
            resultValue[i] = new BPIP_UNIT();
            resultValue[i].fullData(set.Row(i));
          }
          set = null;
      }
      return resultValue;
  }
  //得到当前部门的下级部门--
  public BPIP_UNIT[] GetTreeSubList(String ID) {
        BPIP_UNIT[] resultValue = null;
        String strSQL = "";
        String AZ = "";
        String ZID = "";
        int IDLen = 0;

        StringWork sw = new StringWork();
        ZID = sw.CutLastZero(ID,2);//从后以2位的方式去掉00
        IDLen = ZID.length();

        for (int i=0;i<(10-IDLen);i++)
        {
            AZ = AZ +"0";
        }

        strSQL = "Select * From BPIP_UNIT  Where  State='0' And UnitID<>'"+ID+"' And UnitID like '"+ZID+"%' And UnitID like '%"+AZ+"'   Order By ORDERCODE,UnitID";
        dbSet set = dbengine.QuerySQL(strSQL);
        if (set != null && set.RowCount() > 0) {
            resultValue = new BPIP_UNIT[set.RowCount()];
            for (int i = 0; i < set.RowCount(); i++) {
              resultValue[i] = new BPIP_UNIT();
              resultValue[i].fullData(set.Row(i));
            }
            set = null;
        }
        return resultValue;
  }

  //生成新增部门的编码--
  //strTYPE为1时生成同级单位，2时生成下级单位
  public String AddCode(String strTYPE,String strUNITID)
  {
      String strReValue = "";
      String strSQL = "";
      String SID = "";
      String AZ = "";
      String MaxNo = "";
      StringWork sw = new StringWork();
      String ZID = sw.CutLastZero(strUNITID,2);//从后以2位的方式去掉00

      if (strTYPE.equals("1"))//增加同级单位
      {
         if (ZID.length()>2)
         {
            SID = ZID.substring(0,ZID.length()-2);
         }
         for (int i=0;i<(10-SID.length());i++)
         {
            AZ = AZ +"0";
         }
         strSQL = "select MAX(UNITID) AS MaxNo from BPIP_UNIT where UNITID like '"+SID+"%' and UNITID like '%"+AZ+"'";

      }else//增加下级单位
      {
         for (int i=0;i<(10-ZID.length());i++)
         {
            AZ = AZ +"0";
         }
         strSQL = "select MAX(UNITID) AS MaxNo from BPIP_UNIT where UNITID like '"+ZID+"%' and UNITID like '%"+AZ+"'";
      }
      dbSet set = dbengine.QuerySQL(strSQL);
      if (set != null && set.RowCount() > 0)
      {
          MaxNo = set.Row(0).Column("MaxNo").getString();
          if (MaxNo==null){MaxNo="";}
      }
      if (MaxNo.length()==0)
      {
         strReValue = "010000000000";
      }
      else
      {
         MaxNo = sw.CutLastZero(MaxNo,2);
         if (strTYPE.equals("2"))//增加下级单位
         {
            if (ZID.length() == MaxNo.length())//没有子单位
            {
                MaxNo = MaxNo + "01";
                strReValue = MaxNo;
                for (int i=0;i<(12-MaxNo.length());i++)
                {
                     strReValue = strReValue +"0";
                }
            }else
            {
                strReValue = GetMaxUnitID(MaxNo);
            }
         }else
         {
           strReValue = GetMaxUnitID(MaxNo);
         }
      }

      return strReValue;
  }

  //得到单位编号---
  private String GetMaxUnitID(String ID) {
    String MaxNo = "";
    int LenMaxNo = 0;
    String AZ = "";
    try {
        MaxNo = String.valueOf(Integer.parseInt(ID) + 1);
        LenMaxNo = MaxNo.length();
        if (LenMaxNo%2 == 1)
        {
          MaxNo = "0"+MaxNo;
          LenMaxNo = LenMaxNo + 1;
        }
        for (int i=0;i<(12-LenMaxNo);i++)
        {
            AZ = AZ +"0";
        }
        MaxNo = MaxNo + AZ;
    }
    catch (Exception ex) {
      log.WriteLog("GetMaxUnitID:"+ex.getMessage());
    }
    return MaxNo;
  }
  //得到最小的单位编号---
  public String GetMinUnitID() {
      String strReValue = "";
      String strSQL = "";
      strSQL = "select MIN(UNITID) AS MinNo from BPIP_UNIT where STATE = '0'";
      dbSet set = dbengine.QuerySQL(strSQL);
      if (set != null && set.RowCount() > 0)
      {
          strReValue = set.Row(0).Column("MinNo").getString();
          if (strReValue==null){strReValue="";}
      }
      return strReValue;
  }

}
