package com.qs.mp.web.controller.api.user;

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicResponseParameters;
import com.qs.mp.admin.domain.*;
import com.qs.mp.admin.domain.dto.TicketDrawNumDTO;
import com.qs.mp.admin.domain.param.TicketBoxParam;
import com.qs.mp.admin.domain.param.TicketParam;
import com.qs.mp.admin.domain.vo.*;
import com.qs.mp.admin.service.*;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.core.redis.DistributedLocker;
import com.qs.mp.common.enums.*;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.utils.*;
import com.qs.mp.framework.redis.RedisLockKey;
import com.qs.mp.framework.security.handle.HostHolder;
import com.qs.mp.user.domain.UserHitPrize;
import com.qs.mp.user.domain.UserTicketOrderItem;
import com.qs.mp.user.domain.param.TicketAutoCashPrizeParam;
import com.qs.mp.user.domain.vo.TicketAwardsLabelVO;
import com.qs.mp.user.domain.vo.TicketHitPrizeBarrageVO;
import com.qs.mp.user.service.IUserExchangeOrderService;
import com.qs.mp.user.service.IUserHitPrizeService;
import com.qs.mp.user.service.IUserTicketOrderItemService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.POST;


@RestController
@RequestMapping("/api/v1/mp/user")
@Api(tags = "盲票商城接口")
@AllArgsConstructor
public class UserTicketController extends BaseApiController {


  @Autowired
  private ITicketBoxService ticketBoxService;

  @Autowired
  private ITicketAwardsPrizeService ticketAwardsPrizeService;

  @Autowired
  private ITicketService ticketService;

  @Autowired
  private IUserTicketOrderItemService userTicketOrderItemService;

  @Autowired
  private IUserHitPrizeService userHitPrizeService;

  @Autowired
  private ITicketPackageService ticketPackageService;

  @Autowired
  private MapperFacade mapperFacade;


  @Autowired
  private HostHolder hostHolder;

  @Autowired
  private IUserExchangeOrderService userExchangeOrderService;

  @Autowired
  private ITicketAwardsService ticketAwardsService;

  @Autowired
  private DistributedLocker distributedLocker;

  @Autowired
  private IChannelService channelService;

  /**
   * 盲票进货列表
   */
  @PostMapping("/mall/ticket/list")
  @ApiOperation(value = "盲票组列表", notes = "获取所有盲票信息")
  public TableDataInfo list(@RequestBody TicketBoxParam param) {

    startPage();
    List<TicketBox> ticketBoxes = ticketBoxService.list(
        new LambdaQueryWrapper<TicketBox>().eq(TicketBox::getType, param.getType())
            .eq(null != param.getCategoryId() && 0 != param.getCategoryId(),
                TicketBox::getCategoryId, param.getCategoryId())
            .eq(TicketBox::getStatus, TicketBoxStatusEnum.PUT_ON)
            .orderByDesc(TicketBox::getSortWeight)
    );
    List<TicketBoxListVO> ticketBoxListVOList = mapperFacade.mapAsList(ticketBoxes,
        TicketBoxListVO.class);
    TableDataInfo rspData = getDataTable(ticketBoxes);
    rspData.setRows(ticketBoxListVOList);
    return rspData;
  }


    /**
     * 查看盲票详情
     */
    // TODO: 下个版本删除
    @PostMapping("/mall/ticket/detail")
    @ApiOperation(value = "查看盲票详情", notes = "根据盲票组ID，获取盲票信息")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = TicketBoxVO.class)
    )
    public AjaxResult getInfo(@RequestBody TicketBoxParam param) {
      if (StringUtils.isBlank(param.getBoxId())) {
        return AjaxResult.error("参数异常，盲票组ID缺失");
      }
      TicketBox ticketBox = ticketBoxService.getById(param.getBoxId());
      TicketBoxVO ticketBoxVO = mapperFacade.map(ticketBox, TicketBoxVO.class);


      // 设置经销商佣金比
      if (hostHolder.getUser() != null) {
        Long channelId = hostHolder.getUser().getChannelId();
        if (channelId != null && channelId > 0) {
          Channel channel = channelService.getById(channelId);
          if (channel != null) {
            ticketBoxVO.setChannelCommRate(channel.getCommRate());
          }
        }
      }



      // 设置奖项标签信息
      QueryWrapper<TicketAwards> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("box_id",ticketBox.getBoxId());
      queryWrapper.isNotNull("awards_label");
      queryWrapper.ne("awards_label", "");
      queryWrapper.groupBy("awards_label");
      StringBuilder sortField = new StringBuilder("FIELD(awards_label,'");
      int index = 0;
      for (AwardsLabelEnum awardsLabelEnum : AwardsLabelEnum.values()) {
        index++;
        if (index == AwardsLabelEnum.values().length) {
          sortField.append(awardsLabelEnum.getValue()).append("'");
        }else {
          sortField.append(awardsLabelEnum.getValue()).append("','");
        }
      }
      sortField.append(")");
      queryWrapper.orderByAsc(sortField.toString());
      List<TicketAwardsLabelVO> ticketAwardsLabelVOS = ticketAwardsService.groupSumQuantityByQueryWrapper(queryWrapper);
      if (CollectionUtils.isNotEmpty(ticketAwardsLabelVOS)) {
        for (TicketAwardsLabelVO ticketAwardsLabelVO : ticketAwardsLabelVOS) {
          AwardsLabelEnum awardsLabelEnum = AwardsLabelEnum.getByValue(ticketAwardsLabelVO.getLabelTitle());
          if (Objects.isNull(awardsLabelEnum)) {
            continue;
          }
          ticketAwardsLabelVO.setPicUrl(awardsLabelEnum.getPicUrl());
          Integer quantity = ticketBox.getQuantity();
          int num = ticketAwardsLabelVO.getQuantity();
          ticketAwardsLabelVO.setHitRate(BigDecimal.valueOf(num).divide(BigDecimal.valueOf(quantity), 3, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)));
        }
      }

    if (CollectionUtils.isNotEmpty(ticketAwardsLabelVOS)) {
      // 精度问题处理
      int maxIndex = 0;
      BigDecimal maxHitRate = BigDecimal.valueOf(100);
      for (int i = 0; i < ticketAwardsLabelVOS.size(); i++) {
        TicketAwardsLabelVO ticketAwardsLabelVO = ticketAwardsLabelVOS.get(i);
        if (BigDecimal.ZERO.equals(ticketAwardsLabelVO.getHitRate())) {
          ticketAwardsLabelVO.setHitRate(BigDecimal.valueOf(0.1));
        }
        if (ticketAwardsLabelVO.getHitRate().compareTo(ticketAwardsLabelVOS.get(maxIndex).getHitRate()) > 0) {
          maxIndex = i;
        }
        maxHitRate = maxHitRate.subtract(ticketAwardsLabelVO.getHitRate());
      }
      if (maxHitRate.compareTo(BigDecimal.ZERO) > 0) {
        TicketAwardsLabelVO ticketAwardsLabelVO = ticketAwardsLabelVOS.get(maxIndex);
        ticketAwardsLabelVO.setHitRate(ticketAwardsLabelVO.getHitRate().subtract(maxHitRate));
      } else {
        TicketAwardsLabelVO ticketAwardsLabelVO = ticketAwardsLabelVOS.get(maxIndex);
        ticketAwardsLabelVO.setHitRate(ticketAwardsLabelVO.getHitRate().add(maxHitRate));
      }
    }

    ticketBoxVO.setTicketAwardsLabelList(ticketAwardsLabelVOS);

    List<TicketAwardsPrizeVO> ticketAwardsPrizeVOS = ticketAwardsPrizeService.listPrizeVO(ticketBox.getBoxId());
    ticketBoxVO.setPrizeList(ticketAwardsPrizeVOS);
    return AjaxResult.success(ticketBoxVO);
  }


  /**
   * 查看盲票详情
   */
  @PostMapping("/mall/ticket/detail/new")
  @ApiOperation(value = "查看盲票详情(新)", notes = "根据盲票组ID，获取盲票信息")
  @ApiResponses(
      @ApiResponse(code = 200, message = "成功", response = TicketBoxVO.class)
  )
  public AjaxResult getInfoNew(@RequestBody TicketBoxParam param) {
    if (StringUtils.isBlank(param.getBoxId())) {
      return AjaxResult.error("参数异常，盲票组ID缺失");
    }
    TicketBox ticketBox = ticketBoxService.getById(param.getBoxId());
    TicketBoxVO ticketBoxVO = mapperFacade.map(ticketBox, TicketBoxVO.class);


    // 设置经销商佣金比
    if (hostHolder.getUser() != null) {
      Long channelId = hostHolder.getUser().getChannelId();
      if (channelId != null && channelId > 0) {
        Channel channel = channelService.getById(channelId);
        if (channel != null) {
          ticketBoxVO.setChannelCommRate(channel.getCommRate());
        }
      }
    }



    // 设置奖项标签信息
    QueryWrapper<TicketAwards> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("box_id",ticketBox.getBoxId());
    queryWrapper.isNotNull("awards_label");
    queryWrapper.ne("awards_label", "");
    queryWrapper.groupBy("awards_label");
    StringBuilder sortField = new StringBuilder("FIELD(awards_label,'");
    int index = 0;
    for (AwardsLabelEnum awardsLabelEnum : AwardsLabelEnum.values()) {
      index++;
      if (index == AwardsLabelEnum.values().length) {
        sortField.append(awardsLabelEnum.getValue()).append("'");
      }else {
        sortField.append(awardsLabelEnum.getValue()).append("','");
      }
    }
    sortField.append(")");
    queryWrapper.orderByAsc(sortField.toString());
    List<TicketAwardsLabelVO> ticketAwardsLabelVOS = ticketAwardsService.groupSumQuantityByQueryWrapper(queryWrapper);
    if (CollectionUtils.isNotEmpty(ticketAwardsLabelVOS)) {
      for (TicketAwardsLabelVO ticketAwardsLabelVO : ticketAwardsLabelVOS) {
        AwardsLabelEnum awardsLabelEnum = AwardsLabelEnum.getByValue(ticketAwardsLabelVO.getLabelTitle());
        if (Objects.isNull(awardsLabelEnum)) {
          continue;
        }
        ticketAwardsLabelVO.setPicUrl(awardsLabelEnum.getPicUrl());
        Integer quantity = ticketBox.getQuantity();
        int num = ticketAwardsLabelVO.getQuantity();
        ticketAwardsLabelVO.setHitRate(BigDecimal.valueOf(num).divide(BigDecimal.valueOf(quantity), 3, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)));
      }
    }

    if (CollectionUtils.isNotEmpty(ticketAwardsLabelVOS)) {
      // 精度问题处理
      int maxIndex = 0;
      BigDecimal maxHitRate = BigDecimal.valueOf(100);
      for (int i = 0; i < ticketAwardsLabelVOS.size(); i++) {
        TicketAwardsLabelVO ticketAwardsLabelVO = ticketAwardsLabelVOS.get(i);
        if (BigDecimal.ZERO.equals(ticketAwardsLabelVO.getHitRate())) {
          ticketAwardsLabelVO.setHitRate(BigDecimal.valueOf(0.1));
        }
        if (ticketAwardsLabelVO.getHitRate().compareTo(ticketAwardsLabelVOS.get(maxIndex).getHitRate()) > 0) {
          maxIndex = i;
        }
        maxHitRate = maxHitRate.subtract(ticketAwardsLabelVO.getHitRate());
      }
      if (maxHitRate.compareTo(BigDecimal.ZERO) > 0) {
        TicketAwardsLabelVO ticketAwardsLabelVO = ticketAwardsLabelVOS.get(maxIndex);
        ticketAwardsLabelVO.setHitRate(ticketAwardsLabelVO.getHitRate().subtract(maxHitRate));
      } else {
        TicketAwardsLabelVO ticketAwardsLabelVO = ticketAwardsLabelVOS.get(maxIndex);
        ticketAwardsLabelVO.setHitRate(ticketAwardsLabelVO.getHitRate().add(maxHitRate));
      }
    }

    ticketBoxVO.setTicketAwardsLabelList(ticketAwardsLabelVOS);


    // 轮播图的十个奖品
    StringBuilder sb = new StringBuilder("FIELD(t1.awards_label,'");
    int i = 0;
    for (AwardsLabelEnum awardsLabelEnum : AwardsLabelEnum.values()) {
      i++;
      if (i == AwardsLabelEnum.values().length) {
        sb.append(awardsLabelEnum.getValue()).append("'");
      }else {
        sb.append(awardsLabelEnum.getValue()).append("','");
      }
    }
    sb.append(")");

    List<TicketAwardsPrizeVO> ticketAwardsPrizeVOS = ticketAwardsPrizeService.listPrizeVO(new QueryWrapper<TicketAwardsPrize>()
        .eq("t1.box_id", ticketBox.getBoxId())
        .eq("t2.is_deleted", 0)
        .orderByAsc(sb.toString())
        .orderByAsc("t1.sort")
        .orderByDesc("t2.sort_weight")
        .orderByDesc("t2.value")
        .last("limit 10"));
    ticketBoxVO.setPrizeList(ticketAwardsPrizeVOS);
    return AjaxResult.success(ticketBoxVO);
  }


  @PostMapping("/ticket/prize/list/{boxId}")
  @ApiOperation("查询盲票下奖品列表")
  public TableDataInfo listPrize(@PathVariable("boxId") String boxId) {
      startPage();
      List<TicketAwardsPrizeVO> ticketAwardsPrizeVOS = ticketAwardsPrizeService.listPrizeVO(boxId);
      return getDataTable(ticketAwardsPrizeVOS);
  }

  /**
   * 扫码查看盲票幸运数字
   */
  @PostMapping("/ticket/queryLuckyNum")
  @ApiOperation(value = "查看盲票幸运数字", notes = "根据盲票组ID，获取盲票幸运数字")
  @ApiResponses(
          @ApiResponse(code = 200, message = "success", response = TicketVO.class)
  )
  public AjaxResult queryLuckyNum(@RequestBody TicketParam param) {

    if (StringUtils.isBlank(param.getSerialNo())) {
      return AjaxResult.error("参数异常，盲票序列号缺失");
    }

    String serialNo = param.getSerialNo();
    boolean match = ReUtil.isMatch("^\\w*-\\w*-\\w*$", serialNo);
    if (!match) {
      serialNo = AESUtil.decrypt(serialNo);
    }
    Ticket ticket = ticketService.getOne(
            new LambdaQueryWrapper<Ticket>().eq(Ticket::getSerialNo, serialNo));

    if (null == ticket) {
      return AjaxResult.error("参数异常，盲票不存在");
    }

    TicketBox ticketBox = ticketBoxService.getById(ticket.getBoxId());
    if (ticketBox.getIsEncrypt() == 1 && match) {
      LogUtil.error(logger, "非法访问,serialNo:{0},param:{1}", serialNo, param);
      return AjaxResult.error("非法访问!");
    }


    /*if (ticket.getStatus() == TicketStatusEnum.CASHED) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1017);
    }*/
    TicketPackage ticketPackage = ticketPackageService.getById(ticket.getPkgId());
    if (ticketPackage.getStatus() != TicketPkgStatusEnum.SOLD) {
      LogUtil.warn(logger, "盲票未激活。sn:{0},pkgId:{1}", new Object[]{ticket.getSerialNo(), ticket.getPkgId()});
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1023);
    }


    TicketVO ticketVO = new TicketVO();
    ticketVO.setPrizeList(ticketAwardsPrizeService.listPrizeVO(ticket.getBoxId()));
    ticketVO.setTicketId(ticket.getTicketId());
    ticketVO.setBoxId(ticket.getBoxId());
    ticketVO.setTitle(ticketBox.getTitle());
    ticketVO.setSerialNo(ticket.getSerialNo());
    ticketVO.setFacePrice(ticket.getFacePrice());
    ticketVO.setSalePrice(ticketBox.getSalePrice());
    ticketVO.setPlainLuckyNum(ticket.getPlainLuckyNum());
    ticketVO.setStatus(ticket.getStatus().getValue());
    ticketVO.setPicUrl(ticketBox.getPicUrl());

    // 设置奖项名
    if (Objects.nonNull(ticket.getPlainLuckyNum())) {
      List<TicketDrawNumDTO> drawNumDTOList = JSONObject.parseArray(ticket.getDrawNum(), TicketDrawNumDTO.class);
      for (TicketDrawNumDTO ticketDrawNumDTO : drawNumDTOList) {
        if (ticketDrawNumDTO.getNum() == ticket.getPlainLuckyNum()) {
          ticketVO.setAwardsName(ticketDrawNumDTO.getName());
        }
      }
    }

    if (ticketPackage.getIsPre() == 1) {
      // 预付票设置售价为0
      ticketVO.setSalePrice(0);
    }

    return AjaxResult.success(ticketVO);
  }

  /**
   * 根据盲票购买订单号查看盲票详情
   */
  @PostMapping("/ticket/query")
  @ApiOperation(value = "查看盲票详情", notes = "根据盲票购买订单号，查看盲票详情")
  public AjaxResult queryTicket(@RequestBody TicketParam param) {
    Long userId = SecurityUtils.getLoginUser().getUserId();
    if (StringUtils.isBlank(param.getOrderId())) {
      return AjaxResult.error("参数缺失");
    }

    TicketListVO ticketListVO = userTicketOrderItemService.queryTicketVO(userId,
        param.getOrderId());
    return AjaxResult.success(ticketListVO);
  }

  /**
   * 查看能兑奖的奖品
   */
  @PostMapping("/ticket/queryHitPrizeList")
  @ApiOperation(value = "查看兑奖奖品", notes = "根据盲票ID，查看兑奖奖品")
  public AjaxResult queryHitPrizeList(@RequestBody TicketParam param) {
    Long userId = SecurityUtils.getLoginUser().getUserId();
    if (StringUtils.isBlank(param.getTicketId())) {
      return AjaxResult.error("参数缺失");
    }
    Ticket ticket = ticketService.getById(param.getTicketId());

    if (null == ticket) {
      return AjaxResult.error("参数异常，盲票不存在");
    }
    if (ticket.getStatus() == TicketStatusEnum.CASHED) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1017);
    }
    if (ticket.getStatus() != TicketStatusEnum.ACTIVATED) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1019);
    }
    // 已付款的盲票，需要校验当前用户是否有权限查看
    UserTicketOrderItem orderItem = userTicketOrderItemService.queryFinishedOrderItem(userId,
        ticket.getTicketId());
    if (null == orderItem) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1018);
    }

    // 线上盲票不支持查看兑奖奖品
    TicketBox ticketBox = ticketBoxService.getById(ticket.getBoxId());
    if (TicketTypeEnum.ONLINE.equals(ticketBox.getType())) {
      LogUtil.error(logger, "线上盲票不支持查看兑奖奖品。ticketId:{0}", ticket.getTicketId());
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1000);
    }

    List<TicketAwardsPrize> ticketAwardsPrizes = userHitPrizeService.listPrize(ticket, userId);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("prizeList", ticketAwardsPrizes);
    jsonObject.put("ticketId", ticket.getTicketId());
    jsonObject.put("boxId", ticket.getBoxId());
    return AjaxResult.success(jsonObject);
  }

  @PostMapping("/ticket/autoCashPrize")
  @ApiOperation("自动开奖")
  public AjaxResult autoCashPrize(@Validated @RequestBody TicketAutoCashPrizeParam param) {
    Long userId = SecurityUtils.getLoginUser().getUserId();
    if (Objects.nonNull(param.getTicketId())) {
      Ticket ticket = ticketService.getById(param.getTicketId());
      UserTicketOrderItem userTicketOrderItem = userTicketOrderItemService.getOne(new LambdaQueryWrapper<UserTicketOrderItem>()
              .eq(UserTicketOrderItem::getTicketId, param.getTicketId())
              .eq(UserTicketOrderItem::getUserId, userId));
      if (Objects.isNull(ticket) || Objects.isNull(userTicketOrderItem)) {
        return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1018);
      }
      param.setBoxId(ticket.getBoxId());
      param.setOrderId(userTicketOrderItem.getOrderId());
      param.setIsTry(0);
    }

    return AjaxResult.success(userHitPrizeService.autoCashPrize(userId, param));
  }

  /**
   * 兑奖
   */
  @PostMapping("/ticket/cashPrize")
  @ApiOperation(value = "兑奖", notes = "选择奖品兑奖")
  public AjaxResult cashPrize(@RequestBody TicketParam param) {
    Long userId = SecurityUtils.getLoginUser().getUserId();
    if (StringUtils.isBlank(param.getTicketId()) || StringUtils.isBlank(param.getAwardsId())
        || StringUtils.isBlank(param.getPrizeId())) {
      return AjaxResult.error("参数缺失");
    }

    Ticket ticket = ticketService.getById(param.getTicketId());
    if (null == ticket) {
      return AjaxResult.error("参数异常，盲票不存在");
    }
    if (ticket.getStatus() == TicketStatusEnum.CASHED) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1017);
    }
    if (ticket.getStatus() != TicketStatusEnum.ACTIVATED) {
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1019);
    }

    // 线上盲票不支持手动兑奖
    TicketBox ticketBox = ticketBoxService.getById(ticket.getBoxId());
    if (TicketTypeEnum.ONLINE.equals(ticketBox.getType())) {
      LogUtil.error(logger, "线上盲票不支持手动兑奖。ticketId:{0}", ticket.getTicketId());
      return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1000);
    }

    // 兑奖
    String lockKey = RedisLockKey.build(RedisLockKey.USER_TICKET_CASH_LOCK, param.getPrizeId());
    if (!distributedLocker.tryLock(lockKey)) {
      return AjaxResult.error("系统繁忙，请稍后再试");
    }
    try {
      // 兑奖
      userHitPrizeService.cashPrize(ticket, userId, param.getAwardsId(), param.getPrizeId());
    } finally {
      distributedLocker.unlock(lockKey);
    }

    return AjaxResult.success();
  }

  @PostMapping("/ticket/hitPrizeBarrage")
  @ApiOperation(value = "中奖弹幕", notes = "获取最近中奖的 20-22 条信息")
  @DynamicResponseParameters(properties = {
    @DynamicParameter(name = "listOne", value = "列表 1",required = true, dataTypeClass = TicketHitPrizeBarrageVO.class),
    @DynamicParameter(name = "listTwo", value = "列表 2",required = true, dataTypeClass = TicketHitPrizeBarrageVO.class)
  })
  public AjaxResult hitPrizeBarrage() {

    // 获取用户 id
    Long userId = 0L;

    if (hostHolder.getUser() != null) {
      userId = hostHolder.getUser().getUserId();
    }

    // 弹幕列表
    List<TicketHitPrizeBarrageVO> listOne = new ArrayList<>();
    List<TicketHitPrizeBarrageVO> listTwo = new ArrayList<>();


    // 获取除当前用户外最近10条盲豆大于1000的商品兑换数据
    QueryWrapper<TicketHitPrizeBarrageVO> queryWrapper = new QueryWrapper<>();
    queryWrapper.ge("t1.order_coin", 1000);
    queryWrapper.notIn("t1.user_id", userId);
    queryWrapper.orderByDesc("t1.created_time");
    queryWrapper.last("limit 10");
    List<TicketHitPrizeBarrageVO> exchangeList = userExchangeOrderService.listByWrapper(queryWrapper);

    // 获取当前用户当天的商品兑换数据
    LocalDateTime startTime = LocalDateTime.of(LocalDateTime.now().toLocalDate(), LocalTime.MIN);
    LocalDateTime endTime = LocalDateTime.now().withNano(0);
    queryWrapper.clear();
    queryWrapper.eq("t1.user_id", userId);
    queryWrapper.between("t1.created_time", startTime, endTime);
    List<TicketHitPrizeBarrageVO> userExchangeList = userExchangeOrderService.listByWrapper(queryWrapper);


    if (CollectionUtils.isNotEmpty(userExchangeList)) {
      exchangeList.addAll(userExchangeList);
    }

    for (TicketHitPrizeBarrageVO ticketHitPrizeBarrageVO : exchangeList) {
      // 设置为兑换类型
      ticketHitPrizeBarrageVO.setType(2);
    }



    // 获取用户当天中奖的 2 条弹幕
    if (userId != 0L) {
      List<TicketHitPrizeBarrageVO> ticketHitPrizeBarrageVOList = userHitPrizeService.hitPrizeBarrageByUserId(userId);
      if (CollectionUtils.isNotEmpty(ticketHitPrizeBarrageVOList)) {
        for (int i = 0; i < ticketHitPrizeBarrageVOList.size(); i++) {
          // 类型为盲豆则拼接数量
          if(TicketPrizeTypeEnum.COIN.getValue().equals(ticketHitPrizeBarrageVOList.get(i).getPrizeType())){
            ticketHitPrizeBarrageVOList.get(i).setPrizeInfo(ticketHitPrizeBarrageVOList.get(i).getPrizeInfo() + ticketHitPrizeBarrageVOList.get(i).getValue() + "个");
          }

          // 设置类型为中奖
          ticketHitPrizeBarrageVOList.get(i).setType(1);


          listOne.add(ticketHitPrizeBarrageVOList.get(i));

        }
      }
    }
    // 获取除该用户外，最近中奖的 40 条弹幕信息
    List<TicketHitPrizeBarrageVO> ticketHitPrizeBarrageVOList = userHitPrizeService.hitPrizeBarrage(userId);


    for (TicketHitPrizeBarrageVO ticketHitPrizeBarrageVO : ticketHitPrizeBarrageVOList) {
      // 设置为中奖类型
      ticketHitPrizeBarrageVO.setType(1);
    }

    // 增加兑奖信息并且按时间排序
    ticketHitPrizeBarrageVOList.addAll(exchangeList);

    ticketHitPrizeBarrageVOList.sort((o1, o2) -> o2.getCreatedTime().compareTo(o1.getCreatedTime()));

    // 获取除该用户外，近 6 个月，8 条高级中奖弹幕信息
    List<TicketHitPrizeBarrageVO> expensiveHitPrizeBarrageList = userHitPrizeService.expensiveHitPrizeBarrage(userId);
    int count = 0;
    int index = 0;
    if (CollectionUtils.isNotEmpty(expensiveHitPrizeBarrageList)) {
      count = expensiveHitPrizeBarrageList.size();
      // 去重
      ticketHitPrizeBarrageVOList.removeAll(expensiveHitPrizeBarrageList);
    }


    for (int i = 0; i < ticketHitPrizeBarrageVOList.size(); i++) {
      // 类型为盲豆则拼接数量
      if(TicketPrizeTypeEnum.COIN.getValue().equals(ticketHitPrizeBarrageVOList.get(i).getPrizeType())){
        ticketHitPrizeBarrageVOList.get(i).setPrizeInfo(ticketHitPrizeBarrageVOList.get(i).getPrizeInfo() + ticketHitPrizeBarrageVOList.get(i).getValue() + "个");
      }

      // 插入大奖弹幕
      if (count != 0 && i % 5 == 0) {
        // 设置类型为中奖
        expensiveHitPrizeBarrageList.get(index).setType(1);
        listOne.add(expensiveHitPrizeBarrageList.get(index));

        count--;
        index++;
      }


      listOne.add(ticketHitPrizeBarrageVOList.get(i));

    }
    Map<String,List<TicketHitPrizeBarrageVO>> ticketHitPrizeBarrageMap = new HashMap<>();
    ticketHitPrizeBarrageMap.put("listOne",listOne);
    ticketHitPrizeBarrageMap.put("listTwo",listTwo);

    return AjaxResult.success(ticketHitPrizeBarrageMap);
  }






}
