package com.fs.live.service.impl;


import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.DateUtils;
import com.fs.live.domain.LiveLotteryConf;
import com.fs.live.domain.LiveLotteryRegistration;
import com.fs.live.mapper.LiveLotteryConfMapper;
import com.fs.live.mapper.LiveLotteryProductConfMapper;
import com.fs.live.mapper.LiveLotteryRegistrationMapper;
import com.fs.live.param.LiveLotteryProduct;
import com.fs.live.param.LiveLotteryProductSaveParam;
import com.fs.live.param.LotteryPO;
import com.fs.live.service.ILiveLotteryConfService;
import com.fs.live.vo.LiveLotteryConfVo;
import com.fs.live.vo.LiveLotteryProductListVo;
import com.fs.live.vo.LiveLotteryProductVO;
import com.fs.live.vo.LiveUserLotteryRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 直播抽奖配置Service业务层处理
 *
 * @author fs
 * @date 2025-07-17
 */
@Service
public class LiveLotteryConfServiceImpl implements ILiveLotteryConfService {

    @Autowired
    private LiveLotteryConfMapper mapper;

    @Autowired
    private LiveLotteryProductConfMapper productMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LiveLotteryRegistrationMapper lotteryRegistrationMapper;

    @Autowired
    private LiveLotteryConfMapper baseMapper;
    /**
     * 查询直播抽奖配置
     *
     * @param lotteryId 直播抽奖配置主键
     * @return 直播抽奖配置
     */
    @Override
    public LiveLotteryConf selectLiveLotteryConfByLotteryId(Long lotteryId)
    {
        return baseMapper.selectLiveLotteryConfByLotteryId(lotteryId);
    }

    /**
     * 查询直播抽奖配置列表
     *
     * @param liveLotteryConf 直播抽奖配置
     * @return 直播抽奖配置
     */
    @Override
    public List<LiveLotteryConf> selectLiveLotteryConfList(LiveLotteryConf liveLotteryConf)
    {
        return baseMapper.selectLiveLotteryConfList(liveLotteryConf);
    }

    /**
     * 新增直播抽奖配置
     *
     * @param liveLotteryConf 直播抽奖配置
     * @return 结果
     */
    @Override
    public int insertLiveLotteryConf(LiveLotteryConf liveLotteryConf)
    {
        liveLotteryConf.setCreateTime(DateUtils.getNowDate());
        liveLotteryConf.setLotteryStatus("0");
        return baseMapper.insertLiveLotteryConf(liveLotteryConf);
    }

    /**
     * 修改直播抽奖配置
     *
     * @param liveLotteryConf 直播抽奖配置
     * @return 结果
     */
    @Override
    public R updateLiveLotteryConf(LiveLotteryConf liveLotteryConf)
    {
        String cacheKey = "live:lottery_task:" + liveLotteryConf.getLiveId();
        liveLotteryConf.setUpdateTime(DateUtils.getNowDate());
        if ("1".equals(liveLotteryConf.getLotteryStatus())) {
            List<LiveLotteryProduct> prizes = productMapper.selectLiveLotteryProductConfByLotteryId(liveLotteryConf.getLotteryId());
            if (prizes == null || prizes.isEmpty()) {
                return R.error("请先添加奖品");
            }
            LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(liveLotteryConf.getDuration());
            double score = localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
            redisCache.redisTemplate.opsForZSet().add(cacheKey, String.valueOf(liveLotteryConf.getLotteryId()), score);
            redisCache.redisTemplate.expire(cacheKey, 30, java.util.concurrent.TimeUnit.MINUTES);
        } else {
            redisCache.deleteObject(cacheKey);
        }
        return R.ok().put("data",baseMapper.updateLiveLotteryConf(liveLotteryConf));
    }

    /**
     * 批量删除直播抽奖配置
     *
     * @param lotteryIds 需要删除的直播抽奖配置主键
     * @return 结果
     */
    @Override
    public int deleteLiveLotteryConfByLotteryIds(Long[] lotteryIds)
    {
        return baseMapper.deleteLiveLotteryConfByLotteryIds(lotteryIds);
    }

    /**
     * 删除直播抽奖配置信息
     *
     * @param lotteryId 直播抽奖配置主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteLiveLotteryConfByLotteryId(Long lotteryId)
    {
        return baseMapper.deleteLiveLotteryConfByLotteryId(lotteryId);
    }

    @Override
    @Transactional
    public LiveLotteryConf getById(Long lotteryId) {
        return mapper.selectById(lotteryId);
    }

    @Override
    @Transactional
    public List<LiveLotteryConf> getByLiveId(Long liveId) {
        return mapper.selectByLiveId(liveId);
    }

    @Override
    @Transactional
    public void create(LiveLotteryConf conf) {
        mapper.insert(conf);
    }

    @Override
    @Transactional
    public void update(LiveLotteryConf conf) {
        mapper.updateAll(conf);
    }

    @Override
    @Transactional
    public void delete(Long lotteryId) {
        mapper.deleteById(lotteryId);
    }

    @Override
    public String startLottery(Long lotteryId, Long userId) {
        LiveLotteryConf conf = mapper.selectById(lotteryId);
        if (conf == null)
            return "抽奖不存在";
        if (!"0".equals(conf.getLotteryStatus()))
            return "抽奖已开始";
        //抽奖状态
        conf.setLotteryStatus("1");
        //修改时间
        conf.setUpdateTime(new Date());
        //修改人
        conf.setUpdateBy(userId.toString());
        mapper.updateAll(conf);
        return "开始抽奖成功";
    }

    @Override
    public void saveProducts(LiveLotteryProductSaveParam liveLotteryProducts) {
        //先删除
        productMapper.deleteLiveLotteryProductConfByLotteryId(liveLotteryProducts.getLotteryId());
        liveLotteryProducts.setCreateTime(DateUtils.getNowDate());
        productMapper.saveProducts(liveLotteryProducts);
    }

    @Override
    public LiveLotteryProductVO getGoods(Long lotteryId) {
        LiveLotteryProductVO liveLotteryProductVO = new LiveLotteryProductVO();
        liveLotteryProductVO.setLotteryId(lotteryId);
        liveLotteryProductVO.setPrizes(
                productMapper.selectLiveLotteryProductConfByLotteryId(lotteryId)
        );
        return liveLotteryProductVO;
    }

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

    @Override
    @Transactional
    public R claimLotteryPacket(LotteryPO lottery) {
        int i = lotteryRegistrationMapper.selectRecord(lottery.getUserId(), lottery.getLotteryId());
        if (i > 0) {
            return R.ok("您已参加抽奖活动，请等待开奖！");
        }
        LiveLotteryRegistration registration = new LiveLotteryRegistration();
        Date now = new Date();
        registration.setLiveId(lottery.getLiveId());
        registration.setUserId(lottery.getUserId());
        registration.setLotteryId(lottery.getLotteryId());
        registration.setIsWin(0L);
        registration.setRizeLevel(-1L);
        registration.setCreateTime(now);
        registration.setUpdateTime(now);
        lotteryRegistrationMapper.insertLiveLotteryRegistration(registration);
        return R.ok("参与抽奖成功！请在直播间等待开奖");
    }

    @Override
    public List<LiveLotteryConfVo> selectActivedLottery(Long liveId) {
        return baseMapper.selectActivedLottery(liveId);
    }

    @Override
    public List<LiveLotteryConfVo> selectByLotteryIds(Set<String> range) {
        return baseMapper.selectByLotteryIds(range);
    }

    @Override
    public List<LiveLotteryConfVo> selectVoListByLotteryIds(Set<String> range) {
        List<LiveLotteryConfVo> liveLotteryConfVos = baseMapper.selectByLotteryIds(range);
        List<Long> lotteryIds = liveLotteryConfVos.stream().map(LiveLotteryConfVo::getLotteryId).collect(Collectors.toList());
        if (!lotteryIds.isEmpty()) {
            List<LiveLotteryProductListVo> products = productMapper.selectLiveLotteryProductConfByLotteryIds(lotteryIds);
            for (LiveLotteryConfVo liveLotteryConf : liveLotteryConfVos) {
                liveLotteryConf.setProducts(products.stream().filter(product -> product.getLotteryId().equals(liveLotteryConf.getLotteryId())).collect(Collectors.toList()));
            }
        }
        return liveLotteryConfVos;
    }

    @Override
    public R detail(LotteryPO lottery) {
        LiveLotteryConfVo liveLotteryConf = baseMapper.selectLiveLotteryConfVoByLotteryId(lottery.getLotteryId());
        if (liveLotteryConf == null) {
            return R.error("抽奖不存在!");
        }
        if(!liveLotteryConf.getLotteryStatus().equals("1")) return R.error("抽奖未开始!");
        List<Long> lotteryIds = new ArrayList<>();
        lotteryIds.add(lottery.getLotteryId());
        List<LiveLotteryProductListVo> prizes = productMapper.selectLiveLotteryProductConfByLotteryIds(lotteryIds);
        liveLotteryConf.setProducts(prizes);
        return R.ok().put("data", liveLotteryConf);
    }

    @Override
    public void finishStatusByLotteryIds(List<Long> ids) {
        baseMapper.finishStatusByLotteryIds(ids);
    }

    @Override
    public List<LiveLotteryConf> selectLiveLotteryConfListOn(LiveLotteryConf liveLotteryConf) {
        return baseMapper.selectLiveLotteryConfListOn(liveLotteryConf);
    }

    @Override
    public List<LiveUserLotteryRecordVo> myLottery(long userId) {
        return baseMapper.selectLiveUserLotteryRecordByUserId(userId);
    }


}
