package com.jpsoft.shinestar.scheduled;

import com.jpsoft.shinestar.modules.business.entity.WorkScheduleAttendance;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
@Transactional
public class UpdateWorkMinuteTask {
    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

//    @Scheduled(cron = "0 0/5 * * * ?")
    public void run() {
        List<WorkScheduleAttendance> list = workScheduleAttendanceService.findEmptyWorkMinuteList(100);

        for (WorkScheduleAttendance wsa : list) {
            int workMinutes = 0;

            try {
                List<WorkScheduleAttendance> onWorkList = workScheduleAttendanceService.findByPersonScheduleIdAndClassify(wsa.getPersonScheduleId(), wsa.getWorkShiftId(), "1");

                if(onWorkList.size()>0){
                    WorkScheduleAttendance workStartAttendance = onWorkList.get(0);

                    if (StringUtils.isNotEmpty(workStartAttendance.getResult())
                            && !"0".equals(workStartAttendance.getResult())
                            && workStartAttendance.getRecordTime() != null
                    ) {
                        workMinutes = Minutes.minutesBetween(
                                        new DateTime(workStartAttendance.getRecordTime()), new DateTime(wsa.getRecordTime()))
                                .getMinutes();
                    }
                }

                wsa.setWorkMinute(new BigDecimal(workMinutes));
                wsa.setUpdateTime(new Date());
                workScheduleAttendanceService.updateWorkMinute(wsa);
            }
            catch (Exception ex){
                log.error(ex.getMessage(),ex);
            }
        }
    }
}
