package org.dromara.zjk.learning_world.job;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.dromara.zjk.enums.PublishStatusEnum;
import org.dromara.zjk.learning_world.domain.entity.ZjkLearningActivity;
import org.dromara.zjk.learning_world.enums.course.ActivityStatusEnum;
import org.dromara.zjk.learning_world.mapper.ZjkLearningActivityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class ActivityJobServiceImpl implements ActivityJobService {
    @Autowired
    private ZjkLearningActivityMapper zjkLearningActivityMapper;
    @Override
    public void startActivity() {
        log.error("活动开启 定时任务任务开始==================》");
        LambdaQueryWrapper<ZjkLearningActivity> lqw = Wrappers.lambdaQuery();
        lqw.le(ZjkLearningActivity::getActivityStartTime, new Date());
        lqw.eq(ZjkLearningActivity::getActivityStatus, ActivityStatusEnum.DIDN_T_START.getCode());
        lqw.eq(ZjkLearningActivity::getStatus, PublishStatusEnum.ON.getCode());

        List<ZjkLearningActivity> zjkLearningActivities = zjkLearningActivityMapper.selectList(lqw);
        if(CollectionUtil.isEmpty(zjkLearningActivities)){
            log.error("活动开启 定时任务任务结束==================》没有开启的定时任务");
            return;
        }
        log.error("活动开启 定时任务任务结束==================》"+zjkLearningActivities);
        for (ZjkLearningActivity learningActivity : zjkLearningActivities) {
            learningActivity.setActivityStatus(ActivityStatusEnum.ONGOING.getCode());
        }
        zjkLearningActivityMapper.updateBatchById(zjkLearningActivities);
        log.error("活动开启 定时任务任务结束==================》");
    }

    @Override
    public void endActivity() {
        log.error("活动结束 定时任务任务开始==================》");
        LambdaQueryWrapper<ZjkLearningActivity> lqw = Wrappers.lambdaQuery();
        lqw.le(ZjkLearningActivity::getActivityEndTime, new Date());
        lqw.eq(ZjkLearningActivity::getActivityStatus, ActivityStatusEnum.ONGOING.getCode());
        lqw.eq(ZjkLearningActivity::getStatus, PublishStatusEnum.ON.getCode());

        List<ZjkLearningActivity> zjkLearningActivities = zjkLearningActivityMapper.selectList(lqw);
        if(CollectionUtil.isEmpty(zjkLearningActivities)){
            log.error("活动结束 定时任务任务结束==================》没有开启的定时任务");
            return;
        }
        log.error("活动结束 定时任务任务结束==================》"+zjkLearningActivities);
        for (ZjkLearningActivity learningActivity : zjkLearningActivities) {
            learningActivity.setActivityStatus(ActivityStatusEnum.ENDED.getCode());
        }
        zjkLearningActivityMapper.updateBatchById(zjkLearningActivities);
        log.error("活动结束 定时任务任务结束==================》");
    }
}
