package com.jw.app.unit.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.operations.FileOperation;
import org.apache.commons.vfs2.operations.FileOperations;
import org.apache.poi.hssf.record.formula.functions.Row;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;

import com.gaowj.business.action.BasicAction;
import com.gaowj.business.comp.BusinessManager;
import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.Encipher;
import com.gaowj.business.util.Java_tool;
import com.gaowj.business.util.PropUtil;
import com.gaowj.business.util.RequestUtils;
import com.gaowj.business.util.SessionUtil;
import com.gaowj.business.vfs.FileUtil;
import com.jw.app.business.MappingBusiness;
import com.jw.app.business.PushDataBusiness;
import com.jw.app.business.UnitBusiness;
import com.jw.app.business.UserBusiness;
import com.gaowj.business.SystemOpeBusiness;
import com.gaowj.service.client.remote.util.AuthenticateUtil;
import com.gaowj.service.client.utils.Native2AsciiUtils;
import com.gaowj.service.client.utils.PbeEncrypt;
import com.gaowj.service.client.utils.httpClientPostData;
import com.gaowj.service.client.utils.jsonFormatMap;
import com.gaowj.util.Factory;
import com.gaowj.util.Ldap;
import com.gaowj.util.LdapOuUtils;
import com.gaowj.util.TakeUnitsUtils;
import com.jw.app.business.utils.QueryParamUtil;
import com.jw.app.business.utils.Status;
import com.jw.app.pushData.util.PushDataUtils;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.WritableWorkbook;


public class actAction extends BasicAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5560714628178697924L;

	private JSONObject jsonObject = new JSONObject();

	private File leftFile;

	private File appFile;

	private String loginuserCode = SessionUtil.getCode();

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public File getLeftFile() {
		return leftFile;
	}

	public void setLeftFile(File leftFile) {
		this.leftFile = leftFile;
	}

	public File getAppFile() {
		return appFile;
	}

	public void setAppFile(File appFile) {
		this.appFile = appFile;
	}

	public String insertUnit() throws BusinessException {

		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String flag = "";
		String pushflag = PropUtil.getValue("pushflag","quartz_service","0");
		String ldapflag = PropUtil.getValue("flag","quartz_service","0");
		jsonObject = new JSONObject();
		try {
			entity = QueryParamUtil.StringToDate(entity);
			
			// 恢复删除的数据
			if (entity.get("FLAG") != null
					&& entity.get("FLAG").toString().equals("1")) {
				entity.put("DELETE_FLAG", "0");
				flag = entity.get("FLAG").toString();
				entity.remove("FLAG");
				
				//去除不要更新的字段
				entity.remove("OPETYPE");
				entity.remove("OLD_ORDER_ID");
				entity.remove("IS_ORDER");
				entity.remove("ORDER_ID");
				//修改
				business.update_unit(entity);
			}
			else {
				Map<String, Object> query = new HashMap<String, Object>();
				query.put("UNIT_ID", entity.get("UNIT_ID").toString());
				int count = business.listCount_unit(query);
				// 编号存在
				if (count > 0) {
					query.put("DELETE_FLAG", "1");
					count = 0;
					count = business.listCount_unit(query);
					// 该编号已被删除
					if (count > 0) {
						jsonObject.putAll(Status
								.getStatus(Status.INSERT_ERR_DELETE));
						return "json";
					} else {
						jsonObject.putAll(Status
								.getStatus(Status.INSERT_ERR_UNITID));
						return "json";
					}
				} else {
					//排序
					String is_orders = (String) entity.get("IS_ORDER");
					String is_order[] = is_orders.split("\\_");
					Integer a = Integer.parseInt(is_order[0]);
					Integer b = Integer.parseInt(is_order[2]);
					//去除不要更新的字段
					entity.remove("OPETYPE");
					entity.remove("OLD_ORDER_ID");
					entity.remove("IS_ORDER");
					entity.put("ORDER_ID",a);
					//新增
					business.insert_unit(entity);
					//
					String is_swith = is_order[1];
					List<Map<String, Object>> update_unit_data = UnitSetOrder(a,b,is_swith);
					Map<String, Object> newdata = new HashMap<String,Object>();
					newdata.put("UUID", entity.get("UUID"));
					newdata.put("ORDER_ID", b);
					update_unit_data.add(newdata);
					if(update_unit_data.size()>0){
						for(Map<String, Object> udata : update_unit_data){
							business.update_unit(udata);
						}
					}
					
				}
			}
			
            //ldap同步操作
			if(ldapflag.equals("1")){
				Map<String, Object> mapuuid = business.list_unit_ldap_uuid(entity.get("UNIT_ID").toString());
				String unituuid = mapuuid.get("UUID").toString();
				Ldap ldap = Factory.createInstance();
				ldap.connect();
				String searchFilter = "ou=" + unituuid;
				String searchBase = PropUtil.getValue("root","quartz_service","0000") + "," + PropUtil.getValue("rootrdn","quartz_service","0000");
				List<Map<String, Object>> result = ldap.searchAll(searchFilter, searchBase, null);
				if(result.isEmpty()){
					//如果组织在ldap里面没有，则添加
					Map<String, Object> map = business.list_unit_ldap_ou(unituuid);
					System.out.println("-------uuid"+unituuid);
					System.out.println("-------map"+map);
					String o = PropUtil.getValue("root","quartz_service","0000").substring(2);
					if(map.get("PARENT_ID").equals(o)){
						String rdn = "ou=" + unituuid + "," + searchBase;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", map.get("NAME"));
	        			attrs.put("st", map.get("PARENT_ID"));
	        			attrs.put("street", map.get("UNIT_ID"));
	        			ldap.add(rdn, attrs);
					}else{
						String searchFilter1 = "ou=" + map.get("PARENT_ID");
						List<Map<String, Object>> result1 = ldap.searchAll(searchFilter1, searchBase, null);
						System.out.println("------result1"+ result1);
						String rdn = "ou=" + unituuid + "," + result1.get(0).get("rdn") + "," + searchBase;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", map.get("NAME"));
	        			attrs.put("st", map.get("PARENT_ID"));
	        			attrs.put("street", map.get("UNIT_ID"));
	        			ldap.add(rdn, attrs);
					}
				}
			}
			
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager
					.getBusiness(SystemOpeBusiness.class);
			if (flag.equals(""))
				sysbusiness.insert_logBusiness("insertUnit", "" + entity,
						"增加单位记录", (String) entity.get("UUID"), (String) entity
								.get("NAME"), "JW_APPS_UICM_UNIT");
			else {
				sysbusiness.insert_logBusiness("updateUnit", "" + entity,
						"恢复单位记录", (String) entity.get("UUID"), (String) entity
								.get("NAME"), "JW_APPS_UICM_UNIT");
			}
			//
			// 单位推送
			if(pushflag.equals("1")){
				Map<String, Object> p_unit_query = new HashMap<String, Object>();
				p_unit_query.put("UUID", entity.get("UUID"));
				List<Map<String, Object>> p_unit = business.list_unit(p_unit_query);
				if (p_unit.size() > 0) {
					// 推送单位日志
					if (flag.equals(""))
						sysbusiness.insert_logBusiness("pushInsertUnit", ""
								+ entity, "推送新增单位记录", (String) entity.get("UUID"),
								(String) entity.get("NAME"), "JW_APPS_UICM_PUSH");
					else {
						sysbusiness.insert_logBusiness("pushUpdateUnit", ""
								+ entity, "推送恢复单位记录", (String) entity.get("UUID"),
								(String) entity.get("NAME"), "JW_APPS_UICM_PUSH");
					}
					ThreadUtil thread = new ThreadUtil(QueryParamUtil
							.DateToString(p_unit.get(0)));
					thread.start();
				}
			}
			//
			jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String updateUnit() throws BusinessException {

		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String pushflag = PropUtil.getValue("pushflag","quartz_service","0");
		String ldapflag = PropUtil.getValue("flag","quartz_service","0");
		try {
			//排序
			String is_orders = (String) entity.get("IS_ORDER");
			String is_order[] = is_orders.split("\\_");
			Integer a = Integer.parseInt(is_order[0]);
			Integer b = Integer.parseInt(is_order[2]);
			int maxrderid =  business.list_max_order(null);
			if(b>maxrderid){
				b=maxrderid;
			}else if(b<=0){
				b=1;
			}
			String is_swith = is_order[1];
			List<Map<String, Object>> update_unit_data = UnitSetOrder(a,b,is_swith);
			if(update_unit_data.size()>0){
				for(Map<String, Object> udata : update_unit_data){
					business.update_unit(udata);
				}
			}
			//去除不要更新的字段
			entity.remove("OPETYPE");
			entity.remove("OLD_ORDER_ID");
			entity.remove("IS_ORDER");
			entity.remove("ORDER_ID");
			//修改
			entity = QueryParamUtil.StringToDate(entity);
			business.update_unit(entity);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("updateUnit", "" + entity, "修改单位记录",(String) entity.get("UUID"), (String) entity.get("NAME"),"JW_APPS_UICM_UNIT");
			//
			// 单位推送
			if(pushflag.equals("1")){
				Map<String, Object> p_unit_query = new HashMap<String, Object>();
				p_unit_query.put("UUID", entity.get("UUID"));
				List<Map<String, Object>> p_unit = business.list_unit(p_unit_query);
				if (p_unit.size() > 0) {
					// 推送单位日志
					entity.put("USERID", "System");
					sysbusiness.insert_logBusiness("pushUpdateUnit", "" + entity,"推送单位更新记录", (String) entity.get("UUID"),(String) entity.get("NAME"), "JW_APPS_UICM_PUSH");
					ThreadUtil thread = new ThreadUtil(QueryParamUtil.DateToString(p_unit.get(0)));
					thread.start();
				}
			}
			//ldap同步操作
			if(ldapflag.equals("1")){
				String unituuid = (String) entity.get("UUID");
				String parentid = (String) entity.get("PARENT_ID");
				System.out.println("------parentid" + parentid);
				Ldap ldap = Factory.createInstance();
				ldap.connect();
				String searchFilter = "ou=" + unituuid;
				String searchFilterou = "ou=" + parentid;
				String searchBase = PropUtil.getValue("root","quartz_service","0000") + "," + PropUtil.getValue("rootrdn","quartz_service","0000");
				List<Map<String, Object>> result = ldap.searchAll(searchFilter, searchBase, null);
				if(result.get(0).get("st").equals(parentid)){
					String rdn = (String) result.get(0).get("rdn") + "," + searchBase;
					Map<String, Object> mapou = new HashMap<String, Object>();
					mapou.put("st", parentid);
					mapou.put("description", entity.get("NAME"));
					mapou.put("street", entity.get("UNIT_ID"));
					for(Map.Entry<String, Object> entry : mapou.entrySet()){
						ldap.update(rdn, entry.getKey(), entry.getValue());
					}
				}else{
					if(parentid.equals("A")){
						//更新换成其他上级部门，先插入，后删除
						String rdn = "ou=" + unituuid + "," + searchBase;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", entity.get("NAME"));
	        			attrs.put("st", parentid);
	        			attrs.put("street", entity.get("UNIT_ID"));
	        			ldap.add(rdn, attrs);
	        			ldap.delete((String) result.get(0).get("rdn") + "," + searchBase);
					}else{
						List<Map<String, Object>> resultou = ldap.searchAll(searchFilterou, searchBase, null);
						String rdn = "ou=" + unituuid + "," + (String) resultou.get(0).get("rdn") + "," + searchBase;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", entity.get("NAME"));
	        			attrs.put("st", parentid);
	        			attrs.put("street", entity.get("UNIT_ID"));
	        			ldap.add(rdn, attrs);
	        			ldap.delete((String) result.get(0).get("rdn") + "," + searchBase);
					}
				}	
			}
			jsonObject.putAll(Status.getStatus(Status.UPDATE_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.UPDATE_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String deleteUnit() throws BusinessException {

		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String deletekey = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(deletekey);
		String pushflag = PropUtil.getValue("pushflag","quartz_service","0");
		String ldapflag = PropUtil.getValue("flag","quartz_service","0");
		try {
			List<Map<String, Object>> list_name_unit = business.list_name_unit(ListKey);
			business.delete_unit(ListKey);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("deleteUnit", "" + ListKey,"删除单位记录", ListKey.toString(), list_name_unit.toString(),"JW_APPS_UICM_UNIT");
			//
			// 单位推送
			if(pushflag.equals("1")){
				for (String uuid : ListKey) {
					Map<String, Object> u_query = new HashMap<String, Object>();
					u_query.put("UUID", uuid);
					List<Map<String, Object>> delete_user = business.list_unit(u_query);
					if (delete_user.size() > 0) {
						// 推送单位日志
						sysbusiness.insert_logBusiness("pushDeleteUnit", ""+ ListKey, "推送单位删除记录", ListKey.toString(),list_name_unit.toString(), "JW_APPS_UICM_PUSH");
						ThreadUtil thread = new ThreadUtil(QueryParamUtil.DateToString(delete_user.get(0)));
						thread.start();
					}
				}
			}		
			//ldap同步操作
			if(ldapflag.equals("1")){
				for(String unituuid : ListKey){
					Ldap ldap = Factory.createInstance();
					ldap.connect();
					String searchFilter = "ou=" + unituuid;
					System.out.println("-------unitdele"+unituuid);
					String searchBase = PropUtil.getValue("root","quartz_service","0000") + "," + PropUtil.getValue("rootrdn","quartz_service","0000");
					List<Map<String, Object>> result = ldap.searchAll(searchFilter, searchBase, null);
					String o = PropUtil.getValue("root","quartz_service","0000").substring(2);
					if(result.get(0).get("st").equals(o)){
						String rdn = "ou=" + unituuid + "," + searchBase;
						ldap.delete(rdn);
					}else{
						String rdn = result.get(0).get("rdn") + "," + searchBase;
						ldap.delete(rdn);
					}		
				}
			}		
			jsonObject.putAll(Status.getStatus(Status.DELETE_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.DELETE_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String viewUnitLog() throws BusinessException {

		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			entity = QueryParamUtil.StringToDate(entity);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("viewUnitLog", "" + entity,"查看单位记录", (String) entity.get("UUID"), (String) entity.get("NAME"), "JW_APPS_UICM_UNIT");
			//
			jsonObject.putAll(Status.getStatus(Status.LOG_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.LOG_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String uploadUnit() throws BusinessException {
		String upPath = request.getSession().getServletContext().getRealPath(
				"/uploadFile/apps/unit");
		super.setUserUploadFilePath(upPath);
		return super.upload();
	}
	
	public String updateUnitInitOrder() throws BusinessException {

		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			entity = QueryParamUtil.StringToDate(entity);
			List<Map<String, Object>> p_unit_data = business.list_uuid_order(entity);
			int i=0;
			for(Map<String, Object> map : p_unit_data){
				map.put("ORDER_ID", i++);
				business.update_unit(map);
			}
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("updateUnit", "" + entity, "初始化单位排序号",(String) entity.get("UUID"), (String) entity.get("NAME"),"JW_APPS_UICM_UNIT");
			//
			jsonObject.putAll(Status.getStatusSuccessMessage("排序初始化完成"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("排序初始化失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	public String updateUnitSetOrder() throws BusinessException {

		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			entity = QueryParamUtil.StringToDate(entity);
			String is_orders = (String) entity.get("IS_ORDER");
			String is_order[] = is_orders.split("\\_");
			Integer a = Integer.parseInt(is_order[0]);
			Integer b = Integer.parseInt(is_order[2]);
			String is_swith = is_order[1];
			List<Map<String, Object>> update_unit_data = UnitSetOrder(a,b,is_swith);
			if(update_unit_data.size()>0){
				for(Map<String, Object> udata : update_unit_data){
					business.update_unit(udata);
				}
			}
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("updateUnit", "" + entity, "更换单位排序号",(String) entity.get("UUID"), (String) entity.get("NAME"),"JW_APPS_UICM_UNIT");
			//
			jsonObject.putAll(Status.getStatusSuccessMessage("更换单位排序完成",String.valueOf(b)));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("更换单位排序失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	private List<Map<String, Object>> UnitSetOrder(Integer a,Integer b,String is_swith){
		List<Map<String, Object>> update_unit_data = new ArrayList<Map<String, Object>>();
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> query = new HashMap<String,Object>();
		if(a>b){
			query.put("START_ORDER", b);
			query.put("END_ORDER", a);
			List<Map<String, Object>> p_unit_data = business.list_unit(query);
			for(Map<String, Object> data:p_unit_data){
				Map<String, Object> update_unit_map = new HashMap<String, Object>();
				Integer s_order = null;
				if(data.get("ORDER_ID") instanceof BigDecimal){
					s_order = ((BigDecimal) data.get("ORDER_ID")).intValue();
				}else{
					s_order = (Integer) data.get("ORDER_ID");
				}
				update_unit_map.put("UUID", data.get("UUID"));
				if(is_swith.equals("up")){
					if(s_order>=(b+0) && s_order<=(a-1)){
						s_order +=1;
						update_unit_map.put("ORDER_ID", s_order);
					}else if(s_order==(a+0)){
						update_unit_map.put("ORDER_ID", b);
					}
					update_unit_data.add(update_unit_map);
				}else if(is_swith.equals("down")){
					if(s_order>=(b+1) && s_order<=(a-1)){
						s_order +=1;
						update_unit_map.put("ORDER_ID", s_order);
					}else if(s_order==(a+0)){
						update_unit_map.put("ORDER_ID", b+1);
					}
					update_unit_data.add(update_unit_map);
				}else if(is_swith.equals("exchange")){
					if(s_order == (a+0)){
						update_unit_map.put("ORDER_ID", b);
					}else if(s_order == (b+0)){
						update_unit_map.put("ORDER_ID", a);
					}
					update_unit_data.add(update_unit_map);
				}
			}
			
		}else if(a<b){
			query.put("START_ORDER", a);
			query.put("END_ORDER", b);
			List<Map<String, Object>> p_unit_data = business.list_unit(query);
			for(Map<String, Object> data:p_unit_data){
				Map<String, Object> update_unit_map = new HashMap<String, Object>();
				Integer s_order = null;
				if(data.get("ORDER_ID") instanceof BigDecimal){
					s_order = ((BigDecimal) data.get("ORDER_ID")).intValue();
				}else{
					s_order = (Integer) data.get("ORDER_ID");
				}
				update_unit_map.put("UUID", data.get("UUID"));
				if(is_swith.equals("up")){
					if(s_order>=(a+1) && s_order<=(b-1)){
						s_order -=1;
						update_unit_map.put("ORDER_ID", s_order);
					}else if(s_order==(a+0)){
						update_unit_map.put("ORDER_ID", b-1);
					}
					update_unit_data.add(update_unit_map);
				}else if(is_swith.equals("down")){
					if(s_order>=(a+1) && s_order<=(b+0)){
						s_order -=1;
						update_unit_map.put("ORDER_ID", s_order);
					}else if(s_order==(a+0)){
						update_unit_map.put("ORDER_ID", b);
					}
					update_unit_data.add(update_unit_map);
				}else if(is_swith.equals("exchange")){
					if(s_order == (a+0)){
						update_unit_map.put("ORDER_ID", b);
					}else if(s_order == (b+0)){
						update_unit_map.put("ORDER_ID", a);
					}
					update_unit_data.add(update_unit_map);
				}
			}
			
		}
		return update_unit_data;
	}

	private class ThreadUtil extends Thread {

		private Map<String, Object> map = null;
		private Java_tool jt = new Java_tool();

		public ThreadUtil(Map<String, Object> map) {
			if (map == null)
				map = new HashMap<String, Object>();
			this.map = map;

		}

		private void pushData(Map<String, Object> data) {
			
			PushDataUtils pd = new PushDataUtils();
			String jsondata = pd.getPushUnitData(data);
			// 获取要推送人员数据的单位
			String loginuser_depart = AuthenticateUtil.getEndpoint("loginuser_depart");//提取所有应用系统的接口数据
			String pushdata_default = AuthenticateUtil.getEndpoint("pushdata_default");//人员和单位未选择要推送应用时是否全推1=全推0=不推
			SystemOpeBusiness business = BusinessManager.getBusiness(SystemOpeBusiness.class);
			Map<String, Object> query = new HashMap<String, Object>();
			query.put("ISPUSH", "1");
			query.put("EMDEPART", loginuser_depart);
			List<Map<String, Object>> s_user = business.listLoginServiceUserInfo(query);
			//提取当前人员数据要推送的所有应用ID，如为空则提取是否全推的开关值，不为空则过滤s_user
			List<Map<String, Object>> s_user_choice = new ArrayList<Map<String, Object>>();
			
			//比对往s_user_choice加数据
			PushDataBusiness pushdata_business = BusinessManager.getBusiness(PushDataBusiness.class);
			Map<String, Object> query_use = new HashMap<String, Object>();
			query_use.put("PUSH_DATA_ID", data.get("UUID"));
			query_use.put("TYPE", "2");
			List<Map<String, Object>> s_user_use = pushdata_business.list_pushApp(query_use);
			if(s_user_use.size()>0){
			  for(Map<String, Object> n:s_user){
				int i = 0;
				for(Map<String, Object> m:s_user_use){
					if(StringUtils.equalsIgnoreCase((String)m.get("CLIENT_CODE"), (String)n.get("CODE"))){
						i=0;
						break;
					}else{
						i++;
					}
				}
				if(i == 0){
					s_user_choice.add(n);
				}
			  }
			}
			//
			
			if(s_user_choice.size()==0 && (pushdata_default!=null && pushdata_default.trim().equals("1"))){
				s_user_choice.addAll(s_user);
			}
			//
			for (Map<String, Object> s : s_user_choice) {
				if (s.get("PUSH_UNIT_URL") == null || s.get("PUSH_UNIT_URL").toString().trim().length() == 0) {
					System.out.println("未注册单位推送地址!");
					continue;
				}
				//推送加密字段判断
				if(s.get("PUSH_ENCRYPT") == null || s.get("PUSH_ENCRYPT").toString().equals("0")){
					//不加密
					jsondata = Native2AsciiUtils.native2Ascii(pd.getPushUnitData(data));
				}else if (s.get("PUSH_ENCRYPT").toString().equals("1")){
					//base64加密
					jsondata = new BASE64Encoder().encode(Native2AsciiUtils.native2Ascii(pd.getPushUnitData(data)).getBytes());
				}else if (s.get("PUSH_ENCRYPT").toString().equals("2")){
					//特有加密
					try {
						jsondata = PbeEncrypt.encrypt(Native2AsciiUtils.native2Ascii(pd.getPushUnitData(data)), s.get("EMID").toString());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				httpClientPostData myhttp = new httpClientPostData();
				String ret = myhttp.requestSystem(
						(String) s.get("PUSH_LOGIN_URL"), 
						(String) s.get("PUSH_NAME"),
						(String) s.get("PUSH_PASS"), jsondata, 
						(String) s.get("PUSH_UNIT_URL"), 
						(String) s.get("PUSH_ENCODE"));
				System.out.println(ret);
				Map<String, Object> m = null;
				if (ret != null && ret.trim().length() > 0) {
					m = jsonFormatMap.getMap(ret);
				}
				if (m != null && m.get("NAME") != null && Integer.parseInt((String) m.get("NAME")) > 0) {
					System.out.println("用户[" + s.get("EMNAME") + "]推送成功!");
					// 将成功记录插入表
					Map<String, Object> pushData = new HashMap<String, Object>();
					pushData.put("PUSH_LOGIN_URL", s.get("PUSH_LOGIN_URL"));
					pushData.put("PUSH_NAME", s.get("PUSH_NAME"));
					pushData.put("PUSH_PASS", s.get("PUSH_PASS"));
					pushData.put("PUSH_URL", s.get("PUSH_UNIT_URL"));
					pushData.put("PUSH_ENCODE", s.get("PUSH_ENCODE"));
					pushData.put("CLIENT_CODE", s.get("CODE"));
					pushData.put("PUSH_DATA_ID", data.get("UUID"));
					pushData.put("ISFINISH", "1");
					pushData.put("CREATOR_ID", loginuserCode);
					pushData.put("TYPE", "2");// 类型:1=人员 2=单位

					PushDataBusiness pushData_business = BusinessManager.getBusiness(PushDataBusiness.class);
					Map<String, Object> p_query = new HashMap<String, Object>();
					p_query.put("CLIENT_CODE", pushData.get("CLIENT_CODE"));
					p_query.put("PUSH_DATA_ID", pushData.get("PUSH_DATA_ID"));
					List<Map<String, Object>> p_query_data = pushData_business.list_pushData(p_query);
					if (p_query_data == null || p_query_data.size() == 0) {
						pushData_business.insert_pushData(pushData);
					} else {
						pushData.put("UUID", p_query_data.get(0).get("UUID"));
						pushData_business.update_pushData(pushData);
					}
				} else {
					System.out.println("用户["
									+ s.get("EMNAME")
									+ "]推送失败,失败的数据将提交给作业[RemotePushUserJob],在调度任务中作定时推送!");
					// 把数据存到推送失败的临时表里
					Map<String, Object> pushData = new HashMap<String, Object>();
					pushData.put("PUSH_LOGIN_URL", s.get("PUSH_LOGIN_URL"));
					pushData.put("PUSH_NAME", s.get("PUSH_NAME"));
					pushData.put("PUSH_PASS", s.get("PUSH_PASS"));
					pushData.put("PUSH_URL", s.get("PUSH_UNIT_URL"));
					pushData.put("PUSH_ENCODE", s.get("PUSH_ENCODE"));
					pushData.put("CLIENT_CODE", s.get("CODE"));
					pushData.put("PUSH_DATA_ID", data.get("UUID"));
					pushData.put("CREATOR_ID", loginuserCode);
					pushData.put("TYPE", "2");// 类型:1=人员 2=单位

					PushDataBusiness pushData_business = BusinessManager.getBusiness(PushDataBusiness.class);
					Map<String, Object> p_query = new HashMap<String, Object>();
					p_query.put("CLIENT_CODE", pushData.get("CLIENT_CODE"));
					p_query.put("PUSH_DATA_ID", pushData.get("PUSH_DATA_ID"));
					List<Map<String, Object>> p_query_data = pushData_business.list_pushData(p_query);
					if (p_query_data == null || p_query_data.size() == 0) {
						pushData_business.insert_pushData(pushData);
					} else {
						pushData.put("UUID", p_query_data.get(0).get("UUID"));
						pushData_business.update_pushData(pushData);
					}

				}
			}
		}

		public void run() {
			System.out.println("同步单位开始,开始时间:" + jt.now_datetime());
			pushData(map);
			System.out.println("同步单位结束,结束时间:" + jt.now_datetime());
		}
	}
	//组织批量推送
	public String pushUnitRow(){
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		//System.out.println("--------entity"+entity);
		String key = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(key);
		//System.out.println("------list"+ListKey);
		String cilentid = (String) entity.get("CLIENT_CODE");
		List<String> Listcilentid = QueryParamUtil.StringToList(cilentid);
		//System.out.println("------set"+Listcilentid);
		for(String strid : Listcilentid){
			PushDataBusiness business2 = BusinessManager.getBusiness(PushDataBusiness.class);
			List<Map<String, Object>>  list = business2.list_pushData_one(strid);
			System.out.println("--------map" + list);
		}
		for(String str : ListKey){
			Map<String, Object> p_unit_query = new HashMap<String, Object>();
			p_unit_query.put("UUID", str);
			List<Map<String, Object>> p_unit = business.list_unit(p_unit_query);
			List<Map<String, Object>> list = business.list_unit_ldap();
			String unitPath = TakeUnitsUtils.getp(list, str);
			String[] unituuid = unitPath.split(",");
			String unitPath1 = "";
			for(int i = 0 ; i < unituuid.length - 1 ; i ++){
				System.out.println("--------unituuid"+unituuid[i]);
				Map<String, Object> listunit = business.list_unit_ldap_ou(unituuid[i]);
				unitPath1 = unitPath1 + "," + listunit.get("UNIT_ID");
			}
			if(unitPath1.length()>0){
				unitPath1 = unitPath1.substring(1,unitPath1.length());
			}
			System.out.println("-------unitpah1"+ unitPath1);
			for(Map<String, Object> data : p_unit){
				data.put("UNIT_PATH", unitPath1);
				ThreadUtil th = new ThreadUtil(data);
				System.out.println("------data"+ data);
				th.start();
				}
		}
		return "json";
	} 
	//部门推送新
	public String pushUnitO() throws BusinessException{
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
        System.out.println("推送开始......");
		String key = (String) entity.get("CODE");
		System.out.println("推送部门UUID:" + key);
		List<String> ListKey = QueryParamUtil.StringToList(key);
		String cilentid = (String) entity.get("CLIENT_CODE");
		List<String> Listcilentid = QueryParamUtil.StringToList(cilentid);
		List<Map<String, Object>> listclient = new ArrayList<Map<String,Object>>();
		for(String strid : Listcilentid){
			PushDataBusiness business2 = BusinessManager.getBusiness(PushDataBusiness.class);
			listclient = business2.list_pushData_one(strid);
		for(String str : ListKey){
			Map<String, Object> p_unit_query = new HashMap<String, Object>();
			p_unit_query.put("UUID", str);
			List<Map<String, Object>> p_unit = business.list_unit(p_unit_query);
			List<Map<String, Object>> list = business.list_unit_ldap();
			String unitPath = TakeUnitsUtils.getp(list, str);
			String[] unituuid = unitPath.split(",");
			String unitPath1 = "";
			for(int i = 0 ; i < unituuid.length - 1 ; i ++){
				Map<String, Object> listunit = business.list_unit_ldap_ou(unituuid[i]);
				unitPath1 = unitPath1 + "," + listunit.get("UNIT_ID");
			}
			if(unitPath1.length()>0){
				unitPath1 = unitPath1.substring(1,unitPath1.length());
			}
			
			for(Map<String, Object> url : listclient){
				for(Map<String, Object> data : p_unit){
					data.put("UNIT_PATH", unitPath1);
					/*ThreadUtil th = new ThreadUtil(data);
					System.out.println("------data"+ data);
					th.start();*/
					PushDataUtils pd = new PushDataUtils();
					String jsondata = pd.getPushUnitData(data);
					//推送加密字段判断
					if(url.get("PUSH_ENCRYPT") == null || url.get("PUSH_ENCRYPT").toString().equals("0")){
						//不加密
						jsondata = Native2AsciiUtils.native2Ascii(pd.getPushUnitData(data));
					}else if (url.get("PUSH_ENCRYPT").toString().equals("1")){
						//base64加密
						jsondata = new BASE64Encoder().encode(Native2AsciiUtils.native2Ascii(pd.getPushUnitData(data)).getBytes());
					}else if (url.get("PUSH_ENCRYPT").toString().equals("2")){
						//特有加密
						try {
							jsondata = PbeEncrypt.encrypt(Native2AsciiUtils.native2Ascii(pd.getPushUnitData(data)), url.get("EMID").toString());
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					//String jsondata = pd.getPushUnitData(data);
					httpClientPostData myhttp = new httpClientPostData();
					System.out.println("url"+url.get("PUSH_UNIT_URL"));
					String ret = myhttp.requestSystem(
							(String)url.get("PUSH_LOGIN_URL"),
							(String)url.get("PUSH_NAME"),
							(String)url.get("PUSH_PASS"), jsondata, 
							(String)url.get("PUSH_UNIT_URL"), 
							(String)url.get("PUSH_ENCODE"));
					System.out.println("输出: 推送的url:"+url.get("PUSH_URL"));
					Map<String, Object> m = null;
					if (ret != null && ret.trim().length() > 0) {
						m = jsonFormatMap.getMap(ret);
					}
					if (m != null && m.get("NAME") != null && Integer.parseInt((String) m.get("NAME")) > 0) {
						System.out.println("用户[" + url.get("EMNAME") + "]推送成功!");
						// 将成功记录插入表
						Map<String, Object> pushData = new HashMap<String, Object>();
						pushData.put("PUSH_LOGIN_URL", url.get("PUSH_LOGIN_URL"));
						pushData.put("PUSH_NAME", url.get("PUSH_NAME"));
						pushData.put("PUSH_PASS", url.get("PUSH_PASS"));
						pushData.put("PUSH_URL", url.get("PUSH_UNIT_URL"));
						pushData.put("PUSH_ENCODE", url.get("PUSH_ENCODE"));
						pushData.put("CLIENT_CODE", url.get("CODE"));
						pushData.put("PUSH_DATA_ID", data.get("UUID"));
						pushData.put("ISFINISH", "1");
						pushData.put("CREATOR_ID", loginuserCode);
						pushData.put("TYPE", "2");// 类型:1=人员 2=单位

						PushDataBusiness pushData_business = BusinessManager.getBusiness(PushDataBusiness.class);
						Map<String, Object> p_query = new HashMap<String, Object>();
						p_query.put("CLIENT_CODE", pushData.get("CLIENT_CODE"));
						p_query.put("PUSH_DATA_ID", pushData.get("PUSH_DATA_ID"));
						List<Map<String, Object>> p_query_data = pushData_business.list_pushData(p_query);
						if (p_query_data == null || p_query_data.size() == 0) {
							pushData_business.insert_pushData(pushData);
						} else {
							pushData.put("UUID", p_query_data.get(0).get("UUID"));
							pushData_business.update_pushData(pushData);
						}
					} else {
						System.out.println("用户["
										+ url.get("EMNAME")
										+ "]推送失败,失败的数据将提交给作业[RemotePushUserJob],在调度任务中作定时推送!");
						// 把数据存到推送失败的临时表里
						Map<String, Object> pushData = new HashMap<String, Object>();
						pushData.put("PUSH_LOGIN_URL", url.get("PUSH_LOGIN_URL"));
						pushData.put("PUSH_NAME", url.get("PUSH_NAME"));
						pushData.put("PUSH_PASS", url.get("PUSH_PASS"));
						pushData.put("PUSH_URL", url.get("PUSH_UNIT_URL"));
						pushData.put("PUSH_ENCODE", url.get("PUSH_ENCODE"));
						pushData.put("CLIENT_CODE", url.get("CODE"));
						pushData.put("PUSH_DATA_ID", data.get("UUID"));
						pushData.put("CREATOR_ID", loginuserCode);
						pushData.put("TYPE", "2");// 类型:1=人员 2=单位

						PushDataBusiness pushData_business = BusinessManager.getBusiness(PushDataBusiness.class);
						Map<String, Object> p_query = new HashMap<String, Object>();
						p_query.put("CLIENT_CODE", pushData.get("CLIENT_CODE"));
						p_query.put("PUSH_DATA_ID", pushData.get("PUSH_DATA_ID"));
						List<Map<String, Object>> p_query_data = pushData_business.list_pushData(p_query);
						if (p_query_data == null || p_query_data.size() == 0) {
							pushData_business.insert_pushData(pushData);
						} else {
							pushData.put("UUID", p_query_data.get(0).get("UUID"));
							pushData_business.update_pushData(pushData);
						}

					}
				}
			}
			}
		System.out.println("结束推送......");
		jsonObject.putAll(Status.getStatus(Status.PUSH_OK));
		}
		return "json";
	}
	//ldap全量同步
	public String insertOrUpdateLdap() throws BusinessException{
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		System.out.println("ldap全量同步开始.......");
		List<Map<String, Object>> list1 = business.list_unit_ldap();
		for(Map<String, Object> map1 : list1){
			String ret1 = TakeUnitsUtils.getp(list1, (String) map1.get("UUID"));
			String [] split1 = ret1.split(",");
			Map<String, Object> entity = new HashMap<String, Object>();
			entity.put("LDAP_ORDER", split1.length);
			entity.put("UUID", map1.get("UUID"));
			business.update_unit(entity);
		}
		List<Map<String, Object>> list = business.list_unit_ldap_deletekey();
		Ldap ldap = Factory.createInstance();
        try {
			ldap.connect();
			String rdnroot = PropUtil.getValue("rootrdn","quartz_service","0000");
			for(Map<String, Object> map : list){
				String ret = TakeUnitsUtils.getp(list, (String) map.get("UUID"));
				String [] split = ret.split(",");
				if(split.length == 1){
					//根节点
	    			String objectClass = "organization";
	    			Attribute attr = new BasicAttribute("objectClass");
	    			attr.add(objectClass);
	    			Attributes attrs = new BasicAttributes();
	    			attrs.put(attr);
	    			rdnroot = "o="+map.get("UUID")+","+rdnroot;
	    			attrs.put("description", map.get("NAME"));
	    			attrs.put("street", map.get("UNIT_ID"));
	    			//rdnroot = "o="+map.get("NAME")+"("+map.get("UNIT_ID")+")"+","+rdnroot;
	    			//attrs.put("description", map.get("UNIT_ID"));
	    			//attrs.put("street", map.get("UUID"));
	    			ldap.add(rdnroot, attrs);
				}else if(split.length == 2){
				    //根的下一层节点
					String rdnfinal = "ou=" + map.get("UUID") + "," + rdnroot;
					//String rdnfinal = "ou=" + map.get("NAME")+"("+map.get("UNIT_ID")+")" + "," + rdnroot;
					String objectClass = "organizationalUnit";
        			Attribute attr = new BasicAttribute("objectClass");
        			attr.add(objectClass);
        			Attributes attrs = new BasicAttributes();
        			attrs.put(attr);
        			attrs.put("description", map.get("NAME"));
        			//attrs.put("description", map.get("UNIT_ID"));
        			String splitst[] = rdnroot.split(",");
        			String st = splitst[0].substring(2);
        			attrs.put("st", st);
        			attrs.put("street", map.get("UNIT_ID"));
        			//attrs.put("street", map.get("UUID"));
        			ldap.add(rdnfinal, attrs);
				}else if(split.length > 2){
					//其他节点
					if(map.get("PARENT_ID").equals(split[0])){
						//String ourdn = LdapOuUtils.ldapOu(split);
						//String splitst[] = ourdn.split(",");
						//String st = splitst[0].substring(3);
						String rdn = "";
						for(int i = 0 ; i < split.length -2 ; i++){
							rdn = rdn + "ou=" + split[i] + ",";
						}
						String rdnfinal = "ou=" + map.get("UUID") + "," + rdn + rdnroot;
						String st = split[0];
						//String rdnfinal = "ou=" + map.get("NAME")+"("+map.get("UNIT_ID")+")" + "," +ourdn+rdnroot;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", map.get("NAME"));
	        			//attrs.put("description", map.get("UNIT_ID"));
	        			attrs.put("st", st);
	        			attrs.put("street", map.get("UNIT_ID"));
	        			//attrs.put("street", map.get("UUID"));
	        			ldap.add(rdnfinal, attrs);
					}	
				}
			}
			jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
			System.out.println("ldap全量同步结束.......");
		} catch (NamingException e) {
			jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
			e.printStackTrace();
		}finally {
			try {
				ldap.close();
			} catch (NamingException e) {
				jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
				e.printStackTrace();
			}
		}
		return "json";
	}
	
    //ldap整体清除
	public String deleteLdap() throws BusinessException{
		Ldap ldap = Factory.createInstance();
		jsonObject = new JSONObject();
		try {
			ldap.connect();
			String rdnroot = PropUtil.getValue("rootrdn","quartz_service","0000");
			String name = PropUtil.getValue("root","quartz_service","0000");
			ldap.ldapAllSubContext(name, rdnroot); 
			ldap.delete(name + "," + rdnroot);
			jsonObject.putAll(Status.getStatus(Status.DELETE_OK));
		} catch (NamingException e) {
			jsonObject.putAll(Status.getStatus(Status.DELETE_ERR));
			e.printStackTrace();
		}finally {
			try {
				ldap.close();
			} catch (NamingException e) {
				jsonObject.putAll(Status.getStatus(Status.DELETE_ERR));
				e.printStackTrace();
			}
		}
		return "json";	
	}
	//ldap批量同步
	public String addRowLdap() throws BusinessException {
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		System.out.println("--------entity"+entity);
		String key = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(key);
		Ldap ldap = Factory.createInstance();
		jsonObject = new JSONObject();
		try {
			ldap.connect();
			for(String unituuid : ListKey) {
				String searchFilter = "ou=" + unituuid;
				String searchBase = PropUtil.getValue("root","quartz_service","0000") + "," + PropUtil.getValue("rootrdn","quartz_service","0000");
				List<Map<String, Object>> result = ldap.searchAll(searchFilter, searchBase, null);
				if(result.isEmpty()){
					//如果组织在ldap里面没有，则添加
					Map<String, Object> map = business.list_unit_ldap_ou(unituuid);
					System.out.println("-------map"+map);
					String o = PropUtil.getValue("root","quartz_service","0000").substring(2);
					if(map.get("PARENT_ID").equals(o)){
						String rdn = "ou=" + unituuid + "," + searchBase;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", map.get("NAME"));
	        			attrs.put("st", map.get("PARENT_ID"));
	        			attrs.put("street", map.get("UNIT_ID"));
	        			ldap.add(rdn, attrs);
	        			jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
					}else{
						String searchFilter1 = "ou=" + map.get("PARENT_ID");
						List<Map<String, Object>> result1 = ldap.searchAll(searchFilter1, searchBase, null);
						System.out.println("------result1"+ result1);
						String rdn = "ou=" + unituuid + "," + result1.get(0).get("rdn") + "," + searchBase;
						String objectClass = "organizationalUnit";
	        			Attribute attr = new BasicAttribute("objectClass");
	        			attr.add(objectClass);
	        			Attributes attrs = new BasicAttributes();
	        			attrs.put(attr);
	        			attrs.put("description", map.get("NAME"));
	        			attrs.put("st", map.get("PARENT_ID"));
	        			attrs.put("street", map.get("UNIT_ID"));
	        			ldap.add(rdn, attrs);
	        			jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
					}
				}else{
					//组织在ldap里面存在，则更新
					String rdn = (String) result.get(0).get("rdn") + "," + searchBase;
					Map<String, Object> map = business.list_unit_ldap_ou(unituuid);
					System.out.println("------map"+map);
					Map<String, Object> mapou = new HashMap<String, Object>();
					mapou.put("st", map.get("PARENT_ID"));
					mapou.put("description", map.get("NAME"));
					mapou.put("street", map.get("UNIT_ID"));
					for(Map.Entry<String, Object> entry : mapou.entrySet()){
						ldap.update(rdn, entry.getKey(), entry.getValue());
					}
					jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
				}
			}
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
			e.printStackTrace();
		}finally {
			try {
				ldap.close();
			} catch (NamingException e) {
				jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
				e.printStackTrace();
			}
		}
		return "json";
	}
	//ldap单个删除
	public String deleteLdapUnit() throws BusinessException{
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String key = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(key);
		Ldap ldap = Factory.createInstance();
		jsonObject = new JSONObject();
		try {
			ldap.connect();
			for(String unituuid : ListKey) {
				String searchFilter = "ou=" + unituuid;
				System.out.println("-----unituuid"+unituuid);
				String searchBase = PropUtil.getValue("root","quartz_service","0000") + "," + PropUtil.getValue("rootrdn","quartz_service","0000");
				List<Map<String, Object>> result = ldap.searchAll(searchFilter, searchBase, null);
				String o = PropUtil.getValue("root","quartz_service","0000").substring(2);
				if(result.get(0).get("st").equals(o)){
					String rdn = "ou=" + unituuid + "," + searchBase;
					ldap.delete(rdn);
				}else{
					String rdn = result.get(0).get("rdn") + "," + searchBase;
					ldap.delete(rdn);
				}		
			}
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				ldap.close();
			} catch (NamingException e) {
				e.printStackTrace();
			}
		}
		return "json";
	}
	//组织机构导入
	public String ImpUnit() throws BusinessException {
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		Map<String, Object> file = RequestUtils.getUpdateFieldMap(request, "FILED_");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datastart = df.format(new Date());
		System.out.println("单位导入开始........");
		if (file.get("FILE_PATH") != null && !file.get("FILE_PATH").toString().equals("")) {
			String filePath = file.get("FILE_PATH").toString();
			Workbook book = null;
			try {
				book = Workbook.getWorkbook(new File(filePath));
				int sheetCount = book.getNumberOfSheets();
				String data = "";
				System.out.println("-----------------共"+sheetCount+"页数据开始导入----------------------");
				// 获得第一个工作表对象(组织导入表)
				Sheet sheet = book.getSheet(0);
				int rows = sheet.getRows();
				// 遍历每行每列的单元格
				for (int i = 1; i < rows; i++) {
					Map<String, Object> unitMap = new HashMap<String, Object>();
					// 判断是否要新增数据，要是0 1 2 4 没有数据 则不更新数据
					int flag = 0;
					// 整列为空值
					int flag1 = 0;
					for (int j = 0; j < 15; j++) {
						if (sheet.getCell(j, i).getContents() == null
								|| sheet.getCell(j, i).getContents().equals(
										"null")
								|| sheet.getCell(j, i).getContents().equals(""))
							flag1++;
					}
					for (int j = 0; j < 15; j++) {
						Cell cell = sheet.getCell(j, i);
						String result = cell.getContents();
						if (result != null && !result.equals("null")
								&& !result.equals("")) {
							switch (j) {
							case 0:// 单位唯一标识
								unitMap.put("UUID", result);
								break;
							case 1:// 单位编号
								unitMap.put("UNIT_ID", result);	
								break;
							case 2:// 单位名
								unitMap.put("NAME", result);
								break;
							case 3:// 单位类型
								unitMap.put("TYPE", result);
								break;
							case 4:// 上级部门
								unitMap.put("PARENT_ID", result);
								break;
							case 5:// 实体标识
								unitMap.put("IS_ENTITY", result);
								break;
							case 6:// 单位英文
								unitMap.put("NAME_EN", result);
								break;
							case 7:// 单位缩写
								unitMap.put("NAME_ABBR", result);
								break;
							case 8:// 官网地址
								unitMap.put("VISIT_URL", result);
								break;
							case 9:// 单位简介
								unitMap.put("DESCP", result);
								break;
							case 10:// 部门电话
								unitMap.put("OFFICE_PHONE", result);
								break;
							case 11:// 单位序号
								unitMap.put("ORDER_ID", result);
								break;
							case 12:// 办公地址
								unitMap.put("OFFICE_ADRESS", result);
								break;
							case 13:// 区域类型
								unitMap.put("AREA_TYPE", result);
								break;
							case 14:// 组织后缀
								unitMap.put("DEVCODING", result);
								break;
							default:
								break;
							}
						} else {
							if (j == 0 || j == 1 || j == 2 || j == 4) {
								flag = 1;
								if (flag1 != 15)
									data = data + "第" + (i + 1) + "行,";
								break;
							}

						}
					}
					//unitMap.put("tableName", "UICM_UNIT");
					// 新增
					if (flag == 0) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("UUID", unitMap.get("UUID"));
						System.out.println("----uuid"+map.get("UUID"));
						Integer count = business.listCount_unit(map);
						if (count > 0)
							business.update_unit(unitMap);
						else
							business.insert_unit(unitMap);
					}
				}
				if (data.equals(""))
					jsonObject.putAll(Status.getStatus(Status.UPDATE_OK));
				else {
					Map<String, Object> m = new HashMap<String, Object>();
					data = data.substring(0, data.length() - 1);
					data = data + "由于必填项未填写，未能导入到数据库，请重新填写后导入。";
					m.put("VALUE", data);
					jsonObject.putAll(m);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				jsonObject.putAll(Status.getStatus(Status.UPDATE_ERR));
			}
			String dataend = df.format(new Date());
			System.out.println("-----------------数据导入结束----------------------开始时间："+ datastart + ", 结束时间：" + dataend);
		}
		return "json";
	}
	//文件下载
	public String download() throws BusinessException{
		String ret_download ="";
    	String uuid = request.getParameter("uuid");
		String uploadnew=request.getParameter("uploadnew");
		String uploadpath=request.getParameter("uploadpath");
		String uploadold=request.getParameter("uploadold");
		if(new File(uploadpath+File.separator+uploadnew).exists()==false){
			uploadpath = request.getSession().getServletContext().getRealPath(uploadpath);
			try {
//				uploadold = new String(uploadold.getBytes("iso8859-1"), "utf-8");
				uploadold = new String((uploadold).getBytes("gbk"),"iso8859-1");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			FileUtil fileUtil = new FileUtil();
			//文件存放目录
			FileObject baseDir = fileUtil.getFile(uploadpath);
			
			//获取下载文件
			FileObject file = null;
			try {
				file = baseDir.resolveFile(uploadnew);
			} catch (FileSystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//设置response
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\""+uploadold+"\"");
			
			//下载，写入response
			fileUtil.download(file, response); 
			
			ret_download =  null;
		}else{
			ret_download = super.download();
		}
		return ret_download;	
	}
	//对照文件下载
	public String downloadDz() throws BusinessException {
		String ret_download ="";
		String uploadnew=request.getParameter("uploadnew");
		String uploadpath=request.getParameter("uploadpath");
		String uploadold=request.getParameter("uploadold");
		if(new File(uploadpath+File.separator+uploadnew).exists()==false){
			uploadpath = request.getSession().getServletContext().getRealPath(uploadpath);
			try {
//				uploadold = new String(uploadold.getBytes("iso8859-1"), "utf-8");
				uploadold = new String((uploadold).getBytes("gbk"),"iso8859-1");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			//查对照数据
			UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
 			List<Map<String, Object>> list = business.list_unit_ldap_deletekey();
 			
			FileUtil fileUtil = new FileUtil();
			//文件存放目录
			//FileObject baseDir = fileUtil.getFile(uploadpath);
			
			//获取下载文件
			FileObject file = null;
			try {
				/*file = baseDir.resolveFile(uploadnew);
				file.getName();
				System.out.println("-----"+file.getName());*/
				HSSFWorkbook wb = new HSSFWorkbook(); 
		        //创建第一个sheet（页），命名为 new sheet 
		        HSSFSheet sheet = wb.createSheet("new sheet"); 
		        //Row 行 
		        //Cell 方格 
		        // Row 和 Cell 都是从0开始计数的 
		        //设置宽度
		        sheet.setColumnWidth(0, 5 * 2000);
		        sheet.setColumnWidth(1, 5 * 2000);
		        sheet.setColumnWidth(2, 5 * 2000);
		        // 创建一行，在页sheet上 
		        HSSFRow row = sheet.createRow((short) 0); 
		        // 在row行上创建一个方格 
		       // HSSFCell cell = row.createCell(0); 
		        //设置方格的显示 
		       // cell.setCellValue(1); 
		 
		        // Or do it on one line. 
		        row.createCell(0).setCellValue("单位唯一标识");
		        row.createCell(1).setCellValue("单位编号"); 
		        row.createCell(2).setCellValue("单位名称"); 
		        for(int i = 0 ; i < list.size() ; i++){
		        	HSSFRow row1 = sheet.createRow(i+1);
		        	row1.createCell(0).setCellValue((String)list.get(i).get("UUID"));
		        	row1.createCell(1).setCellValue((String)list.get(i).get("UNIT_ID"));
		        	row1.createCell(2).setCellValue((String)list.get(i).get("NAME"));
		        }
		        //创建一个文件 命名为workbook.xls 
		        String path = uploadpath+"/workbook.xls";
		        FileOutputStream fileOut = new FileOutputStream(path); 
		        // 把上面创建的工作簿输出到文件中 
		        wb.write(fileOut); 
		        //关闭输出流 
		        fileOut.close(); 
		        FileObject baseDir = fileUtil.getFile(uploadpath);
		        file = baseDir.resolveFile("workbook.xls");

			} catch (FileSystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//设置response
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\""+uploadold+"\"");
			
			//下载，写入response
			fileUtil.download(file, response); 
			
			ret_download =  null;
		}else{
			ret_download = super.download();
		}
		return ret_download;
	}
	
	//修改目标树的父类节点
	public String updateParentId() throws BusinessException{
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String unitId = entity.get("UUID").toString();
		String parentId = entity.get("NEW_PARENT").toString();
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("UUID", unitId);
		query.put("PARENT_ID", parentId);
		UnitBusiness business = BusinessManager.getBusiness(UnitBusiness.class);
		business.update_unit(query);
		return "json";	
	}
}
