package com.ruoyi.wx.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.enums.LotteryTypeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.recovery.domain.WxLottery;
import com.ruoyi.framework.recovery.domain.WxUserLottery;
import com.ruoyi.framework.recovery.mapper.WxLotteryMapper;
import com.ruoyi.framework.recovery.mapper.WxUserLotteryMapper;
import com.ruoyi.wx.web.domain.dto.LotteryDto;
import com.ruoyi.wx.web.domain.vo.AwardVo;
import com.ruoyi.wx.web.domain.vo.LotteryVo;
import com.ruoyi.wx.web.service.IWxLotteryUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class WxLotteryUserServiceImpl implements IWxLotteryUserService {
    @Autowired
    private WxLotteryMapper wxLotteryMapper;

    @Autowired
    private WxUserLotteryMapper wxUserLotteryMapper;

    @Override
    public List<LotteryVo> getListById(Long lotteryId) {
        log.info("查询用户抽奖码入参：{}", lotteryId);
        if (lotteryId == null) {
            throw new ServiceException("入参不能为空");
        }
        WxUserLottery lottery = new WxUserLottery();
        String wxOpenid = SecurityUtils.getLoginWxUser().getWxUser().getWxOpenid();
        lottery.setOpenId(wxOpenid);
        lottery.setLotteryId(lotteryId);
        List<WxUserLottery> userLotteries = wxUserLotteryMapper.selectWxUserLotteryList(lottery);
        if (CollectionUtil.isEmpty(userLotteries)) {
            return new ArrayList<>();
        }
        // 根据抽奖类型分类
        List<LotteryVo> resultList = new ArrayList<>();
        Map<String, List<WxUserLottery>> typeMap = userLotteries.stream().collect(Collectors.groupingBy(WxUserLottery::getLotteryType));
        typeMap.forEach((key, value) -> {
            LotteryVo result = new LotteryVo();
            result.setLotteryType(key);
            result.setLotteryTypeName(LotteryTypeEnum.match(Integer.parseInt(key)).getDesc());
            result.setLotteryId(lotteryId);
            List<String> lotteryIds = new ArrayList<>();
            for (WxUserLottery userLottery : value) {
                lotteryIds.add(userLottery.getLotteryCode());
            }
            result.setLotteryCodes(lotteryIds);
            resultList.add(result);
        });
        return resultList;
    }

    @Override
    public LotteryVo addLottery(LotteryDto lotteryDto) {
        String wxOpenid = SecurityUtils.getLoginWxUser().getWxUser().getWxOpenid();
        WxUserLottery lottery = new WxUserLottery();
        lottery.setOpenId(wxOpenid);
        List<WxUserLottery> userLotteries = wxUserLotteryMapper.selectWxUserLotteryList(lottery);
        int total = lotteryDto.getNum() + userLotteries.size();
        if (total > 10) {
            throw new ServiceException("超出抽奖数量阈值");
        }
        List<String> lotteryCodes = new ArrayList<>();
        // 构建抽奖记录
        for (int i = 0 ; i < lotteryDto.getNum() ; i++) {
            WxUserLottery info = new WxUserLottery();
            info.setOpenId(wxOpenid);
            String lotteryCode = String.valueOf(System.currentTimeMillis()).substring(7);
            lotteryCode = lotteryCode + i;
            lotteryCodes.add(lotteryCode);
            info.setLotteryCode(lotteryCode);
            info.setLotteryType(lotteryDto.getType());
            info.setCreateDate(new Date());
            info.setLotteryId(lotteryDto.getLotteryId());
            wxUserLotteryMapper.insertWxUserLottery(info);
        }
        LotteryVo lotteryVo = new LotteryVo();
        lotteryVo.setLotteryCodes(lotteryCodes);
        lotteryVo.setLotteryId(lotteryVo.getLotteryId());
        lotteryVo.setLotteryType(lotteryDto.getType());
        lotteryVo.setLotteryTypeName(LotteryTypeEnum.match(Integer.parseInt(lotteryDto.getType())).getDesc());
        return lotteryVo;
    }

    @Override
    public List<AwardVo> getList(String type) {
        List<AwardVo> awardVos = new ArrayList<>();
        List<WxLottery> wxLotteries = wxLotteryMapper.selectWxLotteryListByTime(new Date(), type);
        // 查询历史获奖记录时会查到以及获奖内容
        if ("now".equals(type)) {
            for (WxLottery lottery : wxLotteries) {
                AwardVo awardVo = new AwardVo();
                BeanUtils.copyProperties(lottery, awardVo);
                awardVos.add(awardVo);
            }
        } else {
            for (WxLottery lottery : wxLotteries) {
                AwardVo awardVo = new AwardVo();
                List<Long> lotteryCodes = wxUserLotteryMapper.selectLotteryCodesByLotteryId(lottery.getId());
                List<String> lotteryCodeList = lotteryCodes.stream().map(String::valueOf).toList();
                BeanUtils.copyProperties(lottery, awardVo);
                awardVo.setLotteryCodes(lotteryCodeList);
                awardVos.add(awardVo);
            }
        }
        return awardVos;
    }
}
