package com.kingdee.shr.custom.service;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.base.permission.IPermission;
import com.kingdee.eas.base.permission.PermissionFactory;
import com.kingdee.eas.basedata.org.*;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.util.ToolUtils;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.util.StringUtils;

import java.sql.SQLException;
import java.util.*;

public class GetOrgUtils {
	
	/**
	 * 获取根组织
	 * @param ctx
	 * @return
	 */
	public static String getRootOrg(Context ctx) {
		String orgId = "";
		try {
			String sql = "select fid from T_ORG_Admin  where FLEVEL  = 1 ";
			IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);
			while(executeQuery.next()) {
				orgId = executeQuery.getString("fid");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (BOSException e) {
			e.printStackTrace();
		}
		return orgId;
	}
	
	/**
	 * 获取人数
	 * checkType不等于1的时候,则查询所有下级组织;
	 * 否则,1,只查询直接下级组织;
	 * @param ctx
	 * @param orgId
	 * @param checkType
	 * @return
	 * @throws BOSException
	 * @throws EASBizException
	 */
	public  static  int  getPersonCount(Context ctx  ,String checkType,Map <String,String> paramMap ) throws BOSException, EASBizException {
		String orgId = paramMap.get("orgId");
		String isOfficer = paramMap.get("isOfficer");
		//权限过滤
		String permStr = addPermissionFilterSql(ctx);
		String filterStr = " and topp.FAdminOrgUnitID  = '"+orgId+"'  "+permStr;
		
		try {
			if(!StringUtils.equals("1", checkType)) {
				List<String> orgIds = getAllSubOrg(ctx, orgId);
				filterStr = " and topp.FAdminOrgUnitID in ( "+ToolUtils.aryToStr(orgIds,true)+" ) "+permStr;
			} 
			if(StringUtils.equals("1", isOfficer)) {
				filterStr += " and   pers.CFIsCadre  = 1 ";
			} 
			String pinSql = pinPersonSql( "count",filterStr);
			IRowSet rs = DbUtil.executeQuery(ctx, pinSql);
			while(rs.next()) {
				return  rs.getInt("pcount");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
		
		
	}
	
	public static List<String> getAllSubOrg( Context ctx ,String orgId ) throws EASBizException, BOSException {
		if(StringUtils.equals("1", orgId)){
			orgId  =  getRootOrg(ctx);
		}
		List<String> orgIds = new ArrayList();
		SelectorItemCollection sic =new SelectorItemCollection();
        sic.add("id");
        sic.add("longNumber");
        sic.add("name");
		IAdminOrgUnit iAdminOrgUnit = AdminOrgUnitFactory.getLocalInstance(ctx);
		AdminOrgUnitInfo orgInfo = iAdminOrgUnit.getAdminOrgUnitInfo(new ObjectUuidPK(orgId),sic);
		
		if(null!=orgInfo &&!StringUtils.isEmpty(orgInfo.getLongNumber())) {
			String longNum = orgInfo.getLongNumber();
			//获取所有下级组织
//			String[] longNumStrs = longNum.split("!");
//			Set<String> numsSet  = new HashSet<String>();
//			numsSet.addAll(Arrays.asList(longNumStrs));
			EntityViewInfo view =  new EntityViewInfo();
			FilterInfo filter = new FilterInfo();
			filter.getFilterItems().add(new FilterItemInfo("longnumber",longNum+"%",CompareType.LIKE));
			filter.getFilterItems().add(new FilterItemInfo("isSealUp", false ,CompareType.EQUALS));
			view.setFilter(filter);
			view.setSelector(sic);
			AdminOrgUnitCollection col = iAdminOrgUnit.getAdminOrgUnitCollection(view);
			if(null!=col && col.size()>0) {
				for (int k = 0; k < col.size(); k++) {
					AdminOrgUnitInfo adminOrg = col.get(k);
					String adminId = StringUtils.cnulls( adminOrg.getString("id"));
					orgIds.add(adminId) ;
				}
			}
		}
		return orgIds;
	}
	
	/**
	 * 根据人名或编码获取人员数据
	 * @param ctx
	 * @param perName
	 * @return
	 * @throws BOSException
	 * @throws EASBizException
	 */
	public static List getPersonFromName(Context ctx ,HashMap<String,String> paraMap ) throws BOSException, EASBizException {
		String orgId = paraMap.get("orgId");
		if(StringUtils.equals("1", orgId)){
			orgId  =  getRootOrg(ctx);
		}
		String perName = paraMap.get("perName");
		//是否干部
		String isOfficer = paraMap.get("isOfficer");
		//权限过滤
		String permStr = addPermissionFilterSql(ctx);
		String filterStr = " and ( pers.fname_l2  like '%"+perName+"%'  or  pers.fnumber like '%"+perName+"%' ) " + permStr;
		if(!StringUtils.isEmpty(orgId)) {
			filterStr = filterStr
					+ " and topp.FAdminOrgUnitID  = '"+orgId+"'   ";
		}
		if(StringUtils.equals(isOfficer, "1")) {
			filterStr += " and  pers.CFIsCadre = 1 ";
		}
		return assemPersonData(ctx, filterStr);
	}
	
	/**
	 * 根据组织获取人员数据
	 * checkType = 0;所有的下级; 1,则只有直接下级
	 * @param ctx
	 * @return
	 * @throws BOSException
	 * @throws EASBizException
	 */
	public static List getPersonFromOrg(Context ctx ,String checkType,Map<String,String> paraMap ) throws BOSException, EASBizException {
		String orgId = paraMap.get("orgId");
		if(StringUtils.equals("1", orgId)){
			orgId  =  getRootOrg(ctx);
		}
		//权限过滤
		String permStr = addPermissionFilterSql(ctx);
		String filterStr = " and topp.FAdminOrgUnitID  = '"+orgId+"'  "+permStr;
		
		if(!StringUtils.equals(checkType, "1")) {
			List<String> orgIds = getAllSubOrg(ctx, orgId);
			String aryToStr = ToolUtils.aryToStr(orgIds,true);
			filterStr = " and topp.FAdminOrgUnitID in ("+aryToStr+")   ";
		}
		//是否干部
		String isOfficer = paraMap.get("isOfficer");
		if(StringUtils.equals(isOfficer, "1")) {
			filterStr +=  " and  pers.CFIsCadre = 1 ";
		}
		return assemPersonData(ctx, filterStr);
		
	}
	
	public static  List  assemPersonData(Context ctx, String filterStr) throws BOSException{
		List<Map> personList = new ArrayList();
		try {
			String pinSql = pinPersonSql( "info",filterStr);
			IRowSet rs = DbUtil.executeQuery(ctx, pinSql);
			while(rs.next()) {
				String fid = StringUtils.cnulls(rs.getString("fid"));
				String name = StringUtils.cnulls(rs.getString("name"));
				String number = StringUtils.cnulls(rs.getString("number"));
				HashMap<String,String> map = new HashMap();
				map.put("fid", fid);
				map.put("name", name);
				map.put("number", number);
				map.put("posname", StringUtils.cnulls(rs.getString("posname")));
				map.put("depname", StringUtils.cnulls(rs.getString("depname")));
				personList.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return personList;
	}


	/**
	 * 添加权限过滤
	 */
	public static String addPermissionFilterSql(Context ctx) throws BOSException, EASBizException {
		//权限过滤
		IPermission permission = PermissionFactory.getLocalInstance(ctx);
		IObjectPK caller = ctx.getCaller();
		Set authorizedOrgIds = permission.getAuthorizedOrgIds(caller, OrgType.Admin, null, "");
		String filterStr =  " and topp.FAdminOrgUnitID  in ("+ToolUtils.aryToStr(authorizedOrgIds,true)+ ") ";
		return filterStr;
	}


	/**
	 * 
	 * @param type
	 * info 人员信息;
	 * count 人员总数量
	 * adminPerson 每个组织下的人数;
	 * @param filterStr
	 * @return
	 */
	public static String pinPersonSql( String type, String  filterStr ) {
		StringBuffer sbf = new StringBuffer();
		sbf.append(" /*dialect*/ SELECT     ");
		if(StringUtils.equals("count", type)) {
			sbf.append("  count( pers.fid )  pcount    ");
		}else if(StringUtils.equals("info", type)) {
			sbf.append("  pers.fid  fid,                       ");
			sbf.append("  pers.fnumber  number ,                       ");
			sbf.append("  pers.FName_L2  name   ,                ");
			sbf.append("  topp.FName_L2  posname ,                 ");
			sbf.append("  admOrg.FName_L2  depname                   ");
		}else if(StringUtils.equals("adminPerson", type)) {
			sbf.append("  count (pers.fid)  pcount,                    ");
			sbf.append("  admOrg.fid  depId                      ");
		}
		sbf.append(" FROM  t_bd_person pers                           ");
		sbf.append(" LEFT JOIN                                        ");
		sbf.append(" T_HR_EmpOrgRelation  rela                        ");
		sbf.append(" ON pers.fid = rela.fpersonid   ");
		sbf.append(" AND rela.FAssignType = 1   ");
		sbf.append(" AND rela. fleffdt = '2199-12-31 00:00:00'      ");
		sbf.append(" INNER JOIN  T_ORG_Position topp                  ");
		sbf.append(" ON rela.FPOSITIONID =  topp.fid                  ");
		sbf.append(" inner join T_HR_EmpLaborRelation labor           ");
		sbf.append(" ON rela.FlaborRelationID = labor.fid             ");
		sbf.append(" INNER JOIN T_ORG_Admin  admOrg   ");
		sbf.append(" ON topp.FAdminOrgUnitID = admOrg.fid   ");
		sbf.append(" where                      ");
		sbf.append("  labor.FLaborRelationStateID in (            ");
		sbf.append("  select fid from T_HR_BDEmployeeType where       ");
		sbf.append("  fname_l2 <> '辞退' and  fname_l2 <> '辞职'      ");
		sbf.append("  and  fname_l2 <> '退休' and  fname_l2 <> '开除' ");
		sbf.append("  and  fname_l2 <> '解聘' and  fname_l2 <> '离职' ");
		sbf.append("  and  fname_l2 <> '死亡'                        ");
		sbf.append("  )                                               ");
		if(!StringUtils.isEmpty(filterStr)) {
			sbf.append(filterStr);
		}
		if(StringUtils.equals("info", type)) {
			sbf.append(" order by  topp.FIsRespPosition  desc ,  pers.fnumber ");
		}else if(StringUtils.equals("adminPerson", type)) {
			sbf.append(" group by admOrg.fid ");
		 
		}
		
		return sbf.toString();
		
	}
}
