package cn.iocoder.yudao.module.bpm.service.workovertime;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAOvertimeItemDO;
import cn.iocoder.yudao.module.system.api.attendance.vo.AttendancePunchRecordVO;
import cn.iocoder.yudao.module.system.api.workovertime.vo.WorkOvertimeRuleApiVO;
import cn.iocoder.yudao.module.system.api.workovertime.vo.WorkOvertimeRuleItemApiVO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 加班 休息日
 *
 * @author 艾楷
 */
@Service("restDay")
@Validated
public class WorkOvertimeRestDayServiceImpl implements WorkOvertimeRestDayService, WorkOvertimeService {
    @Resource
    private WorkOvertimePublicService workOvertimePublicService;

    @Override
    public void getOvertimeHours(BpmOAOvertimeItemDO item, List<AttendancePunchRecordVO> recordList, WorkOvertimeRuleApiVO rule, WorkOvertimeRuleItemApiVO ruleItem) {
        // --- 计算方式 1按审批时长计算 2在审批的时段内，按打卡时长计算 3无需审批，按打卡时长计算  (这里是审批后的节点 只计算 1和2两种情况)
        // --------------------- 按审批时长计算 ---------------------
        if (ruleItem.getCalculationMode() == 1) {
            item.setActualTimeLength(item.getTimeLength());
            return;
        }
        // --------------------- 在审批的时段内，按打卡时长计算 3无需审批，按打卡时长计算 ---------------------
        BigDecimal overtimeHours = BigDecimal.ZERO;
        // -- 休息日 - 打了多久的卡就算多久 - 这里是计算加班时长 -
        AttendancePunchRecordVO first = CollUtil.getFirst(recordList);
        AttendancePunchRecordVO last = CollUtil.getLast(recordList);
        if (first == null || first.getPunchTime() == null || last == null || last.getPunchTime() == null) {
            item.setActualTimeLength(overtimeHours);
            return;
        }
        // -- 计算出加班多少分钟
        long minutes = LocalDateTimeUtil.between(first.getPunchTime(), last.getPunchTime(), ChronoUnit.MINUTES);
        // -- 计算取整 - 插入加班时间到item中
        workOvertimePublicService.calculateActualTimeLength(minutes, rule, item, ruleItem);
    }
}
