package com.kingdee.shr.customer.gtiit.osf;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.base.permission.PermItemFactory;
import com.kingdee.eas.base.permission.PermItemInfo;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.emp.EmployeeInterfacePermBizException;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.permission.api.service.SHRFunctionPermissionService;
import com.kingdee.shr.common.util.StringUtils;
import com.kingdee.shr.customer.gtiit.osf.util.DateUtils;
import com.kingdee.shr.integration.oa.util.IntegrateOAUtil;
import com.kingdee.shr.integration.oa.util.MappingFieldInfo;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GtiitOAGetAdminOrgDataService implements IHRMsfService{
	
	private static final Logger logger = LoggerFactory.getLogger(GtiitOAGetAdminOrgDataService.class);

	public Object process(Context ctx, Map param) throws EASBizException, BOSException {
		logger.error("GtiitOAGetAdminOrgDataService enter ");
		new ArrayList();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 开始日期
		String startDate = (String) param.get("startDate");
		// 截止日期
		String endDate = (String) param.get("endDate");
		if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
			startDate=DateUtils.formatDate(startDate,true);
			endDate=DateUtils.formatDate(endDate,false);
		}
		String adminPermItem = "fffffff0-ffff-efff-e22e-0000000dfa21PERMITEM";
		PermItemInfo permItem = PermItemFactory.getLocalInstance(ctx).getPermItemInfo(new ObjectUuidPK(adminPermItem));

		try {
			SHRFunctionPermissionService.checkCurrnetUserFunctionPermission(ctx, permItem);
		} catch (Exception var9) {
			logger.error(var9.getMessage(), var9);
			String userId = ContextUtil.getCurrentUserInfo(ctx).getId().toString();
			UserInfo userInfo = UserFactory.getLocalInstance(ctx).getUserInfo(new ObjectUuidPK(userId));
			throw new EmployeeInterfacePermBizException(EmployeeInterfacePermBizException.NO_FUNCTION_PERMISSION,
					new Object[]{userInfo.getName(), permItem.getAlias()});
		}

		List<MappingFieldInfo> fieldList = this.initMappingField();
		StringBuffer sql = IntegrateOAUtil.getSelectFieldSql(fieldList);
		//职位变更也要触发部门的同步
		sql.append(" from t_org_admin org left join t_org_admin parent on parent.fid=org.FParentID  "
				+ "left join T_ORG_POSITION position on org.fid=position.FAdminOrgUnitID  left join T_HR_EmpOrgRelation he on he.fAdminOrgId=org.fid ");
		sql.append(" where org.FIsStartSHR=1");
		
		if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
			sql.append(" and (org.flastupdatetime >= '"+startDate+"' and org.flastupdatetime<='"+endDate+"') ");
			sql.append(" or (position.flastupdatetime >= '"+startDate+"' and position.flastupdatetime<='"+endDate+"') ");
			sql.append(" or (he.flastupdatetime >= '"+startDate+"' and he.flastupdatetime<='"+endDate+"') ");
		}
		sql.append(" group by org.fid,org.fname_l2,org.fname_l1,org.FParentID,parent.fname_l2,org.fSortCode,org.FIsLeaf,org.FIsSealUp ,org.FNumber ,org.fcreateTime ,org.FLastUpdateTime ,parent.FNumber ,org.FEffectDate ,org.FsimpleName ");
		IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		logger.info("GtiitOAGetAdminOrgDataService....sql: "+sql.toString());
		List<HashMap<String, String>> dataList = IntegrateOAUtil.getRsListData(fieldList, rs);
		
		//部门负责人处理
		try {
			if(dataList!=null && dataList.size()>0) {
				processHead(ctx,dataList,startDate,endDate);

			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			logger.info("processHead...."+e);
		}
		return dataList;
	}

	private List<MappingFieldInfo> initMappingField() {
		List<MappingFieldInfo> list = new ArrayList();
		MappingFieldInfo fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("easdept_id");
		fieldInfo.setShrField("org.fid");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("name");
		fieldInfo.setShrField("org.fname_l2");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("name_L1");
		fieldInfo.setShrField("org.fname_l1");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("superior");
		fieldInfo.setShrField("org.FParentID");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("supname");
		fieldInfo.setShrField("parent.fname_l2");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("sortCode");
		fieldInfo.setShrField("org.fSortCode");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("endflag");
		fieldInfo.setShrField("org.FIsLeaf");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("status");
		fieldInfo.setShrField("org.FIsSealUp");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("fnumber");
		fieldInfo.setShrField("org.FNumber");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("fcreateTime");
		fieldInfo.setShrField("org.fcreateTime");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("flastUpdateTime");
		fieldInfo.setShrField("org.FLastUpdateTime");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("supFnumber");
		fieldInfo.setShrField("parent.FNumber");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("fEffectDate");
		fieldInfo.setShrField("org.FEffectDate");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("simpleName");
		fieldInfo.setShrField("org.FsimpleName");
		list.add(fieldInfo);
		fieldInfo = new MappingFieldInfo();
		fieldInfo.setOaField("isSealUp");
		fieldInfo.setShrField("org.fissealup");
		list.add(fieldInfo);
		return list;
	}
	
	/**
	 * 赋值部门负责人
	 * @param ctx
	 * @param dataList
	 * @throws BOSException
	 * @throws SQLException
	 */
	private void processHead(Context ctx,List<HashMap<String, String>> dataList,String startDate,String endDate) throws BOSException, SQLException {
		List<String> ids=new ArrayList<>();
		for (int i = 0; i < dataList.size(); i++) {
			ids.add(dataList.get(i).get("easdept_id"));
		}
		
		String processStr = processStr(ids);
		
		//部门负责人
		Map<String, String> heads = getHead(ctx,processStr,startDate,endDate);
		Map<String, String> pvcs = getPvc(ctx,processStr);
		
		if(heads.size()>0) {
			logger.info("heads....count{}  ",heads.size());
		}
		
		for (int i = 0; i < dataList.size(); i++) {
			HashMap<String, String> data = dataList.get(i);
			data.put("pnumber", heads.get(data.get("fnumber"))==null?"":heads.get(data.get("fnumber")));
			data.put("pvc_number", pvcs.get(data.get("fnumber"))==null?"":pvcs.get(data.get("fnumber")));
		}
		
		
	}
	
	/**
	 * 获取pvc分部领导
	 * @param ctx
	 * @param processStr
	 * @return
	 * @throws BOSException
	 * @throws SQLException
	 */
	private Map<String,String> getPvc(Context ctx,String processStr) throws BOSException, SQLException{
		Map<String,String> resultMap=new HashMap<>();
		String sql="SELECT\r\n" + 
				"	org.fnumber orgNumber,\r\n" + 
				"	org.Fname_l1 orgName,\r\n" + 
				"	bp.fnumber pNumber,\r\n" + 
				"	bp.Fname_l1 pName\r\n" + 
				"FROM\r\n" + 
				"	T_WFR_WFROLE wf\r\n" + 
				"	LEFT JOIN T_WFR_PERSONROLE wp ON wp.froleid= wf.fid\r\n" + 
				"	LEFT JOIN T_BD_Person bp ON bp.fid= wp.fpsersonid\r\n" + 
				"	LEFT JOIN T_ORG_Admin org ON org.fid= wp.forgid \r\n" + 
				"WHERE\r\n" + 
				"	wf.fnumber= '02' and org.fid in("+processStr+")";
		
		logger.info("GtiitOAGetAdminOrgDataService->getPvc->sql{} ",sql);
       IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		
		while(rs.next()) {
			String orgNumber = rs.getString("orgNumber");
			if(StringUtils.isBlank(orgNumber)) {
				continue;
			}
			 
			if(StringUtils.isNotBlank(resultMap.get(orgNumber))) {
				resultMap.put(orgNumber, resultMap.get(orgNumber)+","+rs.getString("pNumber"));
			}else {
				resultMap.put(orgNumber, rs.getString("pNumber"));
			}
			
		}
		return resultMap;
		
		
	}
	/**
	 * 获取部门负责人
	 * @param numbers
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private Map<String,String> getHead(Context ctx,String processStr,String startDate,String endDate ) throws BOSException, SQLException{
		Map<String,String> resultMap=new HashMap<>();
		
		String  sql="SELECT\r\n" + 
				"	a.fid AS oId,\r\n" + 
				"	a.fnumber AS oNumber,\r\n" + 
				"	d.fnumber AS pNumber,\r\n" + 
				"	d.fname_L1 AS pNameL1,\r\n" + 
				"	d.fname_L2 AS pNameL2 \r\n" + 
				"FROM\r\n" + 
				"	T_ORG_Admin a\r\n" + 
				"	LEFT JOIN T_ORG_POSITION b ON a.FResponPositionID= b.fid\r\n" + 
				"	LEFT JOIN (\r\n" + 
				"	SELECT\r\n" + 
				"		ca.fpositionid,\r\n" + 
				"		ca.fpersonid, \r\n" + 
				"		ca.fislatestinaday, \r\n" + 
				"		ca.fadminorgid, \r\n" + 
				"		ca.flastupdatetime \r\n" + 
				"	FROM\r\n" + 
				"		T_HR_EmpOrgRelation ca\r\n" + 
				"		INNER JOIN ( SELECT fpositionid, MAX ( fleffdt ) maxDate FROM T_HR_EmpOrgRelation GROUP BY fpositionid ) cb ON ca.fpositionid= cb.fpositionid \r\n" + 
				"		AND ca.fleffdt= cb.maxDate \r\n" + 
				"	) c ON c.fpositionid= b.fid\r\n" + 
				"	LEFT JOIN T_BD_Person d ON d.fid= c.fpersonid\r\n" + 
				"	LEFT JOIN T_HR_BDEmployeeType e ON e.fid= d.femployeetypeid \r\n" + 
				"WHERE\r\n" + 
				"	a.fid IN ("+processStr+") \r\n" + 
				"	AND b.FIsRespPosition= 1 \r\n" + 
				"	AND e.finservice= 1 \r\n" + 
				"	AND b.fdeletedstatus= 1 \r\n"+
				"	AND c.fislatestinaday=1  \r\n";
			
		if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
			sql=sql+"	AND (b.flastupdatetime>= '"+startDate+"' \r\n" + 
					"	AND b.flastupdatetime<= '"+endDate+"') ";
			sql=sql+" or(c.flastupdatetime<= '"+endDate+"' and c.fadminorgid IN ("+processStr+") \r\n" + 
					"	AND c.fislatestinaday=1 and e.finservice=1) ";
		}
		
		sql=sql+" group by a.fid,a.fnumber,d.fnumber,d.fname_L1,d.fname_L2  order by a.fnumber";
				
		
		logger.info("getHead.....sql{} ",sql);
		
		IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		
		while(rs.next()) {
			String oNumber = rs.getString("oNumber");
			if(StringUtils.isBlank(oNumber)) {
				continue;
			}
			if(StringUtils.isNotBlank(resultMap.get(oNumber))) {
				resultMap.put(oNumber, resultMap.get(oNumber)+","+rs.getString("pNumber"));
			}else {
				resultMap.put(oNumber, rs.getString("pNumber"));
			}
		}
		return resultMap;
		
	}
	
	/**
	 * 处理字符串
	 * @param numbers
	 * @return
	 */
	private String processStr(List<String> numbers) {
		String result="";
		StringBuilder sb = new StringBuilder();
        for (String s : numbers) {
            sb.append("'").append(s).append("'").append(",");
        }

        if(sb.length()>0){
            sb.deleteCharAt(sb.lastIndexOf(","));
            result=sb.toString();
        }
        return result;
        
	}
	
}
