package com.jpsoft.shinestar.mq.listener;

import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.business.entity.YearRequestForLeaveInfo;
import com.jpsoft.shinestar.modules.business.service.YearRequestForLeaveInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
@RabbitListener(queues = "yearRequestForLeaveQueue", concurrency = "10")
public class YearRequestForLeaveListener {

    @Autowired
    private YearRequestForLeaveInfoService yearRequestForLeaveInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonInfoService personInfoService;

    @RabbitHandler
    public void process(String id) {
        log.warn("收到年假编号:" + id);

        try {
            YearRequestForLeaveInfo yearRequestForLeaveInfo = yearRequestForLeaveInfoService.get(id);

            if (yearRequestForLeaveInfo != null && yearRequestForLeaveInfo.getStatus() == 1) {
                PersonPopedom personPopedom = personPopedomService.get(yearRequestForLeaveInfo.getPersonPopedomId());
                PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());

                Date now = new Date();

                log.warn("判断是否修改状态:" + id);

                //当前时间是年假期间
                if (yearRequestForLeaveInfo.getStartTime().compareTo(now) <= 0 && yearRequestForLeaveInfo.getEndTime().compareTo(now) > 0) {
                    personInfo.setWorkStatus("7");
                    personInfo.setUpdateTime(new Date());
                    personInfoService.update(personInfo);
                }

                //当前时间已结束年假
                if (yearRequestForLeaveInfo.getEndTime().compareTo(now) <= 0) {
                    personInfo.setWorkStatus("1");
                    personInfo.setUpdateTime(new Date());
                    personInfoService.update(personInfo);

                    log.warn("判断是否修改为工作状态:" + id);
                }
            }

            log.warn("员工延时更新工作状态完毕");
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}
