package com.yccrc.kede.quartz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.yccrc.common.constant.UserConstants;
import com.yccrc.common.core.domain.entity.SysUser;
import com.yccrc.kede.domain.Enterprise;
import com.yccrc.kede.service.IEnterpriseService;
import com.yccrc.kede.service.INotifyService;
import com.yccrc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务调度
 *
 * @author sinhoo
 */
@Component("enterpriseTask")
@Slf4j
public class EnterpriseTask {
    @Autowired
    IEnterpriseService enterpriseService;

    @Autowired
    ISysUserService userService;

    @Autowired
    INotifyService notifyService;

    public void execExpired() {
        log.info("更新过期企业.");
        List<Enterprise> list = enterpriseService.lambdaQuery()
                .eq(Enterprise::getEntState, 2)
                .lt(Enterprise::getEndDate, DateUtil.formatDate(new Date())).list();
        if (!CollectionUtil.isEmpty(list)) {
            List<Integer> ids = list.stream().map(Enterprise::getId).collect(Collectors.toList());
            log.info("已过期企业:{}", ids);
            enterpriseService.lambdaUpdate().set(Enterprise::getEntState, 3).in(Enterprise::getId, ids).update();
            userService.lambdaUpdate().set(SysUser::getStatus, UserConstants.USER_DISABLE).in(SysUser::getScopeId, ids).update();

            for (Enterprise e : list) {
                notifyService.expiredEnterpriseMsg(e, true);
            }
        }
    }

    public void execExpiring() {
        log.info("查询即将过期企业.");

        List<Enterprise> list = enterpriseService.lambdaQuery().eq(Enterprise::getEntState, 2).eq(Enterprise::getEndDate, DateUtil.formatDate(DateUtil.offsetDay(new Date(), -7))).list();
        if (!CollectionUtil.isEmpty(list)) {
            for (Enterprise e : list) {
                notifyService.expireingEnterpriseMsg(e);
            }
        }
    }
}
