package com.fs.live.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;

import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.live.domain.*;
import com.fs.live.mapper.*;
import com.fs.live.param.LiveLotteryProduct;
import com.fs.live.service.ILiveAutoTaskService;
import com.fs.live.service.ILiveCouponService;
import com.fs.live.service.ILiveGoodsService;
import com.fs.live.vo.LiveGoodsVo;
import com.fs.live.vo.LiveLotteryConfVo;
import com.fs.live.vo.LiveLotteryProductListVo;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 直播间自动化任务配置Service业务层处理
 *
 * @author fs
 * @date 2025-08-29
 */
@Service
public class LiveAutoTaskServiceImpl implements ILiveAutoTaskService {

    private static final Logger log = LoggerFactory.getLogger(LiveAutoTaskServiceImpl.class);

    @Autowired
    private LiveMapper liveMapper;
    @Autowired
    private ILiveGoodsService goodsService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LiveAutoTaskMapper baseMapper;

    @Autowired
    private LiveRedConfMapper liveRedConfMapper;
    @Autowired
    private LiveLotteryConfMapper liveLotteryConfMapper;
    @Autowired
    private LiveLotteryProductConfMapper lotteryProductConfMapper;
    @Autowired
    private LiveCouponMapper liveCouponMapper;
    @Autowired
    private LiveCouponIssueMapper liveCouponIssueMapper;

    /**
     * 查询直播间自动化任务配置
     *
     * @param id 直播间自动化任务配置主键
     * @return 直播间自动化任务配置
     */
    @Override
    public LiveAutoTask selectLiveAutoTaskById(Long id)
    {
        return baseMapper.selectLiveAutoTaskById(id);
    }

    /**
     * 查询直播间自动化任务配置列表
     *
     * @param liveAutoTask 直播间自动化任务配置
     * @return 直播间自动化任务配置
     */
    @Override
    public List<LiveAutoTask> selectLiveAutoTaskList(LiveAutoTask liveAutoTask)
    {
        return baseMapper.selectLiveAutoTaskList(liveAutoTask);
    }

    /**
     * 新增直播间自动化任务配置
     *
     * @param liveAutoTask 直播间自动化任务配置
     * @return 结果
     */
    @Override
    public R insertLiveAutoTask(LiveAutoTask liveAutoTask)
    {

        Live live = liveMapper.selectLiveByLiveId(liveAutoTask.getLiveId());
        if(live == null) return R.error("直播间不存在");
        //截取triggerValue 时分秒部分 ，然后根据查询出来的直播间开始时间计算出相对时间
        Date triggerValue = liveAutoTask.getTriggerValue();
        if (triggerValue == null) {
            return R.error("请设置触发时间");
        }
        Date now = new Date();
        // 获取直播间开始时间进行计算触发时间
        liveAutoTask.setTriggerValue(triggerValue);
        liveAutoTask.setAbsValue(getTriggerValue(triggerValue, live.getStartTime()));
        //如果触发时间小于当前时间 报错
        if (liveAutoTask.getAbsValue().before(now)) {return R.error("请勿设置触发时间小于当前时间");}

        // 根据触发时间 查看同一时间有没有相同的数据 1.直播间id 2.时间
        LiveAutoTask existTask = baseMapper.selectLiveAutoTaskByTriggerValue(liveAutoTask.getLiveId(), liveAutoTask.getTriggerValue());
        if(existTask != null) return R.error("该时间段有任务");


        liveAutoTask.setCreateTime(now);
        liveAutoTask.setUpdateTime(now);
        liveAutoTask.setTriggerType(2L);
        liveAutoTask.setFinishStatus(0L);
        if(liveAutoTask.getStatus() == null) liveAutoTask.setStatus(1L);
        if (liveAutoTask.getTaskType() == 1L) {
            // 商品
            LiveGoodsVo liveGoodsVo = goodsService.selectLiveGoodsVoByGoodsId(Long.valueOf(liveAutoTask.getContent()));
            if(liveGoodsVo == null) return R.error("商品不存在");
            liveAutoTask.setContent(JSON.toJSONString(liveGoodsVo));
            baseMapper.insertLiveAutoTask(liveAutoTask);
        }else if (liveAutoTask.getTaskType() == 2L) {
            // 红包
            LiveRedConf liveRedConf = liveRedConfMapper.selectLiveRedConfByRedId(Long.valueOf(liveAutoTask.getContent()));
            if(liveRedConf == null) return R.error("红包配置不存在");
            if(liveRedConf.getRedStatus() != 0L) return R.error("红包状态应该为：未发放");
            liveAutoTask.setContent(JSON.toJSONString(liveRedConf));
            baseMapper.insertLiveAutoTask(liveAutoTask);
        }else if (liveAutoTask.getTaskType() == 4L) {
            // 开启抽奖
            LiveLotteryConf liveLotteryConf = liveLotteryConfMapper.selectLiveLotteryConfByLotteryId(Long.valueOf(liveAutoTask.getContent()));
            if(liveLotteryConf == null) return R.error("抽奖配置不存在");
            if(!"0".equals(liveLotteryConf.getLotteryStatus())) return R.error("抽奖状态应该为：未开始");
            List<Long> lotteryIds = new ArrayList<>();
            lotteryIds.add(liveLotteryConf.getLotteryId());
            List<LiveLotteryProductListVo> prizes = lotteryProductConfMapper.selectLiveLotteryProductConfByLotteryIds(lotteryIds);
            if (prizes == null || prizes.isEmpty()) {
                return R.error("抽奖配置请先添加奖品");
            }
            liveAutoTask.setContent(JSON.toJSONString(liveLotteryConf));
            baseMapper.insertLiveAutoTask(liveAutoTask);
        } else if(liveAutoTask.getTaskType() == 3L){
            baseMapper.insertLiveAutoTask(liveAutoTask);
        } else if (liveAutoTask.getTaskType() == 5L) {
            LiveCouponIssue liveCouponIssue = liveCouponIssueMapper.selectLiveCouponIssueById(Long.valueOf(liveAutoTask.getContent()));
            if(liveCouponIssue == null)return R.error("优惠券未发布");
            // 自动优惠券
            LiveCoupon liveCoupon = liveCouponMapper.selectLiveCouponById(liveCouponIssue.getCouponId());
            if(liveCoupon == null) return R.error("优惠券不存在");
            LiveCouponIssueRelation liveCouponIssueRelation = liveCouponMapper.selectCouponRelation(liveAutoTask.getLiveId(),liveCouponIssue.getId());
            if(liveCouponIssueRelation == null) return R.error("优惠券尚未添加在直播间");
            if(ObjectUtil.isEmpty(liveCouponIssueRelation.getGoodsId())) return R.error("未绑定商品，无法制定自动化任务！");
            liveCoupon.setGoodsId(liveCouponIssueRelation.getGoodsId());
            liveCoupon.setIssueId(liveCouponIssueRelation.getCouponIssueId());
            liveAutoTask.setContent(JSON.toJSONString(liveCoupon));
            baseMapper.insertLiveAutoTask(liveAutoTask);
        } else if (liveAutoTask.getTaskType() == 6L) {
            // 上架/下架商品
            try {
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(liveAutoTask.getContent());
                Long goodsId = jsonObject.getLong("goodsId");
                Integer status = jsonObject.getInteger("status");
                if (goodsId == null) return R.error("商品ID不能为空");
                if (status == null) return R.error("状态不能为空");

                // 查询商品信息
                LiveGoodsVo liveGoodsVo = goodsService.selectLiveGoodsVoByGoodsId(goodsId);
                if(liveGoodsVo == null) return R.error("商品不存在");

                // 保存商品信息和上下架状态
                com.alibaba.fastjson.JSONObject content = new com.alibaba.fastjson.JSONObject();
                content.put("goodsId", liveGoodsVo.getGoodsId());
                content.put("productId", liveGoodsVo.getProductId());
                content.put("productName", liveGoodsVo.getProductName());
                content.put("status", status);
                liveAutoTask.setContent(content.toJSONString());
                baseMapper.insertLiveAutoTask(liveAutoTask);
            } catch (Exception e) {
                return R.error("内容格式错误，应为{\"goodsId\":123,\"status\":1}");
            }
        } else {
            return R.error("任务类型错误");
        }


        if (live.getStatus() == 2 && liveAutoTask.getStatus() == 1L) {
            liveAutoTask.setUpdateTime(null);
            liveAutoTask.setCreateTime(null);
            redisCache.redisTemplate.opsForZSet().add("live:auto_task:" + live.getLiveId(), JSON.toJSONString(liveAutoTask),liveAutoTask.getAbsValue().getTime());
            redisCache.redisTemplate.expire("live:auto_task:" + live.getLiveId(), 30, java.util.concurrent.TimeUnit.MINUTES);
        }


        return R.ok();
    }

    /**
     * 复制新增直播间自动化任务配置
     *
     * @param liveAutoTask 直播间自动化任务配置
     * @return 结果
     */
    @Override
    public R copyInsertLiveAutoTask(LiveAutoTask liveAutoTask , Live live)
    {

        Date triggerValue = liveAutoTask.getTriggerValue();
        if (triggerValue == null) {
            return R.error("请设置触发时间");
        }
        Date now = new Date();
        // 获取直播间开始时间进行计算触发时间
        liveAutoTask.setTriggerValue(triggerValue);
        liveAutoTask.setAbsValue(getTriggerValue(triggerValue, live.getStartTime()));

        liveAutoTask.setCreateTime(now);
        liveAutoTask.setUpdateTime(now);
        liveAutoTask.setTriggerType(2L);
        liveAutoTask.setFinishStatus(0L);
        if(liveAutoTask.getStatus() == null) liveAutoTask.setStatus(1L);
        baseMapper.insertLiveAutoTask(liveAutoTask);

        if (live.getStatus() == 2 && liveAutoTask.getStatus() == 1L) {
            liveAutoTask.setUpdateTime(null);
            liveAutoTask.setCreateTime(null);
            redisCache.redisTemplate.opsForZSet().add("live:auto_task:" + live.getLiveId(), JSON.toJSONString(liveAutoTask),liveAutoTask.getAbsValue().getTime());
            redisCache.redisTemplate.expire("live:auto_task:" + live.getLiveId(), 30, java.util.concurrent.TimeUnit.MINUTES);
        }
        return R.ok();
    }

    private Date getTriggerValue( Date triggerValue, LocalDateTime liveStartTime) {
        LocalDateTime triggerDateTime = LocalDateTime.ofInstant(
                triggerValue.toInstant(),
                ZoneId.systemDefault()
        );
        LocalTime triggerTime = triggerDateTime.toLocalTime();
        LocalDateTime combinedTime = liveStartTime
                .plusHours(triggerTime.getHour())
                .plusMinutes(triggerTime.getMinute())
                .plusSeconds(triggerTime.getSecond());
        return Date.from(combinedTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 修改直播间自动化任务配置
     *
     * @param liveAutoTask 直播间自动化任务配置
     * @return 结果
     */
    @Override
    public R updateLiveAutoTask(LiveAutoTask liveAutoTask)
    {
        LiveAutoTask existTask = baseMapper.selectLiveAutoTaskById(liveAutoTask.getId());
        redisCache.redisTemplate.opsForZSet().removeRangeByScore("live:auto_task:" + existTask.getLiveId(), existTask.getAbsValue().getTime(), existTask.getAbsValue().getTime());
        if (liveAutoTask.getTaskType() == 1L) {
            // 商品
            LiveGoodsVo liveGoodsVo = goodsService.selectLiveGoodsVoByGoodsId(Long.valueOf(liveAutoTask.getContent()));
            if(liveGoodsVo == null) return R.error("商品不存在");
            liveAutoTask.setContent(JSON.toJSONString(liveGoodsVo));
            baseMapper.updateLiveAutoTask(liveAutoTask);
        }else if (liveAutoTask.getTaskType() == 2L) {
            // 红包
            LiveRedConf liveRedConf = liveRedConfMapper.selectLiveRedConfByRedId(Long.valueOf(liveAutoTask.getContent()));
            if(liveRedConf == null) return R.error("红包不存在！");
            if(liveRedConf.getRedStatus() != 0L) return R.error("红包已结束！");
            liveAutoTask.setContent(JSON.toJSONString(liveRedConf));
            baseMapper.updateLiveAutoTask(liveAutoTask);
        }else if (liveAutoTask.getTaskType() == 4L) {
            // 开启抽奖
            LiveLotteryConf liveLotteryConf = liveLotteryConfMapper.selectLiveLotteryConfByLotteryId(Long.valueOf(liveAutoTask.getContent()));
            if(liveLotteryConf == null) return R.error("抽奖不存在！");
            if(!"0".equals(liveLotteryConf.getLotteryStatus())) return R.error("抽奖未开始！");
            List<LiveLotteryProduct> prizes = lotteryProductConfMapper.selectLiveLotteryProductConfByLotteryId(liveLotteryConf.getLotteryId());
            if (prizes == null || prizes.isEmpty()) {
                return R.error("请先添加奖品");
            }
            liveAutoTask.setContent(JSON.toJSONString(liveLotteryConf));
            baseMapper.updateLiveAutoTask(liveAutoTask);
        } else if(liveAutoTask.getTaskType() == 3L){
            baseMapper.updateLiveAutoTask(liveAutoTask);
        } else if( liveAutoTask.getTaskType() == 5L){
            LiveCouponIssue liveCouponIssue = liveCouponIssueMapper.selectLiveCouponIssueById(Long.valueOf(liveAutoTask.getContent()));
            if(liveCouponIssue == null)return R.error("优惠券未发布");
            // 自动优惠券
            LiveCoupon liveCoupon = liveCouponMapper.selectLiveCouponById(liveCouponIssue.getCouponId());
            if(liveCoupon == null) return R.error("优惠券不存在");
            LiveCouponIssueRelation liveCouponIssueRelation = liveCouponMapper.selectCouponRelation(liveAutoTask.getLiveId(),liveCouponIssue.getId());
            if(liveCouponIssueRelation == null) return R.error("优惠券尚未添加在直播间");
            if(ObjectUtil.isEmpty(liveCouponIssueRelation.getGoodsId())) return R.error("未绑定商品，无法制定自动化任务！");
            liveCoupon.setGoodsId(liveCouponIssueRelation.getGoodsId());
            liveCoupon.setIssueId(liveCouponIssueRelation.getCouponIssueId());
            liveAutoTask.setContent(JSON.toJSONString(liveCoupon));
            baseMapper.updateLiveAutoTask(liveAutoTask);
        } else if (liveAutoTask.getTaskType() == 6L) {
            // 上架/下架商品
            try {
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(liveAutoTask.getContent());
                Long goodsId = jsonObject.getLong("goodsId");
                Integer status = jsonObject.getInteger("status");
                if (goodsId == null || status == null) return R.error("商品ID或状态为空");

                // 查询商品信息
                LiveGoodsVo liveGoodsVo = goodsService.selectLiveGoodsVoByGoodsId(goodsId);
                if(liveGoodsVo == null) return R.error("商品不存在");

                // 保存商品信息和上下架状态
                com.alibaba.fastjson.JSONObject content = new com.alibaba.fastjson.JSONObject();
                content.put("goodsId", liveGoodsVo.getGoodsId());
                content.put("productId", liveGoodsVo.getProductId());
                content.put("productName", liveGoodsVo.getProductName());
                content.put("status", status);
                liveAutoTask.setContent(content.toJSONString());
                baseMapper.updateLiveAutoTask(liveAutoTask);
            } catch (Exception e) {
                log.error("上架/下架商品自动化任务，更新异常！" + e.getMessage());
                return R.error("上架/下架商品自动化任务，更新异常！");
            }
        } else {
            return R.error("任务类型错误");
        }
        return R.ok("更新成功");
    }

    /**
     * 批量删除直播间自动化任务配置
     *
     * @param ids 需要删除的直播间自动化任务配置主键
     * @return 结果
     */
    @Override
    public int deleteLiveAutoTaskByIds(Long[] ids)
    {
        // 先从缓存中删除所有任务
        for (Long id : ids) {
            LiveAutoTask task = baseMapper.selectLiveAutoTaskById(id);
            if (task != null) {
                removeTaskFromCache(task);
            }
        }
        return baseMapper.deleteLiveAutoTaskByIds(ids);
    }

    /**
     * 删除直播间自动化任务配置信息
     *
     * @param id 直播间自动化任务配置主键
     * @return 结果
     */
    @Override
    public int deleteLiveAutoTaskById(Long id)
    {
        return baseMapper.deleteLiveAutoTaskById(id);
    }

    @Override
    public List<LiveAutoTask> selectLiveAutoTaskByLiveId(Long existLiveId) {
        return  baseMapper.selectLiveAutoTaskByLiveId(existLiveId);
    }

    @Override
    public List<LiveAutoTask> selectNoActivedByLiveId(Long existLiveId, Date now) {
        return baseMapper.selectNoActivedByLiveId(existLiveId, now);
    }

    @Override
    public List<LiveAutoTask> selectLiveAutoTaskByLiveIds(List<Long> liveIdLists) {
        return baseMapper.selectLiveAutoTaskByLiveIds(liveIdLists, new Date());
    }

    @Override
    public void recalcLiveAutoTask(Live live) {

        if(live == null) return;
        List<LiveAutoTask> liveAutoTasks = baseMapper.recalcLiveAutoTaskQuery(live.getLiveId());
        Date now = new Date();
        List<LiveAutoTask> updateList = new ArrayList<>();
        for (LiveAutoTask liveAutoTask : liveAutoTasks) {
            liveAutoTask.setAbsValue(getTriggerValue(liveAutoTask.getTriggerValue(), live.getStartTime()));
            liveAutoTask.setUpdateTime(now);
            liveAutoTask.setFinishStatus(0L);
            updateList.add(liveAutoTask);
            if (updateList.size() >= 200) {
                baseMapper.batchUpdateLiveAutoTask(updateList);
                updateList.clear();
            }
        }
        if (!updateList.isEmpty()) {
            baseMapper.batchUpdateLiveAutoTask(updateList);
        }
    }

    @Override
    public void finishLiveAutoTask(LiveAutoTask task) {
        baseMapper.finishLiveAutoTask(task);
    }

    @Override
    public List<LiveAutoTask> selectLiveAutoTaskBarrageList(LiveAutoTask liveAutoTask) {
        return baseMapper.selectLiveAutoTaskBarrageList(liveAutoTask);
    }

    @Override
    public void directInsertLiveAutoTask(LiveAutoTask liveAutoTask) {
        baseMapper.insertLiveAutoTask(liveAutoTask);
    }

    @Override
    public void batchInsertLiveAutoTask(List<LiveAutoTask> addList) {
        baseMapper.batchInsertLiveAutoTask(addList);
    }

    /**
     * 删除与优惠券相关的自动化任务（taskType=5）
     * @param couponId 优惠券ID
     * @param liveId 直播间ID（可为null，null表示所有直播间）
     */
    @Override
    public void deleteAutoTasksByCouponId(Long couponId, Long liveId) {
        try {
            List<LiveAutoTask> allTasks;
            if (liveId != null) {
                allTasks = baseMapper.selectLiveAutoTaskByLiveId(liveId);
            } else {
                // 查询所有直播间的任务
                LiveAutoTask queryTask = new LiveAutoTask();
                queryTask.setTaskType(5L); // 优惠券任务
                allTasks = baseMapper.selectLiveAutoTaskList(queryTask);
            }

            List<Long> taskIdsToDelete = new ArrayList<>();
            for (LiveAutoTask task : allTasks) {
                if (task.getTaskType() != null && task.getTaskType() == 5L) {
                    try {
                        LiveCoupon liveCoupon = JSON.parseObject(task.getContent(), LiveCoupon.class);
                        if (liveCoupon != null && couponId.equals(liveCoupon.getCouponId())) {
                            taskIdsToDelete.add(task.getId());
                            // 从缓存中删除
                            removeTaskFromCache(task);
                        }
                    } catch (Exception e) {
                        log.warn("解析自动化任务content失败，taskId: {}, error: {}", task.getId(), e.getMessage());
                    }
                }
            }

            if (!taskIdsToDelete.isEmpty()) {
                Long[] ids = taskIdsToDelete.toArray(new Long[0]);
                baseMapper.deleteLiveAutoTaskByIds(ids);
                log.info("删除与优惠券ID {} 相关的自动化任务 {} 个", couponId, taskIdsToDelete.size());
            }
        } catch (Exception e) {
            log.error("删除优惠券相关自动化任务失败，couponId: {}", couponId, e);
        }
    }

    /**
     * 删除与红包相关的自动化任务（taskType=2）
     * @param redId 红包ID
     * @param liveId 直播间ID
     */
    @Override
    public void deleteAutoTasksByRedId(Long redId, Long liveId) {
        try {
            List<LiveAutoTask> allTasks = baseMapper.selectLiveAutoTaskByLiveId(liveId);
            List<Long> taskIdsToDelete = new ArrayList<>();

            for (LiveAutoTask task : allTasks) {
                if (task.getTaskType() != null && task.getTaskType() == 2L) {
                    try {
                        LiveRedConf liveRedConf = JSON.parseObject(task.getContent(), LiveRedConf.class);
                        if (liveRedConf != null && redId.equals(liveRedConf.getRedId())) {
                            taskIdsToDelete.add(task.getId());
                            // 从缓存中删除
                            removeTaskFromCache(task);
                        }
                    } catch (Exception e) {
                        log.warn("解析自动化任务content失败，taskId: {}, error: {}", task.getId(), e.getMessage());
                    }
                }
            }

            if (!taskIdsToDelete.isEmpty()) {
                Long[] ids = taskIdsToDelete.toArray(new Long[0]);
                baseMapper.deleteLiveAutoTaskByIds(ids);
                log.info("删除与红包ID {} 相关的自动化任务 {} 个", redId, taskIdsToDelete.size());
            }
        } catch (Exception e) {
            log.error("删除红包相关自动化任务失败，redId: {}, liveId: {}", redId, liveId, e);
        }
    }

    /**
     * 删除与抽奖相关的自动化任务（taskType=4）
     * @param lotteryId 抽奖ID
     * @param liveId 直播间ID
     */
    @Override
    public void deleteAutoTasksByLotteryId(Long lotteryId, Long liveId) {
        try {
            List<LiveAutoTask> allTasks = baseMapper.selectLiveAutoTaskByLiveId(liveId);
            List<Long> taskIdsToDelete = new ArrayList<>();

            for (LiveAutoTask task : allTasks) {
                if (task.getTaskType() != null && task.getTaskType() == 4L) {
                    try {
                        LiveLotteryConf liveLotteryConf = JSON.parseObject(task.getContent(), LiveLotteryConf.class);
                        if (liveLotteryConf != null && lotteryId.equals(liveLotteryConf.getLotteryId())) {
                            taskIdsToDelete.add(task.getId());
                            // 从缓存中删除
                            removeTaskFromCache(task);
                        }
                    } catch (Exception e) {
                        log.warn("解析自动化任务content失败，taskId: {}, error: {}", task.getId(), e.getMessage());
                    }
                }
            }

            if (!taskIdsToDelete.isEmpty()) {
                Long[] ids = taskIdsToDelete.toArray(new Long[0]);
                baseMapper.deleteLiveAutoTaskByIds(ids);
                log.info("删除与抽奖ID {} 相关的自动化任务 {} 个", lotteryId, taskIdsToDelete.size());
            }
        } catch (Exception e) {
            log.error("删除抽奖相关自动化任务失败，lotteryId: {}, liveId: {}", lotteryId, liveId, e);
        }
    }

    /**
     * 删除与商品相关的自动化任务（taskType=1或6）
     * @param goodsId 商品ID
     * @param liveId 直播间ID
     */
    @Override
    public void deleteAutoTasksByGoodsId(Long goodsId, Long liveId) {
        try {
            List<LiveAutoTask> allTasks = baseMapper.selectLiveAutoTaskByLiveId(liveId);
            List<Long> taskIdsToDelete = new ArrayList<>();

            for (LiveAutoTask task : allTasks) {
                if (task.getTaskType() != null && (task.getTaskType() == 1L || task.getTaskType() == 6L)) {
                    try {
                        if (task.getTaskType() == 1L) {
                            // 商品推荐任务
                            LiveGoodsVo liveGoodsVo = JSON.parseObject(task.getContent(), LiveGoodsVo.class);
                            if (liveGoodsVo != null && goodsId.equals(liveGoodsVo.getGoodsId())) {
                                taskIdsToDelete.add(task.getId());
                                removeTaskFromCache(task);
                            }
                        } else if (task.getTaskType() == 6L) {
                            // 商品上下架任务
                            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(task.getContent());
                            Long taskGoodsId = jsonObject.getLong("goodsId");
                            if (taskGoodsId != null && goodsId.equals(taskGoodsId)) {
                                taskIdsToDelete.add(task.getId());
                                removeTaskFromCache(task);
                            }
                        }
                    } catch (Exception e) {
                        log.warn("解析自动化任务content失败，taskId: {}, error: {}", task.getId(), e.getMessage());
                    }
                }
            }

            if (!taskIdsToDelete.isEmpty()) {
                Long[] ids = taskIdsToDelete.toArray(new Long[0]);
                baseMapper.deleteLiveAutoTaskByIds(ids);
                log.info("删除与商品ID {} 相关的自动化任务 {} 个", goodsId, taskIdsToDelete.size());
            }
        } catch (Exception e) {
            log.error("删除商品相关自动化任务失败，goodsId: {}, liveId: {}", goodsId, liveId, e);
        }
    }

    /**
     * 从缓存中删除自动化任务
     * @param task 自动化任务
     */
    private void removeTaskFromCache(LiveAutoTask task) {
        try {
            if (task.getLiveId() != null && task.getId() != null) {
                String cacheKey = "live:auto_task:" + task.getLiveId();
                // 获取ZSet中的所有任务
                Set<String> allTasks = redisCache.redisTemplate.opsForZSet().range(cacheKey, 0, -1);
                if (allTasks != null && !allTasks.isEmpty()) {
                    // 遍历找到匹配的任务ID
                    for (String taskJson : allTasks) {
                        try {
                            LiveAutoTask cachedTask = JSON.parseObject(taskJson, LiveAutoTask.class);
                            if (cachedTask != null && task.getId().equals(cachedTask.getId())) {
                                // 找到匹配的任务，从ZSet中删除
                                redisCache.redisTemplate.opsForZSet().remove(cacheKey, taskJson);
                                log.debug("从缓存中删除自动化任务，liveId: {}, taskId: {}", task.getLiveId(), task.getId());
                                break;
                            }
                        } catch (Exception e) {
                            log.warn("解析缓存中的任务失败，taskJson: {}, error: {}", taskJson, e.getMessage());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("从缓存删除自动化任务失败，taskId: {}, error: {}", task.getId(), e.getMessage());
        }
    }

    /**
     * 删除抽奖缓存
     * @param lotteryId 抽奖ID
     * @param liveId 直播间ID
     */
    public void deleteLotteryCache(Long lotteryId, Long liveId) {
        try {
            String cacheKey = "live:lottery_task:" + liveId;
            // 从ZSet中删除指定的抽奖ID
            redisCache.redisTemplate.opsForZSet().remove(cacheKey, String.valueOf(lotteryId));
            log.info("删除抽奖缓存，lotteryId: {}, liveId: {}", lotteryId, liveId);
        } catch (Exception e) {
            log.error("删除抽奖缓存失败，lotteryId: {}, liveId: {}", lotteryId, liveId, e);
        }
    }

    /**
     * 删除红包缓存
     * @param redId 红包ID
     * @param liveId 直播间ID
     */
    public void deleteRedCache(Long redId, Long liveId) {
        try {
            String cacheKey = "live:red_task:" + liveId;
            // 从ZSet中删除指定的红包ID
            redisCache.redisTemplate.opsForZSet().remove(cacheKey, String.valueOf(redId));
            // 同时删除剩余红包数的缓存
            redisCache.deleteObject("live:red:remainingLots:" + redId);
            log.info("删除红包缓存，redId: {}, liveId: {}", redId, liveId);
        } catch (Exception e) {
            log.error("删除红包缓存失败，redId: {}, liveId: {}", redId, liveId, e);
        }
    }
}
