package nc.impl.sscpfa.report.useropration;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.pub.sscpfa.report.useropration.UserOprationHandleService;
import nc.vo.bd.workcalendar.CalendarDateType;
import nc.vo.bd.workcalendar.WorkCalendarDateVO;
import nc.vo.bd.workcalendar.WorkCalendarVO;
import nc.vo.pub.BusinessException;
import nc.jdbc.framework.processor.ColumnProcessor;

/**
 * @author gujsh
 * @date 2022-04-12
 * @desc 作业人员作业量报表处理服务接口
 */
public class UserOprationHandleServiceImpl implements UserOprationHandleService {

	private BaseDAO baseDAO = null;

	@Override
	public Map<String, Long> calcEliminatedTime(List<Map<String, Object>> allApproveAndRejectData, List<Map<String, Object>> allHandonAndAdjustTimeData) throws BusinessException {
//		if (allApproveAndRejectData == null) {
//			return null;
//		}
		String calendarSql = "select pk_workcalendar from bd_workcalendar where code='Fssc001' and dr='0' and enablestate='2'";
		String pk_workcalendar = (String) this.getBaseDAO().executeQuery(calendarSql, new ColumnProcessor());
		Map<String, Long> respMap = new HashMap<String, Long>();
		if (allApproveAndRejectData != null) {
			for (int i = 0; i < allApproveAndRejectData.size(); i++) {
				Map<String, Object> map = allApproveAndRejectData.get(i);
				String beignTime = (String) map.get("beigntime");
				String operateTime = (String) map.get("operatetime");
				String pk_sscgroup = (String)map.get("pk_sscgroup");
				String pk_sscuser = (String)map.get("pk_sscuser");
				String key = pk_sscgroup + pk_sscuser;
				long seconds = this.getQueryUnWorkingDaySeconds(pk_workcalendar, beignTime, operateTime);
				Long oldSeconds = respMap.getOrDefault(key, 0L);
				Long newSeconds = oldSeconds + seconds;
				respMap.put(key, newSeconds);
			}
		}
		if (allHandonAndAdjustTimeData != null) {
			for (int i = 0; i < allHandonAndAdjustTimeData.size(); i++) {
				Map<String, Object> map = allHandonAndAdjustTimeData.get(i);
				String beignTime = (String) map.get("beigntime");
				String operateTime = (String) map.get("operatetime");
				String pk_sscgroup = (String)map.get("pk_workinggroup");
				String pk_sscuser = (String)map.get("pk_user");
				String key = pk_sscgroup + pk_sscuser;
				long seconds = this.getQueryUnWorkingDaySeconds(pk_workcalendar, beignTime, operateTime);
				Long oldSeconds = respMap.getOrDefault(key, 0L);
				Long newSeconds = oldSeconds + seconds;
				respMap.put(key, newSeconds);
			}
		}
		return respMap;
	}

	private BaseDAO getBaseDAO() {
		if (this.baseDAO == null) {
			this.baseDAO = new BaseDAO();
		}

		return this.baseDAO;
	}

	// 获取区间内非工作日的总秒数
	private long getQueryUnWorkingDaySeconds(String pk_calendar, String begindate, String enddate) throws DAOException {
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append(" select count(*)");
		sqlBuffer
				.append(" from " + WorkCalendarDateVO.getDefaultTableName() + " "
						+ WorkCalendarDateVO.getDefaultTableName())
				.append(" inner join  " + WorkCalendarVO.getDefaultTableName() + " "
						+ WorkCalendarVO.getDefaultTableName())
				.append(" on  " + WorkCalendarDateVO.getDefaultTableName() + "." + "pk_workcalendar" + "="
						+ WorkCalendarVO.getDefaultTableName() + "." + "pk_workcalendar")
				.append(" where ");
		sqlBuffer.append(WorkCalendarDateVO.getDefaultTableName() + "." + "pk_workcalendar" + "='" + pk_calendar + "'");
		sqlBuffer.append(" and calendardate >= " + WorkCalendarVO.getDefaultTableName() + "." + "begindate");
		sqlBuffer.append(" and calendardate >= '" + begindate + "'");
		sqlBuffer.append(" and calendardate <= '" + enddate + "'");
		sqlBuffer.append(" and (datetype= " + CalendarDateType.WEEKENDDAY.ordinal() + " or datetype= "
				+ CalendarDateType.HOLIDAY.ordinal() + ")");
		Integer result = (Integer) this.getBaseDAO().executeQuery(sqlBuffer.toString(), new ColumnProcessor());
		int days = result == null ? 0 : result;
		long seconds = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		// 判断开始、结束时间是否同一天
		boolean isSameDay = true;
		long diff = 0;
		try {
			diff = this.calcSeconds(begindate, enddate);
			if (diff > 24*60*60) {
				isSameDay = false;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		if (isSameDay) {// 同一天完成
			if (this.isUnWorkingDay(pk_calendar, begindate)) {
				seconds = diff;
			}
		} else {// 非同一天完成
			if (this.isUnWorkingDay(pk_calendar, begindate)) {// 开始时间是非工作日
		        try {
					calendar.setTime(sdf.parse(begindate));
					calendar.add(Calendar.DATE, 1);
					String nextDateTime = sdf.format(calendar.getTime()) + " 00:00:00";
					seconds += this.calcSeconds(begindate, nextDateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if (this.isUnWorkingDay(pk_calendar, enddate) && days > 0) {// 结束时间是非工作日
				try {
					calendar.setTime(sdf.parse(enddate));
					calendar.add(Calendar.DATE, 1);
					String nextDateTime = sdf.format(calendar.getTime()) + " 00:00:00";
					seconds = seconds - this.calcSeconds(enddate, nextDateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		
		if (days > 0) {
			seconds += days * 24 * 60 * 60;
		}
		return seconds;
	}

	// 判断传入日期是否非工作日
	private boolean isUnWorkingDay(String pk_calendar, String datetime) throws DAOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date curDate = null;
		try {
			curDate = sdf.parse(datetime);
			datetime = sdf.format(curDate);
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
		String sql = "select wdate.datetype from bd_workcalendardate wdate where wdate.pk_workcalendar='" + pk_calendar
				+ "' and calendardate = '" + datetime + "'";
		Integer datetype = (Integer) this.getBaseDAO().executeQuery(sql, new ColumnProcessor());
		if ("1".equals(datetype.toString()) || "2".equals(datetype.toString())) {
			return true;
		} else {
			return false;
		}
	}
	
	//计算两个时间相差的秒数
    private long calcSeconds(String startTime, String endTime) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long eTime = df.parse(endTime).getTime();
        long sTime = df.parse(startTime).getTime();
        long diff = (eTime - sTime) / 1000;
        return diff;
    }
}
