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

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.common.EASBizException;
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 com.kingdee.shr.base.syssetting.context.SHRContext;

/**
 * 所有待审批单据的当前审批人状态为离职则提醒
 * 
 * @author ISSUSER
 *
 */
public class DepartStatusFacadeControllerBean extends AbstractDepartStatusFacadeControllerBean {
	private static Logger logger = Logger
			.getLogger("com.kingdee.eas.custom.facade.worktime.DepartStatusFacadeControllerBean");

	@Override
	protected void _departStatus(Context ctx) throws BOSException {

		String title = "Notification of Approver Resignation";
		// 邮件内容
		String content = getContent(ctx);
		try {
			// 收件人
			IRowSet recipientRowSet = getRecipient(ctx);
			while (recipientRowSet.next()) {
				// SendUtils.msgSend(ctx, title, PriorityEnum.HIGHT_VALUE, false, content,
				// "1CV1Xix+Qua9UEeo/uZ6TIDvfe0=",
				// BOSMsgTypeEnum.V_TYPE_EMAIL, null, null, MimeTypeEnum.HTML);
				SendUtils.msgSend(ctx, title, PriorityEnum.HIGHT_VALUE, false, content,
						recipientRowSet.getString("FPSERSONID"), BOSMsgTypeEnum.V_TYPE_EMAIL, null, null,
						MimeTypeEnum.HTML);
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (EASBizException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}

	/**
	 * 查询所有单据的审批人 是离职状态的
	 */
	public IRowSet getApproved(Context ctx) {
		// 获取当前日期
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String strDate = sdf.format(nowDate);
		// 查询所有单据的审批人并且是离职状态的
		StringBuffer approvedSql = new StringBuffer();
		approvedSql.append(
				"SELECT c.fid as personid,c.fnumber as personnumber,c.fname_l1 as name FROM T_HR_EmpLaborRelationHis a left join  T_HR_BDEmployeeType b on a.FLaborRelationStateID=b.fid left join t_bd_person c on a.FPersonID=c.fid");
		approvedSql
				.append(" where b.FinService in('2') and a.FPersonID in (SELECT FPERSONEMPID FROM T_WFR_Assign) and ");
		approvedSql.append("a.FStartDateTime <= '" + strDate + "'");
		approvedSql.append(" and FEndDateTime>='" + strDate + "'");
		IRowSet rs = null;
		try {
			rs = DbUtil.executeQuery(ctx, approvedSql.toString());
		} catch (BOSException e) {
			e.printStackTrace();
		}

		return rs;
	}

	/**
	 * 统计审批人是离职的 单据条数
	 */
	public Map<String, String> getCountBill(Context ctx) {
		// 用set统计处离职的人员
		Set<String> departSet = new HashSet();
		// 存储审批人id和统计数
		Map<String, String> approvedMap = new HashMap();
		IRowSet approvedRowSet = getApproved(ctx);
		try {
			while (approvedRowSet.next()) {

				departSet.add(approvedRowSet.getString("personid"));
			}
			// 审批人是离职的 单据条数
			StringBuffer countBillSql = new StringBuffer();
			countBillSql.append("SELECT count(*) as count, FPERSONEMPID  FROM  T_WFR_Assign  ");
			if (!departSet.isEmpty()) {
				countBillSql.append(" where FPERSONEMPID in (");
				for (String depart : departSet) {
					countBillSql.append("'");
					countBillSql.append(depart);
					countBillSql.append("'");
					countBillSql.append(",");
				}
				// 删除最后一个逗号
				countBillSql.deleteCharAt(countBillSql.length() - 1);
				countBillSql.append(")");
			}
			countBillSql.append(" group by FPERSONEMPID");
			IRowSet countRowSet = DbUtil.executeQuery(ctx, countBillSql.toString());
			while (countRowSet.next()) {
				approvedMap.put(countRowSet.getString("FPERSONEMPID"), countRowSet.getString("count"));
			}
		} catch (SQLException | BOSException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		return approvedMap;
	}

	/**
	 * 查询角色107的人员id 收件人
	 */
	public IRowSet getRecipient(Context ctx) {
		String sql = "SELECT a.FPSERSONID FROM T_WFR_PERSONROLE a left join T_WFR_WFROLE b on a.FROLEID=b.fid where b.FNUMBER='107'";
		IRowSet reRowSet = null;
		try {
			reRowSet = DbUtil.executeQuery(ctx, sql);
		} catch (BOSException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return reRowSet;
	}

	/**
	 * 拼接内容
	 */
	public String getContent(Context ctx) {
		StringBuffer content = new StringBuffer();
		content.append("<html><head></head><body>");
		content.append("<span>Dear HR and IT:</span><br>");
		content.append("<span></span><br>");
		content.append(
				"<span>The following employees are inactive in HR system but there are still some workflows waiting for their approval.</span><br>");
		content.append("<span></span><br>");
		content.append(
				"<span>If the person will be rehired soon, you can ignore this message.After the rehire is finished, the workflow will be normal.</span><br>");
		content.append("<span></span><br>");
		content.append(
				"<span>If the person will not be rehired soon, you need to identify the new approver and notify the system administrator to manually assign the workflow to the new approver.</span><br>");
		 content.append("<span></span><br>");
		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>Person Number</th><th>Name</th><th>Document quantity</th></tr>");
		IRowSet approvedRowSet = getApproved(ctx);
		Map<String, String> countBillMap = getCountBill(ctx);
		try {
			approvedRowSet.beforeFirst();
			while (approvedRowSet.next()) {
				String personId = approvedRowSet.getString("personid");
				// 如果人员id在map里面就拼接
				if (countBillMap.containsKey(personId)) {
					content.append("<tr>");
					content.append("<td>" + approvedRowSet.getString("personnumber") + "</td>"); // 第一列
					content.append("<td>" + approvedRowSet.getString("name") + "</td>"); // 第二列
					content.append("<td>" + countBillMap.get(personId) + "</td>"); // 三列
					content.append("</tr>");
					countBillMap.remove(personId);

				}
			}
			content.append("</body></html>");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return content.toString();
	}

}