package edu.whut.trigger.http;

import com.alibaba.fastjson.JSON;
import edu.whut.api.IMarketIndexService;
import edu.whut.api.dto.GoodsMarketRequestDTO;
import edu.whut.api.dto.GoodsMarketResponseDTO;
import edu.whut.api.response.Response;
import edu.whut.domain.activity.model.entity.MarketProductEntity;
import edu.whut.domain.activity.model.entity.TrialBalanceEntity;
import edu.whut.domain.activity.model.entity.UserGroupBuyOrderDetailEntity;
import edu.whut.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import edu.whut.domain.activity.model.valobj.TeamStatisticVO;
import edu.whut.domain.activity.service.IIndexGroupBuyMarketService;
import edu.whut.types.annotations.RateLimiterAccessInterceptor;
import edu.whut.types.enums.ResponseCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@RestController
@CrossOrigin("*")
@RequiredArgsConstructor
@RequestMapping("/api/v1/gbm/index")
public class MarketIndexController implements IMarketIndexService {

    private final IIndexGroupBuyMarketService indexGroupBuyMarketService;

    // 每秒放 5 个令牌，超限 5 次后算进黑名单
    @RateLimiterAccessInterceptor(key = "userId", fallbackMethod = "queryGroupBuyMarketConfigFallBack", permitsPerSecond = 5.0d, blacklistCount = 5)
    @PostMapping("/query_group_buy_market_config")
    @Override
    public Response<GoodsMarketResponseDTO> queryGroupBuyMarketConfig(
            @RequestBody GoodsMarketRequestDTO req) {

        log.info("查询拼团营销配置开始: userId={} goodsId={}", req.getUserId(), req.getGoodsId());

        // —— 1. 参数校验 ——  req.getUserId()可为空
        if (StringUtils.isAnyBlank(req.getSource(), req.getChannel(), req.getGoodsId())) {
            return Response.<GoodsMarketResponseDTO>builder()
                    .code(ResponseCode.ILLEGAL_PARAMETER.getCode())
                    .info(ResponseCode.ILLEGAL_PARAMETER.getInfo())
                    .build();
        }

        try {
            // —— 2. 优惠试算 ——
            MarketProductEntity product = new MarketProductEntity();


            BeanUtils.copyProperties(req, product);
            //获得当前用户所得的优惠信息
            TrialBalanceEntity trial = indexGroupBuyMarketService.indexMarketTrial(product);

            GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = trial.getGroupBuyActivityDiscountVO();
            Long activityId = groupBuyActivityDiscountVO.getActivityId();

            // —— 3. 构建 Goods 子对象 ——
            GoodsMarketResponseDTO.Goods goods = new GoodsMarketResponseDTO.Goods();
            BeanUtils.copyProperties(trial, goods);

            // —— 4. 拼团队列 DTO 列表 ——
            //获取拼团展示列表
            List<UserGroupBuyOrderDetailEntity> userGroupBuyOrderDetailEntities = indexGroupBuyMarketService.queryInProgressUserGroupBuyOrderDetailList(
                            trial.getGroupBuyActivityDiscountVO().getActivityId(), 4);

            List<GoodsMarketResponseDTO.Team> teams = new ArrayList<>();
            if (null != userGroupBuyOrderDetailEntities && !userGroupBuyOrderDetailEntities.isEmpty()) {
                for (UserGroupBuyOrderDetailEntity userGroupBuyOrderDetailEntity : userGroupBuyOrderDetailEntities) {
                    GoodsMarketResponseDTO.Team team = GoodsMarketResponseDTO.Team.builder()
                            .userId(userGroupBuyOrderDetailEntity.getUserId())
                            .teamId(userGroupBuyOrderDetailEntity.getTeamId())
                            .activityId(userGroupBuyOrderDetailEntity.getActivityId())
                            .targetCount(userGroupBuyOrderDetailEntity.getTargetCount())
                            .completeCount(userGroupBuyOrderDetailEntity.getCompleteCount())
                            .lockCount(userGroupBuyOrderDetailEntity.getLockCount())
                            .validStartTime(userGroupBuyOrderDetailEntity.getValidStartTime())
                            .validEndTime(userGroupBuyOrderDetailEntity.getValidEndTime())
                            .validTimeCountdown(GoodsMarketResponseDTO.Team.differenceDateTime2Str(new Date(), userGroupBuyOrderDetailEntity.getValidEndTime()))
                            .outTradeNo(userGroupBuyOrderDetailEntity.getOutTradeNo())
                            .build();
                    teams.add(team);
                }
            }

            // —— 5. 统计数据 DTO ——
            TeamStatisticVO statVo = indexGroupBuyMarketService.queryTeamStatisticByActivityId(trial.getGroupBuyActivityDiscountVO().getActivityId());

            GoodsMarketResponseDTO.TeamStatistic stat = new GoodsMarketResponseDTO.TeamStatistic();
            BeanUtils.copyProperties(statVo, stat);

            // —— 6. 返回组装 ——
            GoodsMarketResponseDTO body = GoodsMarketResponseDTO.builder()
                    .activityId(activityId)
                    .goods(goods)
                    .teamList(teams)
                    .teamStatistic(stat)
                    .build();

            Response<GoodsMarketResponseDTO> resp = Response.<GoodsMarketResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(body)
                    .build();

            log.info("查询拼团营销配置完成: userId={} goodsId={} response={}",
                    req.getUserId(), req.getGoodsId(), JSON.toJSONString(resp));

            return resp;

        } catch (Exception e) {
            log.error("查询拼团营销配置失败: userId={} goodsId={}", req.getUserId(), req.getGoodsId(), e);
            return Response.<GoodsMarketResponseDTO>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    public Response<GoodsMarketResponseDTO> queryGroupBuyMarketConfigFallBack(@RequestBody GoodsMarketRequestDTO requestDTO) {
        log.error("查询拼团营销配置限流:{}", requestDTO.getUserId());
        return Response.<GoodsMarketResponseDTO>builder()
                .code(ResponseCode.RATE_LIMITER.getCode())
                .info(ResponseCode.RATE_LIMITER.getInfo())
                .build();
    }

}
