package shop.alien.job.store;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import shop.alien.entity.storePlatform.StoreOperationalActivity;
import shop.alien.entity.storePlatform.StoreOperationalActivitySignup;
import shop.alien.mapper.storePlantform.StoreOperationalActivityMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivitySignupMapper;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 营销活动状态定时任务
 * 根据活动的开始时间和结束时间自动更新活动状态
 *
 * @author system
 * @date 2025/01/XX
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StoreOperationalActivityJob {

    private final StoreOperationalActivityMapper activityMapper;
    private final StoreOperationalActivitySignupMapper signupMapper;

    /**
     * 营销活动状态更新任务
     * 定时更新活动状态：未开始 -> 进行中 -> 已结束
     */
    @XxlJob("operationalActivityStatusUpdateTask")
    public void operationalActivityStatusUpdateTask() {
        log.info("【定时任务】开始执行营销活动状态更新任务...");
        
        // 获取当前时间（零点）
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        now = calendar.getTime();

        try {
            // 查询需要更新状态的活动：2-未开始, 5-进行中, 8-审核成功
            List<Integer> statusList = new ArrayList<>();
            statusList.add(2); // 未开始
            statusList.add(5); // 进行中
            statusList.add(6);
            statusList.add(8); // 审核成功

            LambdaQueryWrapper<StoreOperationalActivity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(StoreOperationalActivity::getStatus, statusList)
                    .isNotNull(StoreOperationalActivity::getStartTime)
                    .isNotNull(StoreOperationalActivity::getEndTime);
            
            List<StoreOperationalActivity> activities = activityMapper.selectList(queryWrapper);
            log.info("【定时任务】查询到需要更新状态的活动数量: {}", activities.size());

            if (activities.isEmpty()) {
                log.info("【定时任务】没有需要更新状态的活动");
                return;
            }

            // 需要设置为"已结束"的活动ID列表
            List<Integer> endActivityIds = new ArrayList<>();
            // 需要设置为"进行中"的活动ID列表
            List<Integer> ongoingActivityIds = new ArrayList<>();
            // 需要设置为"未开始"的活动ID列表
            List<Integer> notStartActivityIds = new ArrayList<>();

            // 遍历活动，判断状态
            for (StoreOperationalActivity activity : activities) {
                Date startTime = activity.getStartTime();
                Date endTime = activity.getEndTime();
                Integer currentStatus = activity.getStatus();

                if (startTime == null || endTime == null) {
                    log.warn("【定时任务】活动ID: {} 的开始时间或结束时间为空，跳过处理", activity.getId());
                    continue;
                }

                // 判断当前时间与活动时间的关系
                if (now.compareTo(endTime) > 0) {
                    // 当前时间 > 结束时间：应该设置为"已结束"(7)
                    // 只处理状态为"未开始"(2)或"进行中"(5)的活动
//                    if (currentStatus == 2 || currentStatus == 5) {
                        endActivityIds.add(activity.getId());
                        log.debug("【定时任务】活动ID: {} 已过期，需要设置为已结束", activity.getId());
//                    }
                } else if (now.compareTo(startTime) >= 0 && now.compareTo(endTime) <= 0) {
                    // 当前时间在活动时间范围内：应该设置为"进行中"(5)
                    // 只处理状态为"未开始"(2)或"审核成功"(8)的活动
                    if (currentStatus == 2 || currentStatus == 8) {
                        ongoingActivityIds.add(activity.getId());
                        log.debug("【定时任务】活动ID: {} 正在进行中，需要设置为进行中", activity.getId());
                    }
                } else if (now.compareTo(startTime) < 0) {
                    // 当前时间 < 开始时间：应该设置为"未开始"(2)
                    // 只处理状态为"审核成功"(8)的活动
                    if (currentStatus == 8) {
                        notStartActivityIds.add(activity.getId());
                        log.debug("【定时任务】活动ID: {} 未开始，需要设置为未开始", activity.getId());
                    }
                }
            }

            // 批量更新状态为"已结束"
            if (!endActivityIds.isEmpty()) {
                LambdaUpdateWrapper<StoreOperationalActivity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(StoreOperationalActivity::getId, endActivityIds)
                        .set(StoreOperationalActivity::getStatus, 7); // 7-已结束
                int updateCount = activityMapper.update(null, updateWrapper);
                log.info("【定时任务】已结束活动更新完成，活动ID列表: {}，更新数量: {}", endActivityIds, updateCount);
            }

            // 批量更新状态为"进行中"
            if (!ongoingActivityIds.isEmpty()) {
                LambdaUpdateWrapper<StoreOperationalActivity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(StoreOperationalActivity::getId, ongoingActivityIds)
                        .set(StoreOperationalActivity::getStatus, 5); // 5-进行中
                int updateCount = activityMapper.update(null, updateWrapper);
                log.info("【定时任务】进行中活动更新完成，活动ID列表: {}，更新数量: {}", ongoingActivityIds, updateCount);
            }

            // 批量更新状态为"未开始"
            if (!notStartActivityIds.isEmpty()) {
                LambdaUpdateWrapper<StoreOperationalActivity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(StoreOperationalActivity::getId, notStartActivityIds)
                        .set(StoreOperationalActivity::getStatus, 2); // 2-未开始
                int updateCount = activityMapper.update(null, updateWrapper);
                log.info("【定时任务】未开始活动更新完成，活动ID列表: {}，更新数量: {}", notStartActivityIds, updateCount);
            }

            // 处理报名时间已过但未审核通过的报名记录
            // 使用当前实际时间（包含时分秒）进行比较
            processExpiredSignups(new Date());

            log.info("【定时任务】营销活动状态更新任务执行完成");
        } catch (Exception e) {
            log.error("【定时任务】营销活动状态更新任务执行异常", e);
        }
    }

    /**
     * 处理报名时间已过但未审核通过的报名记录
     * 如果报名人员没有在报名时间内审核通过，一律改为审核拒绝
     *
     * @param now 当前时间
     */
    private void processExpiredSignups(Date now) {
        log.info("【定时任务】开始处理报名时间已过的待审核报名记录...");
        
        try {
            // 查询所有有报名结束时间的活动
            LambdaQueryWrapper<StoreOperationalActivity> activityWrapper = new LambdaQueryWrapper<>();
            activityWrapper.isNotNull(StoreOperationalActivity::getSignupEndTime)
                    .eq(StoreOperationalActivity::getDeleteFlag, 0);
            
            List<StoreOperationalActivity> activities = activityMapper.selectList(activityWrapper);
            log.info("【定时任务】查询到有报名结束时间的活动数量: {}", activities.size());

            int totalRejectedCount = 0;

            for (StoreOperationalActivity activity : activities) {
                Date signupEndTime = activity.getSignupEndTime();
                if (signupEndTime == null) {
                    continue;
                }

                // 如果当前时间 > 报名结束时间，说明报名时间已过
                if (now.compareTo(signupEndTime) > 0) {
                    // 查询该活动下所有待审核（status=0）的报名记录
                    LambdaQueryWrapper<StoreOperationalActivitySignup> signupWrapper = new LambdaQueryWrapper<>();
                    signupWrapper.eq(StoreOperationalActivitySignup::getActivityId, activity.getId())
                            .eq(StoreOperationalActivitySignup::getStatus, 0) // 0-待审核
                            .eq(StoreOperationalActivitySignup::getDeleteFlag, 0);
                    
                    List<StoreOperationalActivitySignup> pendingSignups = signupMapper.selectList(signupWrapper);
                    
                    if (!pendingSignups.isEmpty()) {
                        // 批量更新为拒绝状态
                        List<Integer> signupIds = new ArrayList<>();
                        for (StoreOperationalActivitySignup signup : pendingSignups) {
                            signupIds.add(signup.getId());
                        }
                        
                        LambdaUpdateWrapper<StoreOperationalActivitySignup> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.in(StoreOperationalActivitySignup::getId, signupIds)
                                .set(StoreOperationalActivitySignup::getStatus, 1) // 1-拒绝
                                .set(StoreOperationalActivitySignup::getRejectReason, "报名时间已过，未在规定时间内审核通过")
                                .set(StoreOperationalActivitySignup::getAuditTime, now);
                        
                        int updateCount = signupMapper.update(null, updateWrapper);
                        totalRejectedCount += updateCount;
                        log.info("【定时任务】活动ID: {} 报名时间已过，将 {} 条待审核报名记录改为拒绝", 
                                activity.getId(), updateCount);
                    }
                }
            }

            if (totalRejectedCount > 0) {
                log.info("【定时任务】报名时间已过的待审核报名记录处理完成，共拒绝 {} 条", totalRejectedCount);
            } else {
                log.info("【定时任务】没有需要处理的报名时间已过的待审核报名记录");
            }
        } catch (Exception e) {
            log.error("【定时任务】处理报名时间已过的待审核报名记录异常", e);
        }
    }
}

