package com.ruoyi.wgz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.bgt.domain.BgtProjectRecruit;
import com.ruoyi.bgt.domain.BgtProjectRecruitApply;
import com.ruoyi.bgt.domain.dto.BgtAttendanceDTO;
import com.ruoyi.bgt.domain.dto.BgtAttendanceDetailDTO;
import com.ruoyi.bgt.domain.vo.BgtAttendanceCountVO;
import com.ruoyi.bgt.domain.vo.BgtAttendanceDetailVO;
import com.ruoyi.bgt.domain.vo.BgtAttendanceVO;
import com.ruoyi.bgt.domain.vo.WgzAttendanceRecordVO;
import com.ruoyi.bgt.service.IBgtProjectRecruitApplyService;
import com.ruoyi.bgt.service.IBgtProjectRecruitService;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.util.DataUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fbs.domain.FbsProjectTask;
import com.ruoyi.fbs.service.IFbsProjectTaskService;
import com.ruoyi.wgz.bo.WgzAttendanceQueryBo;
import com.ruoyi.wgz.bo.req.WgzAppSubmitTheClockReq;
import com.ruoyi.wgz.bo.res.WgzAppCardReplacementApplicationRes;
import com.ruoyi.wgz.bo.res.WgzAppPunchTheCalendarRecordRes;
import com.ruoyi.wgz.bo.res.WgzAppUserClockingConditionRes;
import com.ruoyi.wgz.bo.rests.WgzAppCardReplacementApplicationTwo;
import com.ruoyi.wgz.bo.rests.WgzAppPunchTheCalendarRecordThree;
import com.ruoyi.wgz.bo.rests.WgzAppPunchTheCalendarRecordTwo;
import com.ruoyi.wgz.domain.WgzAttendance;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.mapper.WgzAttendanceMapper;
import com.ruoyi.wgz.service.IWgzAttendanceService;
import com.ruoyi.wgz.service.IWgzLeaveService;
import com.ruoyi.wgz.service.IWgzUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考勤打卡Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-20
 */
@Service
public class WgzAttendanceServiceImpl extends ServicePlusImpl<WgzAttendanceMapper, WgzAttendance> implements IWgzAttendanceService {

	//上班打卡状态 0上 1下
	public static final String Clocking = "0";
	public static final String OffDuty= "1";

	@Autowired
	private IBgtProjectRecruitApplyService iBgtProjectRecruitApplyService;

	@Autowired
	private IBgtProjectRecruitService iBgtProjectRecruitService;

	@Autowired
	private  IWgzLeaveService iWgzLeaveService;

	@Autowired
	private IFbsProjectTaskService taskService;

	@Autowired
	private IWgzUserService wgzUserService;


	@Override
    public WgzAttendance queryById(Long id){
        return getById(id);
    }

    @Override
    public TableDataInfo<WgzAttendance> queryPageList(WgzAttendanceQueryBo bo) {
        Page<WgzAttendance> result = page(PageUtils.buildPage(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<WgzAttendance> queryList(WgzAttendanceQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<WgzAttendance> buildQueryWrapper(WgzAttendanceQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WgzAttendance> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getRecruitId() != null, WgzAttendance::getRecruitId, bo.getRecruitId());
        lqw.eq(bo.getUserId() != null, WgzAttendance::getUserId, bo.getUserId());
        lqw.eq(bo.getLeaveMarkId() != null, WgzAttendance::getLeaveMarkId, bo.getLeaveMarkId());
        lqw.eq(bo.getDailyWage() != null, WgzAttendance::getDailyWage, bo.getDailyWage());
        lqw.eq(bo.getDate() != null, WgzAttendance::getDate, bo.getDate());
        lqw.eq(StrUtil.isNotBlank(bo.getPnchOsition()), WgzAttendance::getPnchOsition, bo.getPnchOsition());
        lqw.eq(bo.getClockInTime() != null, WgzAttendance::getClockInTime, bo.getClockInTime());
        lqw.eq(bo.getClockOutTime() != null, WgzAttendance::getClockOutTime, bo.getClockOutTime());
        lqw.eq(bo.getLate() != null, WgzAttendance::getLate, bo.getLate());
        lqw.eq(bo.getLateTime() != null, WgzAttendance::getLateTime, bo.getLateTime());
        lqw.eq(bo.getEarlyLeave() != null, WgzAttendance::getEarlyLeave, bo.getEarlyLeave());
        lqw.eq(bo.getEarlyLeaveTime() != null, WgzAttendance::getEarlyLeaveTime, bo.getEarlyLeaveTime());
        lqw.eq(bo.getMissedIn() != null, WgzAttendance::getMissedIn, bo.getMissedIn());
        lqw.eq(bo.getMissedOut() != null, WgzAttendance::getMissedOut, bo.getMissedOut());
        lqw.eq(StrUtil.isNotBlank(bo.getExceptionType()), WgzAttendance::getExceptionType, bo.getExceptionType());
        return lqw;
    }

    @Override
    public Boolean insert(WgzAttendance bo) {
        WgzAttendance add = BeanUtil.toBean(bo, WgzAttendance.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean update(WgzAttendance bo) {
        WgzAttendance update = BeanUtil.toBean(bo, WgzAttendance.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(WgzAttendance entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }


	/**
	 * APP相关
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */

	@Override
	@Transactional
	public Boolean userSubmitTheClock(WgzAppSubmitTheClockReq req) {
		//1、获取当前用户信息
		Long appUserId = SecurityUtils.getAppUserId();
		//2、获取当前用户所在的工地id
		BgtProjectRecruitApply by = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(appUserId);
		//3、根据工地id得到完整的工地信息
		BgtProjectRecruit appById = iBgtProjectRecruitService.getAppById(by.getId());
//		//4、查看当前用户是否有请假申请，有请假申请并且通过，那就无法进行打卡------------------>此处代码将改写逻辑为：每天凌晨1分的时候直接找出已请假的人然后定时插入数据到打卡记录中标记为请假
//		String formattedDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//		WgzLeave wgzLeave = iWgzLeaveService.FindAskForLeaveOrNotInfo(appUserId, by.getId(), formattedDate);
//		if (wgzLeave != null) { //表示有请假申请
//			LocalDateTime startTime = wgzLeave.getStartTime();
//			LocalDate localDate = startTime.toLocalDate();
//			throw new RuntimeException("您有已通过的请假申请，请假时间为："+localDate);
//		}
		//5、查看当前人、当前工地、当天的打卡记录
		String formattedDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		WgzAttendance we = publicFindByUserIdWait(appUserId, by.getId(), formattedDate);
		String exceptionType = we.getExceptionType();
		if (we.getLeaveMarkId() != null && we.getLeaveMarkId()!= 0) {
			throw new RuntimeException("您有已通过的请假申请，请假时间为："+formattedDate);
		}
		//6、组装完整的打卡信息
		WgzAttendance wgzAttendance = new WgzAttendance().
			setRecruitId(appById.getId()).
			setUserId(appUserId).
			setDailyWage(appById.getRecruitAmount()).
			setDate(LocalDate.now()).
			setPnchOsition(req.getPnchOsition());
		LocalDateTime now = LocalDateTime.now(); //当前完整年月日时分秒
		LocalTime localTime = now.toLocalTime(); //获取时分秒
		if (Objects.isNull(we)) { //表示当天第一次打卡---上班
			wgzAttendance.setClockInTime(now);
			LocalTime beginWorkTime = appById.getBeginWorkTime(); //上班
			if (!localTime.isBefore(beginWorkTime)) {
				wgzAttendance.setLate(1); //迟到
				wgzAttendance.setLateTime(now);
				wgzAttendance.setExceptionType("1,");
			}
		}else{ //表示当天不是第一次打卡---下班
			wgzAttendance.setClockOutTime(now);
			LocalTime endWorkTime = appById.getEndWorkTime(); //下班
			if (!localTime.isAfter(endWorkTime)) {
				wgzAttendance.setEarlyLeave(1); //早退
				wgzAttendance.setEarlyLeaveTime(now);
				wgzAttendance.setExceptionType(exceptionType+"2,");
			}
		}
		return baseMapper.insert(wgzAttendance) > 0;
	}

	@Override
	public WgzAppUserClockingConditionRes userClockingCondition() {
		WgzAppUserClockingConditionRes res = new WgzAppUserClockingConditionRes();
		//1、获取打卡信息
		Long appUserId = SecurityUtils.getAppUserId();
		BgtProjectRecruitApply by = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(appUserId);
		String formattedDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		WgzAttendance wgzAttendance = publicFindByUserIdWait(appUserId, by.getId(), formattedDate);
		//2、获取今日用户打卡状态
		if (Objects.isNull(wgzAttendance)) {
			res.setClockingCondition(0); //上班
		}else{
			res.setClockingCondition(1); //下班
			if (wgzAttendance.getLeaveMarkId()!= null && wgzAttendance.getLeaveMarkId()!= 0) {
				res.setClockingCondition(2); //请假
			}
		}
		return res;
	}

	@Override
	public WgzAppPunchTheCalendarRecordRes userPunchTheCalendarRecord() {
		Long appUserId = SecurityUtils.getAppUserId();
		BgtProjectRecruitApply by = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(appUserId);
		//1、获取当月的所有日期
		LocalDate currentDate = LocalDate.now();
		LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
		LocalDate lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
		List<LocalDate> dates = new ArrayList<>();
		LocalDate tempDate = firstDayOfMonth;
		while (!tempDate.isAfter(lastDayOfMonth)) {
			dates.add(tempDate);
			tempDate = tempDate.plusDays(1);
		}
		String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
		//2、获取当前人、当前工地、当前月的所有考勤记录
		LambdaQueryWrapper<WgzAttendance> apply = new LambdaQueryWrapper<WgzAttendance>().
			eq(WgzAttendance::getUserId, appUserId).
			eq(WgzAttendance::getRecruitId, by.getId()).
			apply("DATE_FORMAT(date, '%Y-%m') = {0}", format);
		List<WgzAttendance> wgzAttendances = baseMapper.selectList(apply);
		//3、组装返回数据
		Map<LocalDate, WgzAppPunchTheCalendarRecordTwo> mp = new HashMap<>();
		for (LocalDate date : dates) {
			for (WgzAttendance wa : wgzAttendances) {
				WgzAppPunchTheCalendarRecordTwo two = new WgzAppPunchTheCalendarRecordTwo().setId(wa.getId());
				LocalDate clockDate = wa.getDate();
				if (clockDate.equals(date)) {
					//上班
					if (wa.getClockInTime() != null) {
						two.setNum(1);
						two.setSb(sbOrXb(wa, 1));
					}
					//下班
					if (wa.getClockOutTime() != null) {
						two.setNum(2);
						two.setManHour(calculateWorkingHours(wa.getClockInTime(), wa.getClockOutTime()));
						two.setSb(sbOrXb(wa, 2));
					}
				}
				mp.put(date, two);
			}
		}
		return  new WgzAppPunchTheCalendarRecordRes().setMp(mp);
	}

	@Override
	public WgzAttendance findById(Long id) {
		return getById(id);
	}

	@Override
	public WgzAppCardReplacementApplicationRes userCardReplacementApplication() {
		//1、获取当前用户信息
		Long appUserId = SecurityUtils.getAppUserId();
		//2、获取当前用户所在的工地id
		BgtProjectRecruitApply by = iBgtProjectRecruitApplyService.selectByUserIdProjectRecruitApplyId(appUserId);
		//3、根据工地id得到完整的工地信息
		BgtProjectRecruit appById = iBgtProjectRecruitService.getAppById(by.getId());
		//4、查询所有缺卡、迟到、早退的打卡记录
		LambdaQueryWrapper<WgzAttendance> apply = new LambdaQueryWrapper<WgzAttendance>().
			eq(WgzAttendance::getUserId, appUserId).
			eq(WgzAttendance::getRecruitId, by.getId()).
			eq(WgzAttendance::getRecruitId, by.getId())
			.and(wrapper -> wrapper
				.eq(WgzAttendance::getLate, 1)
				.or()
				.eq(WgzAttendance::getEarlyLeave, 1)
				.or()
				.eq(WgzAttendance::getMissedIn, 1)
				.or()
				.eq(WgzAttendance::getMissedOut, 1)
			);
		List<WgzAttendance> wgzAttendances = baseMapper.selectList(apply);
		//4、将这些数据进行拆分
		ArrayList<WgzAppCardReplacementApplicationTwo> list = new ArrayList<>();
		for (WgzAttendance wgzAttendance : wgzAttendances) {
			String exceptionType = wgzAttendance.getExceptionType();
			if (exceptionType.contains("1")) { // 迟到
				addRecord(wgzAttendance, 1, wgzAttendance.getClockInTime(), list);
			}
			if (exceptionType.contains("2")) { // 早退
				addRecord(wgzAttendance, 2, wgzAttendance.getClockOutTime(), list);
			}
			if (exceptionType.contains("3")) { // 上班缺卡
				addRecord(wgzAttendance, 3, LocalDateTime.from(appById.getBeginWorkTime()), list);
			}
			if (exceptionType.contains("4")) { // 下班缺卡
				addRecord(wgzAttendance, 4, LocalDateTime.from(appById.getEndWorkTime()), list);
			}
		}
		return null;
	}

	@Override
	public Integer attendanceDetail(Long userId,Long recruitId, Integer num){
		LambdaQueryWrapper<WgzAttendance> apply = new LambdaQueryWrapper<WgzAttendance>().
			eq(WgzAttendance::getUserId, userId).
			eq(WgzAttendance::getRecruitId, recruitId).and(wrapper -> wrapper
				.isNotNull(WgzAttendance::getClockInTime)
				.or()
				.isNotNull(WgzAttendance::getClockOutTime)
			);
		apply.orderByAsc(WgzAttendance::getDate);
		if (num!=null && num>0) { //表示查询指定天数的打卡记录,否则查询所有
			apply.last("LIMIT " + num);
		}
		return baseMapper.selectCount(apply);
	}


	@Override
	public List<BgtAttendanceCountVO> countByTaskId(Long taskId, LocalDate beginDate, LocalDate endDate) {
		return baseMapper.countByTaskId(taskId, beginDate, endDate);
	}

	@Override
	public BgtAttendanceVO attendanceDetail(BgtAttendanceDTO dto) {
		BgtAttendanceVO bgtAttendanceVO = new BgtAttendanceVO();
		FbsProjectTask task = taskService.getById(dto.getTaskId());
		bgtAttendanceVO.setTaskId(task.getId());
		bgtAttendanceVO.setTaskName(task.getTaskName());
		LocalDate date = dto.getDate();

		LocalDate startData = null;
		LocalDate endData = null;

		if(dto.getDateType().equals(DateUtils.DAY)){
			// 获取本月开始日期
			startData = date.with(TemporalAdjusters.firstDayOfMonth());
			endData = date;

			List<BgtAttendanceCountVO> countVOS = countByTaskId(dto.getTaskId(), startData, endData);
			if(CollectionUtil.isNotEmpty(countVOS)){
				bgtAttendanceVO.setCountVOs(DataUtil.fillMissingDates(countVOS, startData, endData));
				BgtAttendanceCountVO countVO = countVOS.stream()
					.filter(vo -> vo.getDate().isEqual(date))
					.findFirst().orElse(null);
				bgtAttendanceVO.setReportToDutyNum(countVO.getReportToDutyNum());
				bgtAttendanceVO.setTotalNum(countVO.getTotalNum());
				bgtAttendanceVO.setAbsenceDutyNum(countVO.getTotalNum()-countVO.getReportToDutyNum());
			}
		}else if(dto.getDateType().equals(DateUtils.MONTH)){
			// 获取本年开始日期
			startData = date.with(TemporalAdjusters.firstDayOfYear());
			endData = date.with(TemporalAdjusters.lastDayOfMonth());
			List<BgtAttendanceCountVO> countVOS = countByTaskId(dto.getTaskId(), startData, endData);
			if(CollectionUtil.isNotEmpty(countVOS)){
				bgtAttendanceVO.setCountVOs(DataUtil.statisticsByMonth(countVOS,startData, endData));
			}
			BgtAttendanceCountVO countVO = countVOS.stream()
				.filter(vo -> YearMonth.from(vo.getDate()).equals(YearMonth.from(date)))
				.findFirst().orElse(null);
			bgtAttendanceVO.setReportToDutyNum(countVO.getReportToDutyNum());
			bgtAttendanceVO.setTotalNum(countVO.getTotalNum());
			bgtAttendanceVO.setAbsenceDutyNum(countVO.getAbsenceDutyNum());
		}
		getLateAndLeave(bgtAttendanceVO, startData, endData);
		return bgtAttendanceVO;
	}

	public void getLateAndLeave(BgtAttendanceVO vo,LocalDate startDate, LocalDate endDate){
		List<BgtProjectRecruit> bgtProjectRecruits = iBgtProjectRecruitService.getBaseMapper().selectList(Wrappers.<BgtProjectRecruit>lambdaQuery()
			.eq(BgtProjectRecruit::getTaskId, vo.getTaskId()));
		List<Long> recruitIds = bgtProjectRecruits.stream().map(BgtProjectRecruit::getId).collect(Collectors.toList());
		Integer late = baseMapper.selectCount(Wrappers.<WgzAttendance>lambdaQuery().eq(WgzAttendance::getLate, 1)
			.in(WgzAttendance::getRecruitId, recruitIds).between(WgzAttendance::getDate, startDate, endDate));
		Integer leave = baseMapper.selectCount(Wrappers.<WgzAttendance>lambdaQuery().isNotNull(WgzAttendance::getLeaveMarkId)
			.in(WgzAttendance::getRecruitId, recruitIds).between(WgzAttendance::getDate, startDate, endDate));
		vo.setLateNum(late);
		vo.setLeaveNum(leave);
	}

//	@Override
//	public WgzAttendance findByUserIdWait(Long appUserId, Long recruitId, String date) {
//		LambdaQueryWrapper<WgzAttendance> qw = new LambdaQueryWrapper<>();
//		qw.eq(WgzAttendance::getRecruitId,recruitId);
//		qw.eq(WgzAttendance::getUserId,appUserId);
//		return null;
//	}

	/**
	 * 获取指定人、指定工地、指定日期的打卡记录
	 * @param appUserId 务工者用户id
	 * @param recruitId 工地id
	 * @param date	具体日期
	 * @return WgzAttendance
	 */
	public WgzAttendance publicFindByUserIdWait(Long appUserId, Long recruitId, String date) {
		LambdaQueryWrapper<WgzAttendance> qw = new LambdaQueryWrapper<>();
		qw.eq(WgzAttendance::getRecruitId,recruitId);
		qw.eq(WgzAttendance::getUserId,appUserId);
		qw.eq(WgzAttendance::getDate,date);
		return baseMapper.selectOne(qw);
	}

	/**
	 * 计算两个时间之间的工作小时数
	 *
	 * @param startTime 开始时间
	 * @param endTime   结束时间
	 * @return 工作小时数
	 */
	public double calculateWorkingHours(LocalDateTime startTime, LocalDateTime endTime) {
		// 计算两个时间之间的持续时间
		Duration duration = Duration.between(startTime, endTime);

		// 将持续时间转换为分钟
		long minutes = duration.toMinutes();

		// 将分钟转换为小时
		double hours = (double) minutes / 60;

		// 使用 DecimalFormat 保留两位小数
		DecimalFormat df = new DecimalFormat("#.00");
		String formattedHours = df.format(hours);

		// 将格式化后的字符串转换回 double 类型
		return Double.parseDouble(formattedHours);
	}

	/**
	 * 组装上班、下班打卡记录
	 * @param wa 打卡记录
	 * @param num 1上班 2下班
	 * @return WgzAppPunchTheCalendarRecordThree
	 */
	public WgzAppPunchTheCalendarRecordThree sbOrXb( WgzAttendance wa,int num) {
		WgzAppPunchTheCalendarRecordThree sbb = new WgzAppPunchTheCalendarRecordThree().
			setClockingTime(wa.getClockInTime()).
			setPnchOsition(wa.getPnchOsition()).
			setClockingCondition(0); //正常
		//判断是否请假
		if (wa.getLeaveMarkId()!=null && wa.getLeaveMarkId()!=0) {
			sbb.setClockingCondition(7);
		}
		if (num == 1){
			//判断上班迟到
			if (wa.getLate() == 1) {
				sbb.setClockingCondition(1);
			}
			//判断是否上班补卡
			if (wa.getExceptionType().contains("5")) {
				sbb.setClockingCondition(5);
			}
		}
		if (num == 2){
			//判断下班早退
			if (wa.getEarlyLeave() == 1) {
				sbb.setClockingCondition(2);
			}
			//判断是否下班补卡
			if (wa.getExceptionType().contains("6")) {
				sbb.setClockingCondition(6);
			}
		}
		return sbb;
	}

	/**
	 * 补卡
	 * @param wgzAttendance 打卡记录
	 * @param type 1上班 2下班
	 * @param fillingDataTime 补卡时间
	 * @param list 补卡记录
	 */
	private void addRecord(WgzAttendance wgzAttendance, int type, LocalDateTime fillingDataTime, List<WgzAppCardReplacementApplicationTwo> list) {
		LocalDate date = wgzAttendance.getDate();
		DayOfWeek dayOfWeek = date.getDayOfWeek();
		String week = dayOfWeek.toString();
		WgzAppCardReplacementApplicationTwo two = new WgzAppCardReplacementApplicationTwo()
			.setId(wgzAttendance.getId())
			.setType(type)
			.setFillingData(date)
			.setWeek(week)
			.setFillingDataTime(fillingDataTime);
		list.add(two);
	}

	@Override
	public BgtAttendanceDetailVO bgtAttendanceDetail(BgtAttendanceDetailDTO dto) {
		BgtAttendanceDetailVO bgtAttendanceDetailVO = new BgtAttendanceDetailVO();

		WgzUser wgzUser = wgzUserService.getById(dto.getUserId());
		bgtAttendanceDetailVO.setUserId(wgzUser.getUserId());
		bgtAttendanceDetailVO.setUsername(wgzUser.getUsername());
		bgtAttendanceDetailVO.setAvatarName(wgzUser.getAvatarName());

		List<BgtProjectRecruit> bgtProjectRecruits = iBgtProjectRecruitService.getBaseMapper().selectList(Wrappers.<BgtProjectRecruit>lambdaQuery()
			.eq(BgtProjectRecruit::getTaskId, dto.getTaskId()));
		List<Long> recruitIds = bgtProjectRecruits.stream().map(BgtProjectRecruit::getId).collect(Collectors.toList());

		BgtProjectRecruitApply recruitApply = iBgtProjectRecruitApplyService.getById(recruitIds.get(0));
		bgtAttendanceDetailVO.setEntryTime(recruitApply.getEntryTime());
		bgtAttendanceDetailVO.setStatus(recruitApply.getStatus());

		LambdaQueryWrapper<WgzAttendance> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(WgzAttendance::getUserId,dto.getUserId());

		wrapper.in(WgzAttendance::getRecruitId,recruitIds);
		LocalDate date = dto.getDate();
		LocalDate startDate = date.with(TemporalAdjusters.firstDayOfMonth());
		LocalDate endData = date.with(TemporalAdjusters.lastDayOfMonth());
		wrapper.between(WgzAttendance::getDate,startDate,endData);
		List<WgzAttendance> wgzAttendances = baseMapper.selectList(wrapper);
		// 创建SimpleDateFormat对象，格式化日期为中文星期
		SimpleDateFormat sdf = new SimpleDateFormat("EEEE", java.util.Locale.CHINESE);

		//获取招工打卡时间
		List<BgtProjectRecruit> list = iBgtProjectRecruitService.list(Wrappers.<BgtProjectRecruit>lambdaQuery().in(BgtProjectRecruit::getId));
		Map<Long, BgtProjectRecruit> recruitMap = list.stream().collect(Collectors.toMap(BgtProjectRecruit::getId, recruit -> recruit));


		List<WgzAttendanceRecordVO> lateRecords = new ArrayList<>();
		List<WgzAttendanceRecordVO> earlyLeaveRecords= new ArrayList<>();
		List<WgzAttendanceRecordVO> missRecords= new ArrayList<>();
		List<WgzAttendanceRecordVO> records= new ArrayList<>();


		for (WgzAttendance wgzAttendance:wgzAttendances){
			WgzAttendanceRecordVO recordVO = new WgzAttendanceRecordVO();
			recordVO.setDate(wgzAttendance.getDate());
			recordVO.setWeek(sdf.format(date));
			if(wgzAttendance.getMissedIn()==0 && wgzAttendance.getMissedOut()==0){
				recordVO.setDay(1D);
				records.add(recordVO);
			}else if(wgzAttendance.getMissedIn()==1 && wgzAttendance.getMissedOut()==1){
				recordVO.setDay(0D);
			}else {
				recordVO.setDay(0.5D);
				records.add(recordVO);
			}
			BgtProjectRecruit recruit = recruitMap.get(wgzAttendance.getRecruitId());
			LocalDateTime clockInTime = wgzAttendance.getClockInTime();
			LocalDateTime clockOutTime = wgzAttendance.getClockOutTime();
			LocalTime beginWorkTime = recruit.getBeginWorkTime();
			LocalTime endWorkTime = recruit.getEndWorkTime();
			if (wgzAttendance.getLate() == 1) {
				WgzAttendanceRecordVO LateRecordVO = BeanUtil.copyProperties(recordVO, WgzAttendanceRecordVO.class);
				LateRecordVO.setTime(clockInTime.toLocalTime());
				LateRecordVO.setMinutes(DataUtil.getMinutes(clockInTime,beginWorkTime));
				lateRecords.add(LateRecordVO);
			}
			if (wgzAttendance.getEarlyLeave() == 1) {
				WgzAttendanceRecordVO earlyLeaveRecordVO = BeanUtil.copyProperties(recordVO, WgzAttendanceRecordVO.class);
				earlyLeaveRecordVO.setTime(clockOutTime.toLocalTime());
				earlyLeaveRecordVO.setMinutes(DataUtil.getMinutes(clockOutTime,endWorkTime));
				earlyLeaveRecords.add(earlyLeaveRecordVO);
			}

			if (wgzAttendance.getMissedIn() == 1) {
				WgzAttendanceRecordVO missRecordVO = BeanUtil.copyProperties(recordVO, WgzAttendanceRecordVO.class);
				missRecordVO.setTime(beginWorkTime);
				missRecords.add(missRecordVO);
			}

			if (wgzAttendance.getMissedOut() == 1) {
				WgzAttendanceRecordVO missRecordVO = BeanUtil.copyProperties(recordVO, WgzAttendanceRecordVO.class);
				missRecordVO.setTime(endWorkTime);
				missRecords.add(missRecordVO);
			}
		}
		bgtAttendanceDetailVO.setDayNum(records.stream().mapToDouble(WgzAttendanceRecordVO::getDay).sum());

		bgtAttendanceDetailVO.setLateNum(lateRecords.size());
		bgtAttendanceDetailVO.setLateMinute(lateRecords.stream().mapToInt(WgzAttendanceRecordVO::getMinutes).sum());
		bgtAttendanceDetailVO.setLateRecords(lateRecords);

		bgtAttendanceDetailVO.setEarlyLeaveNum(earlyLeaveRecords.size());
		bgtAttendanceDetailVO.setEarlyLeaveMinute(earlyLeaveRecords.stream().mapToInt(WgzAttendanceRecordVO::getMinutes).sum());
		bgtAttendanceDetailVO.setEarlyLeaveRecords(earlyLeaveRecords);

		bgtAttendanceDetailVO.setMissNum(earlyLeaveRecords.size());
		bgtAttendanceDetailVO.setMissRecords(earlyLeaveRecords);
		return bgtAttendanceDetailVO;



	}
}
