package com.kingdee.eas.custom.facade.abnormal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.aliyun.odps.utils.StringUtils;
import com.kingdee.bos.*;
import com.kingdee.eas.custom.entity.AbnormaAttendanceDetailInfo;
import com.kingdee.eas.custom.entity.AbnormaAttendanceInfo;
import com.kingdee.eas.custom.entity.AbnormalInfo;
import com.kingdee.eas.custom.utils.SendUtils;
import com.kingdee.eas.mobile.BOSMsgTypeEnum;
import com.kingdee.eas.mobile.MimeTypeEnum;
import com.kingdee.eas.mobile.PriorityEnum;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
// 部门考勤异常预警

public class AbnormalFacadeControllerBean extends AbstractAbnormalFacadeControllerBean {
	private static Logger logger = LoggerFactory.getLogger(AbnormalFacadeControllerBean.class);
			

	@Override
	public void _abnormalAttendance(Context ctx) throws BOSException {
		// 查询考勤异常的统计数据
		String attendanceSql ="/*dialect*/SELECT\r\n" + 
				"	temp.attendDate attendDate,\r\n" + 
				"	temp.personId personId,\r\n" + 
				"	thpc.fpersondep orgId,\r\n" + 
				"	temp.abnormalCount abnormalCount,\r\n" + 
				"	temp.reason reason \r\n" + 
				"FROM\r\n" + 
				"	(\r\n" + 
				"	SELECT DISTINCT\r\n" + 
				"		a.FAttendanceDate attendDate,\r\n" + 
				"		a.FProposer personId,\r\n" + 
				"		a.FAttendanceValue abnormalCount,\r\n" + 
				"		c.fname_l1 reason \r\n" + 
				"	FROM\r\n" + 
				"		T_HR_ATS_AbnormalAttendance a\r\n" + 
				"		LEFT JOIN (\r\n" + 
				"		SELECT\r\n" + 
				"			FProposer,\r\n" + 
				"			SUM ( FAttendanceValue ) AS COUNT \r\n" + 
				"		FROM\r\n" + 
				"			T_HR_ATS_AbnormalAttendance \r\n" + 
				"		WHERE\r\n" + 
				"			FAttendanceDate >= date_trunc ( 'month', CURRENT_DATE - INTERVAL '1 month' ) \r\n" + 
				"			AND FAttendanceDate <= LAST_DAY (\r\n" + 
				"			DATE_TRUNC ( 'month', CURRENT_DATE - INTERVAL '1 month' ))  and FStatus= '1' and FOperationStatus= '1' \r\n" + 
				"		GROUP BY\r\n" + 
				"			FProposer \r\n" + 
				"		HAVING\r\n" + 
				"			SUM ( FAttendanceValue ) > 3 \r\n" + 
				"		) b ON a.FProposer= b.FProposer\r\n" + 
				"		LEFT JOIN T_HR_ATS_AttendanceProject c ON c.fid= a.FattendanceProject \r\n" + 
				"	WHERE\r\n" + 
				"		a.FStatus= '1' \r\n" + 
				"		AND a.FOperationStatus= '1' \r\n" + 
				"		AND a.FAttendanceDate >= date_trunc ( 'month', CURRENT_DATE - INTERVAL '1 month' ) \r\n" + 
				"		AND a.FAttendanceDate <= LAST_DAY (\r\n" + 
				"		DATE_TRUNC ( 'month', CURRENT_DATE - INTERVAL '1 month' )) \r\n" + 
				"		AND b.count > 3 \r\n" + 
				"	) temp\r\n" + 
				"	LEFT JOIN (\r\n" + 
				"	SELECT\r\n" + 
				"		thpa.fpersonid,\r\n" + 
				"		thpa.fpersondep \r\n" + 
				"	FROM\r\n" + 
				"		T_HR_PersonPosition thpa\r\n" + 
				"		INNER JOIN ( SELECT fpersonid fpersonid, MAX ( fjoindate ) maxDate FROM T_HR_PersonPosition GROUP BY fpersonid ) thpb ON thpa.fjoindate= thpb.maxDate \r\n" + 
				"	AND thpa.fpersonid= thpb.fpersonid \r\n" + 
				"	) thpc ON thpc.fpersonid= temp.personId";
		
//		String attendanceSql ="/*dialect*/ \r\n" + 
//				"	SELECT DISTINCT\r\n" + 
//				"		a.FAttendanceDate attendDate,\r\n" + 
//				"		a.FProposer personId,\r\n" + 
//				"		a.FAdminOrgUnitId orgId,\r\n" + 
//				"		a.FAttendanceValue abnormalCount,\r\n" + 
//				"		c.fname_l1 reason\r\n" + 
//				"	FROM\r\n" + 
//				"		T_HR_ATS_AbnormalAttendance a\r\n" + 
//				"		LEFT JOIN (\r\n" + 
//				"		SELECT\r\n" + 
//				"			FProposer,\r\n" + 
//				"			SUM(CAST(FAttendanceValue AS INT)) AS COUNT \r\n" + 
//				"		FROM\r\n" + 
//				"			T_HR_ATS_AbnormalAttendance \r\n" + 
//				"		WHERE\r\n" + 
//				"			FAttendanceDate >= '2023-11-01' \r\n" + 
//				"			AND FAttendanceDate <= '2023-11-30' \r\n" + 
//				"		GROUP BY\r\n" + 
//				"			FProposer \r\n" + 
//				"		HAVING\r\n" + 
//				"			SUM(CAST(FAttendanceValue AS INT))  > 3 \r\n" + 
//				"		) b ON a.FProposer= b.FProposer\r\n" + 
//				"		LEFT JOIN T_HR_ATS_AttendanceProject c ON c.fid= a.FattendanceProject \r\n" + 
//				"	WHERE\r\n" + 
//				"		a.FStatus= '1' \r\n" + 
//				"		AND a.FOperationStatus= '1' \r\n" + 
//				"		AND a.FAttendanceDate >'2023-11-01'\r\n" + 
//				"		AND a.FAttendanceDate <= '2023-11-30' \r\n" + 
//				"		AND b.count > 3 ";
		
		try {
			// System.out.print(kqSql);
			// 先把部门查出来
			logger.info("AbnormalFacadeControllerBean->attendanceSql->{} ",attendanceSql);
			IRowSet kqRowSet = DbUtil.executeQuery(ctx, attendanceSql);
			Set<String> kqSet = new HashSet<>();
			List<AbnormalInfo> dataList=new ArrayList<>();
			while (kqRowSet.next()) {
				AbnormalInfo info=new AbnormalInfo();
				String fAdminOrgUnitId = kqRowSet.getString("orgId");
				kqSet.add(fAdminOrgUnitId);
				info.setAttendDate(kqRowSet.getString("attendDate"));
				info.setPersonId(kqRowSet.getString("personId"));
				info.setOrgId(kqRowSet.getString("orgId"));
				info.setReason(kqRowSet.getString("reason"));
				info.setAbnormalCount(Integer.valueOf(kqRowSet.getString("abnormalCount")));
				dataList.add(info);
			}
			
			//查询条件的字符串拼接
			String processStr = processStr(kqSet);
			
			//部门负责人 key为人员  value部门，多个部门以,分隔
			Map<String, String> headMap = getHead(ctx,processStr);
			
			//pvc   key为人员  value部门，多个部门以,分隔
			Map<String, String> pvcMap = getPvc(ctx,processStr);
			
//		    //人员统计数
//			Map<String, String> personAndCount = getPersonAndCount(ctx);
			
			//合并部门负责人和pvc  key为收件人id，value为部门id集合
			Map<String, Set<String>> sendPersonIds = mergerPerson(headMap,pvcMap);
			
			//初始化部门集合
			Map<String, String> orgMap = initOrg(ctx);
			
			//初始化人员集合
			Map<String, String> personMap = initPerson(ctx);
			
			
			
			//发送邮件
			sendEmail(ctx,sendPersonIds,dataList,getTitle(getCurrenLastDayDate()),orgMap,personMap);

		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}
	
	/**
	 * 默认查询所有的部门集合
	 * @param ctx
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private Map<String,String> initOrg(Context ctx) throws BOSException, SQLException{
		String sql="select fid orgId,fname_l1 orgName from T_ORG_ADMIN";
		Map<String, String> orgMap = new HashMap<>();
		IRowSet orgRowSet = DbUtil.executeQuery(ctx, sql);
		while (orgRowSet.next()) {
			orgMap.put(orgRowSet.getString("orgId"), orgRowSet.getString("orgName"));
		}
		return orgMap;
	}
	
	/**
	 * 默认查询所有的部门集合
	 * @param ctx
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private Map<String,String> initPerson(Context ctx) throws BOSException, SQLException{
		String sql="select fid pId,fname_l1 pName from T_BD_PERSON ";
		Map<String, String> personMap = new HashMap<>();
		IRowSet personRowSet = DbUtil.executeQuery(ctx, sql);
		while (personRowSet.next()) {
			personMap.put(personRowSet.getString("pId"), personRowSet.getString("pName"));
		}
		return personMap;
	}
	
	
//	/**
//	 * 获取人员与统计
//	 * @return key为人员id  value统计数
//	 * @throws BOSException 
//	 * @throws SQLException 
//	 */
//	private Map<String,String> getPersonAndCount(Context ctx) throws BOSException, SQLException{
//		String sumSql="/*dialect*/ SELECT\r\n" + 
//				"FProposer,\r\n" + 
//				"COUNT ( * ) AS COUNT \r\n" + 
//				"FROM\r\n" + 
//				"	T_HR_ATS_AbnormalAttendance \r\n" + 
//				"WHERE\r\n" + 
//				"	FAttendanceDate >= date_trunc ( 'month', CURRENT_DATE - INTERVAL '1 month' ) \r\n" + 
//				"	AND FAttendanceDate <= LAST_DAY (\r\n" + 
//				"	DATE_TRUNC ( 'month', CURRENT_DATE - INTERVAL '1 month' )) \r\n" + 
//				"	AND FStatus = '1' \r\n" + 
//				"	AND FOperationStatus = '1' \r\n" + 
//				"GROUP BY\r\n" + 
//				"	FProposer \r\n" + 
//				"HAVING\r\n" + 
//				"	SUM ( FAttendanceValue ) > 3";
//		
////		String sumSql="/*dialect*/ SELECT\r\n" + 
////				"FProposer,\r\n" + 
////				"COUNT ( * ) AS COUNT \r\n" + 
////				"FROM\r\n" + 
////				"	T_HR_ATS_AbnormalAttendance \r\n" + 
////				"WHERE\r\n" + 
////				"	FAttendanceDate >= '2023-11-01' \r\n" + 
////				"	AND FAttendanceDate <= '2023-11-30' \r\n" + 
////				"	AND FStatus = '1' \r\n" + 
////				"	AND FOperationStatus = '1' \r\n" + 
////				"GROUP BY\r\n" + 
////				"	FProposer \r\n" + 
////				"HAVING\r\n" + 
////				"	SUM(CAST(FAttendanceValue AS INT)) > 3";
//		Map<String, String> countMap = new HashMap<>();
//		IRowSet countRowSet = DbUtil.executeQuery(ctx, sumSql);
//		while (countRowSet.next()) {
//			countMap.put(countRowSet.getString("FProposer"), countRowSet.getString("count"));
//		}
//		return countMap;
//
//	}
//	
	/**
	 * 获取部门负责人
	 * @param numbers
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private Map<String,String> getHead(Context ctx,String processStr) 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.fid AS pId,\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";
		
		logger.info("AbnormalFacadeControllerBean->getHead->sql{} ",sql);
		
		IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		
		while(rs.next()) {
			String pId = rs.getString("pId");
			if(StringUtils.isBlank(pId)) {
				continue;
			}
			
			 
			if(StringUtils.isNotBlank(resultMap.get(pId))) {
				resultMap.put(pId, resultMap.get(pId)+","+rs.getString("oId"));
			}else {
				resultMap.put(pId, rs.getString("oId"));
			}
		}
		return resultMap;
		
	}
	
	/**
	 * 获取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.fid oId,\r\n" + 
				"	org.fnumber orgNumber,\r\n" + 
				"	org.Fname_l1 orgName,\r\n" + 
				"	bp.fnumber pNumber,\r\n" + 
				"	bp.fid pId,\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= '106' and org.fid in("+processStr+")";
		
		logger.info("AbnormalFacadeControllerBean->getPvc->sql{} ",sql);
       IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		
		while(rs.next()) {
			String pId = rs.getString("pId");
			if(StringUtils.isBlank(pId)) {
				continue;
			}
			
			if(StringUtils.isNotBlank(resultMap.get(pId))) {
				resultMap.put(pId, resultMap.get(pId)+","+rs.getString("oId"));
			}else {
				resultMap.put(pId, rs.getString("oId"));
			}
			
		}
		return resultMap;
		
		
	}
	
	/**
	 * 合并部门负责人和pvc
	 * @return
	 */
	private Map<String,Set<String>> mergerPerson(Map<String, String> headMap,Map<String, String> pvcMap ){
		
		Map<String,Set<String>> map=new HashMap<>();
		
		//key为人员id  value为部门id,多个以,分隔
		for(Map.Entry<String, String> entry:headMap.entrySet()) {
			Set<String> set=new HashSet<>();
			String key = entry.getKey();
			String headValues = entry.getValue();
			if(StringUtils.isBlank(headValues)) {
				continue;
			}
			String[] split = headValues.split(",");
			
			for(String str:split) {
				set.add(str);
			}
			map.put(key, set);
		}
		
		
		//key为人员id  value为部门id,多个以,分隔
		for(Map.Entry<String, String> entry:pvcMap.entrySet()) {
			String key = entry.getKey();
			String pvcValues = entry.getValue();
			if(StringUtils.isBlank(pvcValues)) {
				continue;
			}
			String[] split = pvcValues.split(",");
			Set<String> set = map.get(key);
			
			if(set==null || set.size()==0) {
				set=new HashSet<>();
			}
			for(String str:split) {
				set.add(str);
			}
			map.put(key, set);
		}
		return map;
		
	}
	
	/**
	 * 处理字符串
	 * @param numbers
	 * @return
	 */
	private String processStr(Set<String> ids) {
		String result="";
		StringBuilder sb = new StringBuilder();
        for (String s : ids) {
            sb.append("'").append(s).append("'").append(",");
        }

        if(sb.length()>0){
            sb.deleteCharAt(sb.lastIndexOf(","));
            result=sb.toString();
        }
        return result;
	}
	
	/**
	 * 发送部门负责人邮件
	 * @throws SQLException 
	 */
	private void sendEmail(Context ctx,Map<String, Set<String>> sendPersonIds,List<AbnormalInfo> dataList,String title,Map<String, String> orgMap,Map<String, String> personMap) throws SQLException {

		if(sendPersonIds==null) {
			return;
		}
		
		try {
			//遍历所有的接收人 ，并取对应的部门及相关信息
			Set<Entry<String,Set<String>>> entrySet = sendPersonIds.entrySet();
			for(Map.Entry<String,Set<String>> entry:entrySet) {
				
				//接收人id
				String personId = entry.getKey();
				
				//接收人对应的部门id集合
				Set<String> deptIds = entry.getValue();
				
				if(deptIds==null || deptIds.size()==0) {
					continue;
				}
				
				StringBuilder totalContent = new StringBuilder("<html><head></head><body>");
				totalContent.append("<span>Dear Sir/Madam,</span><br>\r\n" + 
						"		<span>This is attendance exception report of the last month.</span><br>\r\n" + 
						"		<span>Admin employees who has more than 3 abnormal records per month, it will be recorded in this exception report. It’s suggested to remind your team members to complete the leave application, business trip through Kingdee system by the end of each month to ensure the accuracy of the report.</span><br>\r\n" + 
						"		<span>Should you have any question, please do not hesitate to contact HR "+getHrEmail(ctx)+".</span><br>");
				StringBuilder detailContent=new StringBuilder();
				totalContent.append(
						"<table border=\'1\' cellspacing=\'0\' style=\'border:solid 1px #E8F2F9;font-size=8px;;font-size:10px;\'>");
				totalContent.append(
						"<tr style=\'background-color: #428BCA; color:#ffffff\'><th>Month月份</th><th>Name姓名</th><th>Department部门</th><th>AbnormalTimes考勤异常次数</th></tr>");
				//通过部门拿下面的人
				for(String deptId:deptIds) {
					//考勤明细数据 key为考勤明细中的姓名 value为对应的考勤异常数据
					Map<String, List<AbnormaAttendanceDetailInfo>> detailMap = processDetail(dataList,deptId,orgMap,personMap);
					
					//考勤统计数据 key为姓名 value对应为统计数据
					Map<String, AbnormaAttendanceInfo> totalMap = processInfo(detailMap);
					
					if(totalMap==null || detailMap==null) {
						continue;
					}
					
					//构建统计数据
					if(totalMap!=null && totalMap.size()>0) {
						Set<Entry<String,AbnormaAttendanceInfo>> totalEntrySet = totalMap.entrySet();
						for(Map.Entry<String,AbnormaAttendanceInfo> totalEntry:totalEntrySet) {
							
							AbnormaAttendanceInfo info = totalEntry.getValue();
							totalContent.append("<tr>");
							totalContent.append("<td>" + getCurrenLastDayDate() + "</td>"); // 第一列
							totalContent.append("<td>" + info.getName() + "</td>"); // 第二列
							totalContent.append("<td>" + info.getDept() + "</td>"); // 三列
							totalContent.append("<td>" + info.getCount() + "</td>"); // 第四列
							totalContent.append("</tr>");
								
						}
					
					}
					
					
					//构建明细数据
					if(detailMap!=null && detailMap.size()>0) {
						Set<Entry<String,List<AbnormaAttendanceDetailInfo>>> detailEntrySet = detailMap.entrySet();
						for(Map.Entry<String,List<AbnormaAttendanceDetailInfo>> detailEntry:detailEntrySet) {
							String personName = detailEntry.getKey();
							List<AbnormaAttendanceDetailInfo> detailList = detailEntry.getValue();
							
							detailContent.append(
									"<p style=\"font-size:10px;\">" + totalMap.get(personName).getName() + " of "+detailList.get(0).getDept()+" had "
											+ totalMap.get(personName).getCount() + " abnormal records in " + getCurrenLastDayDate() + "</p>");
							detailContent.append(
									"<table border=\'1\' cellspacing=\'0\' style=\'border:solid 1px #E8F2F9;font-size=8px;;font-size:10px;\'>");
							detailContent.append(
									"<tr style=\'background-color: #428BCA; color:#ffffff\'><th>Name姓名</th><th>Department部门</th><th>AbnormalDate日期 </th><th>AbnoralReason考勤异常原因</th></tr>");// <th>AbnoralReason考勤异常原因</th>
							
							if(detailList==null || detailList.size()==0) {
								continue;
							}
							
							for(AbnormaAttendanceDetailInfo info:detailList) {
								detailContent.append("<tr>");
								detailContent.append("<td>" + info.getName() + "</td>"); // 第一列
								detailContent.append("<td>" + info.getDept() + "</td>"); // 第二列
								detailContent.append("<td>" + info.getDate().substring(0, 10)
										+ "</td>"); // 三列
								detailContent.append("<td>" + info.getReason()+";"+info.getAbnormalCount() + "</td>"); // 第四列
								detailContent.append("</tr>");
							}
							detailContent.append("</table>");
							
						}
						
						
					}
					
				}
				totalContent.append("</table>");
				String content = (totalContent.append(detailContent).append("</body></html>")).toString();
				logger.info("GtiitOrgAdminService->sendHead->content{} ",content);
				try {
					//发送邮件
					SendUtils.msgSend(ctx, title, PriorityEnum.HIGHT_VALUE, false, content, personId,
							BOSMsgTypeEnum.V_TYPE_EMAIL, null, null, MimeTypeEnum.HTML);
					
				}catch(Exception e) {
					logger.info("AbnormalFacadeControllerBean->SendUtils.msgSend->{} ",e);
				}finally {
					//发送完清理
					totalContent=new StringBuilder();
					detailContent=new StringBuilder();
				}
			}
			
		}catch(Exception e) {
			logger.info("AbnormalFacadeControllerBean->sendHead->{} ",e);
		}
		
	}
	
	/**
	 * 构建考勤异常明细数据
	 * @param rowSet
	 * @param sendPersonIds
	 * @return
	 * @throws SQLException
	 */
	private Map<String,List<AbnormaAttendanceDetailInfo>> processDetail(List<AbnormalInfo> dataList,String deptId,Map<String, String> orgMap,Map<String, String> personMap) throws SQLException{
		//key为异常明细姓名 value是对应的人员集合
		Map<String,List<AbnormaAttendanceDetailInfo>> map=new HashMap<>();
		if(dataList==null || StringUtils.isBlank(deptId) ) {
			return null;
		}
		
		for(AbnormalInfo ab:dataList) {
			String orgId = ab.getOrgId();
			if(deptId.equals(orgId)) {
				String personName = personMap.get(ab.getPersonId());
				List<AbnormaAttendanceDetailInfo> list = map.get(personName);
				AbnormaAttendanceDetailInfo info=new AbnormaAttendanceDetailInfo();
				if(list==null || list.size()==0) {
					list=new ArrayList<>();
				}
				info.setDate(ab.getAttendDate());
				info.setName(personMap.get(ab.getPersonId()));
				info.setDept(orgMap.get(ab.getOrgId()));
				info.setReason(ab.getReason());
				info.setPersonId(ab.getPersonId());
				info.setAbnormalCount(ab.getAbnormalCount());
				list.add(info);
				map.put(personName, list);
			}
			
		}
		return map;
	}
	
	/**
     * 构建考勤统计数据
     * @param detailMap
     * @return
     */
    private Map<String, AbnormaAttendanceInfo> processInfo(Map<String,List<AbnormaAttendanceDetailInfo>> detailMap){
        //key为人员姓名  value为对应的人员统计数据
    	Map<String,AbnormaAttendanceInfo> map=new HashMap<>();
        if(detailMap==null ) {
        	return null;
        }
        Set<Map.Entry<String,List<AbnormaAttendanceDetailInfo>>> entrySet = detailMap.entrySet();
        for(Map.Entry<String,List<AbnormaAttendanceDetailInfo>> entry:entrySet) {
            String personName = entry.getKey();
            List<AbnormaAttendanceDetailInfo> detailList = entry.getValue();
            //考勤统计集合
            if(detailList==null || detailList.size()==0) {
            	continue;
            }
            for(AbnormaAttendanceDetailInfo detailInfo:detailList) {
            	 AbnormaAttendanceInfo info = map.get(personName);
                 if(info!=null) {
                 	info.setCount((info.getCount()+detailInfo.getAbnormalCount()));
                 }else {
                 	info=new AbnormaAttendanceInfo();
                 	info.setName(detailInfo.getName());
                 	info.setDept(detailInfo.getDept());
                 	info.setMonth(getCurrenLastDayDate());
                 	info.setCount(detailInfo.getAbnormalCount());
                 }
                 map.put(personName, info);
            }
        }
        return map;


    }
    
	
	/**
	 * 获取上个月的月份
	 * @return
	 */
	private String getCurrenLastDayDate() {
		// 获取当前日期
		LocalDate today = LocalDate.now();
		System.out.println("今天的日期是: " + today);
		// 获取上个月的第一天
		LocalDate firstDayOfLastMonth = today.minusMonths(1);
		System.out.println("上个月的第一天是: " + firstDayOfLastMonth);
		// 定义日期格式为"yyyy/mm"
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM");
		// 将日期格式化为指定格式的字符串
		return firstDayOfLastMonth.format(formatter);
			
	}
	
	/**
	 * 获取title
	 * @param formattedDate
	 * @return
	 */
	private String getTitle(String formattedDate) {
		String replace = formattedDate.replace("/", "");  
		return "Attendance Alert Report – "+replace;
	}
	
	/**
	 * 获取HR邮箱地址
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private String getHrEmail(Context ctx) throws BOSException, SQLException {
		String sql="select fname_l1 name from T_HR_ATS_OverTimeReason where fnumber='GTYJ001'";
		 IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
			String hrEmial="";
			while(rs.next()) {
				String name = rs.getString("name");
				if(StringUtils.isBlank(name)) {
					hrEmial="Carleen(carleen.wu@gtiit.edu.cn,88077081)";
				}else {
					hrEmial=name;
				}
		
				
			}
			return hrEmial;
	}
	
	

	// 拼接html
//	public void emailTable(IRowSet bumenRowSet, Set<String> bumenSet, String ReceiverID, Map<String, String> countmap,
//			Context ctx) {
//		int size = bumenSet.size();
//		String pid = null;
//		int sum = 0;
//		int count = 0;
//		try {
//			for (String element : bumenSet) {
//				// 创建一个map部门负责人作为key set存储人员
//				Map<String, Set<String>> darmentMap = new HashMap<>();
//				Set<String> darmentSet = new HashSet<>();
//				// 存储人员姓名的Set用于拼接html
//				Set<String> peronSet = new HashSet<>();
//				// map存储人员id和姓名用于拼接html
//				Map<String, String> personMap = new HashMap<>();
//				bumenRowSet.beforeFirst();
//				while (bumenRowSet.next()) {
//					String bumperonids = bumenRowSet.getString(ReceiverID);
//					// 负责人id作为key 只有负责人id相等才存set，每次for循环进来保证key都只有一个
//					if (!StringUtils.isBlank(bumperonids)) {
//
//						if (bumperonids.equals(element)) {
//							darmentSet.add(bumenRowSet.getString("FProposer"));
//							personMap.put(bumenRowSet.getString("FProposer"), bumenRowSet.getString("peronName"));
//
//						}
//					}
//				}
//				darmentMap.put(element, darmentSet);
//				// 部门负责人id为key，人员为vlue
//				Map<String, String> kqMap = new HashMap<>();
//				StringBuilder content = new StringBuilder("<html><head></head><body>");
//				content.append("<span>Dear Sir/Madan,</span><br>\r\n" + 
//						"		<span>This is attendance exception report of the last month.</span><br>\r\n" + 
//						"		<span>Admin employees who has more than 3 abnormal records per month, it will be recorded in this exception report. It’s suggested to remind your team members to complete the leave application, business trip through Kingdee system by the end of each month to ensure the accuracy of the report.</span><br>\r\n" + 
//						"		<span>Should you have any question, please do not hesitate to contact HR Carleen(carleen.wu@gtiit.edu.cn,88077081).</span><br>");
//				boolean isFirst = true;
//				boolean two = false;
//				bumenRowSet.beforeFirst();
//				while (bumenRowSet.next()) {
//					// 部门负责人id
//					String bumperonid = bumenRowSet.getString(ReceiverID);
//					String personid = bumenRowSet.getString("FProposer");
//					String darmentID = bumenRowSet.getString("fAdminOrgUnitId");
//					if (bumperonid != null) {
//
//						// 部门负责人id相同才能进1CV1Xix+Qua9UEeo/uZ6TIDvfe0=
//						// 进来的时候bumperonid和element比较，进来之后isFirst设置false 所以不会重复
//						if (bumperonid.equals(element)) {
//							// 第一次先拼接html
//							if (isFirst) {
//								count++;
//								isFirst = false;
//								two = true;
//								kqMap.put(bumperonid, personid);
//								// 去除set中的元素 去除第一个拼接html的人员
//								darmentSet.remove(kqMap.get(bumperonid));
//								pid = bumperonid;
//								content.append(
//										"<table border=\'1\' cellspacing=\'0\' style=\'border:solid 1px #E8F2F9;font-size=8px;;font-size:10px;\'>");
//								content.append(
//										"<tr style=\'background-color: #428BCA; color:#ffffff\'><th>Month月份</th><th>Name姓名</th><th>Department部门</th><th>AbnormalTimes考勤异常次数</th></tr>");
//								content.append("<tr>");
//								content.append("<td>" + formattedDate + "</td>"); // 第一列
//								content.append("<td>" + bumenRowSet.getString("peronName") + "</td>"); // 第二列
//								content.append("<td>" + bumenRowSet.getString("bumenName") + "</td>"); // 三列
//								content.append("<td>" + bumenRowSet.getString("count") + "</td>"); // 第四列
//								content.append("</tr>");
//								peronSet.add(bumenRowSet.getString("peronName"));
//								continue;
//							}
//							// 1CV1Xix+Qua9UEeo/uZ6TIDvfe0=
//							// if (kqMap.containsKey(bumperonid)) {
//							// String key = kqMap.get(bumperonid);
//							// if (!kqMap.get(bumperonid).equals(personid)) {
//							// }
//							// }
//							// 创建一个map统计异常的数据
//							// Map<String, String> countMap = new HashMap<>();
//							// int tosum=0;
//
//							// 判断负责人的id是为map的key
//							if (darmentMap.containsKey(bumperonid)) {
//								for (String key : darmentMap.keySet()) {
//									// 因为负责人id一次循环只有一个 所以只要判断set中是否存在人员id 存在就拼接html
//									Set<String> valueSet = darmentMap.get(key);
//									// 判断人员是否在set中
//									if (valueSet.contains(personid)) {
//										content.append("<tr>");
//										content.append("<td>" + formattedDate + "</td>"); // 第一列
//										content.append("<td>" + bumenRowSet.getString("peronName") + "</td>"); // 第二列
//										content.append("<td>" + bumenRowSet.getString("bumenName") + "</td>"); // 三列
//										content.append("<td>" + bumenRowSet.getString("count") + "</td>"); // 第四列
//										content.append("</tr>");
//										// 进来的人员id可能重复，拼接完之后去除set中这个元素
//										darmentSet.remove(personid);
//										peronSet.add(bumenRowSet.getString("peronName"));
//										continue;
//									}
//
//								}
//
//							}
//						}
//					}
//				}
//				// 如果上个表有就是true 就需要拼接明细
//				if (two) {
//
//					content.append("</table>");
//				}
//				// // 拼接姓名的文字
//				//
//				// content.append("<p style=\"font-size:10px;\">" + person
//				// + "of Human Resources Department had 5 abnormal records in " + formattedDate
//				// + "</p>");
//				// personset遍历拼接
//
//				// 遍历map拿key和统计条数的mapkey比较如果相等就评价html
//				for (String personkey : personMap.keySet()) {
//
//					String perosnvalue = personMap.get(personkey);
//
//					for (String countkey : countmap.keySet()) {
//
//						String countvalue = countmap.get(personkey);
//						if (personkey.equals(countkey)) {
//							// 拼接姓名和统计条数
//
//							content.append(
//									"<p style=\"font-size:10px;\">" + perosnvalue + "of Human Resources Department had "
//											+ countvalue + " abnormal records in " + formattedDate + "</p>");
//							content.append(
//									"<table border=\'1\' cellspacing=\'0\' style=\'border:solid 1px #E8F2F9;font-size=8px;;font-size:10px;\'>");
//							content.append(
//									"<tr style=\'background-color: #428BCA; color:#ffffff\'><th>Name姓名</th><th>Department部门</th><th>AbnormalDate日期 </th><th>AbnoralReason考勤异常原因</th></tr>");// <th>AbnoralReason考勤异常原因</th>
//							String peronname = null;
//							String attenDate = null;
//							boolean first = true;
//							// 再次做个表格拼接 明细
//							bumenRowSet.beforeFirst();
//							while (bumenRowSet.next()) {
//								// 获取负责人id和 负责人id
//								String bumperonid = bumenRowSet.getString(ReceiverID);
//								String personid = bumenRowSet.getString("FProposer");
//								String danceDate = bumenRowSet.getString("FAttendanceDate").substring(0, 10);
//								for (Map.Entry<String, String> entry : kqMap.entrySet()) {
//									String key = entry.getKey();
//									String value = entry.getValue();
//									// 判断是否在同一个负责人下，是的话就拼接
//									if (!StringUtils.isBlank(bumperonid)) {
//										// 数据拼接可能会有重复需要判断做处理
//										if (bumperonid.equals(key)) {
//											// 第一次进来先拼接 并且人员要相等
//											if (first&&personkey.equals(personid)) {
//												first = false;
//												content.append("<tr>");
//												content.append("<td>" + bumenRowSet.getString("peronName") + "</td>"); // 第一列
//												content.append("<td>" + bumenRowSet.getString("bumenName") + "</td>"); // 第二列
//												content.append("<td>" + bumenRowSet.getString("FAttendanceDate").substring(0, 10)
//														+ "</td>"); // 三列
//												content.append("<td>" + bumenRowSet.getString("lack")
//												+ bumenRowSet.getString("FAttendanceValue") + "</td>"); // 第四列
//												content.append("</tr>");
//												peronname = bumenRowSet.getString("FProposer");
//												attenDate = bumenRowSet.getString("FAttendanceDate").substring(0, 10);
//												break;
//											}
//											// 判断人员和日期是否相等 相等就是以及拼接过的就需要跳出循环
//											if (personid.equals(peronname) && danceDate.equals(attenDate)) {
//												break;
//											} else if(personkey.equals(personid)){
//												content.append("<tr>");
//												content.append("<td>" + bumenRowSet.getString("peronName") + "</td>"); // 第一列
//												content.append("<td>" + bumenRowSet.getString("bumenName") + "</td>"); // 第二列
//												content.append("<td>" + bumenRowSet.getString("FAttendanceDate").substring(0, 10)
//														+ "</td>"); // 三列
//												content.append("<td>" + bumenRowSet.getString("lack")
//												+ bumenRowSet.getString("FAttendanceValue") + "</td>"); // 第四列
//												content.append("</tr>");
//												peronname = bumenRowSet.getString("FProposer");
//												attenDate = bumenRowSet.getString("FAttendanceDate").substring(0, 10);
//												break;
//											}
//											
//										}
//									}
//									
//								}
//								
//							}
//							content.append("</table>");
//							break;
//						}
//
//					}
//
//				}
//
//				content.append("</body></html>");
//				String replace = formattedDate.replace("/", "");  
//				String title = "Attendance Alert Report – "+replace;
//				String contents = null;
//				if (two) {
//
//					contents = content.toString();
//				}
//				System.out.println("Html是" + contents);
//
//				// MsgUtil.msgSend(ctx, title, PriorityEnum.HIGHT_VALUE, false, contents, pid,
//				// BOSMsgTypeEnum.V_TYPE_EMAIL, null, null, MimeTypeEnum.HTML);
//				SendUtils.msgSend(ctx, title, PriorityEnum.HIGHT_VALUE, false, contents, pid,
//						BOSMsgTypeEnum.V_TYPE_EMAIL, null, null, MimeTypeEnum.HTML);
//
//				content = new StringBuilder();
//			}
//		} catch (SQLException | EASBizException | BOSException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
//
//	}

}