package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.ActivityPlanDao;
import com.yonge.cooleshow.biz.dal.dto.ActivityPlanDto;
import com.yonge.cooleshow.biz.dal.dto.ActivityPlanRewardDto;
import com.yonge.cooleshow.biz.dal.dto.req.OrderPayReq;
import com.yonge.cooleshow.biz.dal.dto.search.OrderSearch;
import com.yonge.cooleshow.biz.dal.entity.ActivityEvaluation;
import com.yonge.cooleshow.biz.dal.entity.ActivityPlanReward;
import com.yonge.cooleshow.biz.dal.entity.ActivityUserReward;
import com.yonge.cooleshow.biz.dal.enums.GoodTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.OrderTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.activity.ActivityRankingMethodEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.ActivityPlanVo;
import com.yonge.cooleshow.biz.dal.vo.ActivityRankingVo;
import com.yonge.cooleshow.biz.dal.vo.UserOrderVo;
import com.yonge.cooleshow.common.enums.ActivityResourceEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yonge.cooleshow.biz.dal.entity.ActivityPlanEvaluation;
import com.yonge.cooleshow.biz.dal.dao.ActivityPlanEvaluationDao;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ActivityPlanEvaluationServiceImpl extends ServiceImpl<ActivityPlanEvaluationDao, ActivityPlanEvaluation> implements ActivityPlanEvaluationService {
    private final static Logger log = LoggerFactory.getLogger(ActivityPlanEvaluationServiceImpl.class);

    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private ActivityRewardService activityRewardService;
    @Autowired
    private ActivityUserRewardService activityUserRewardService;
    @Autowired
    private ActivityPlanRewardService activityPlanRewardService;

    @Autowired
    private ActivityPlanService activityPlanService;

    @Autowired
    private ActivityEvaluationRecordService activityEvaluationRecordService;

    @Autowired
    private ActivityEvaluationService activityEvaluationService;
    @Autowired
    private ActivityPlanDao activityPlanMapper;

    @Override
    public boolean createOrUpdate(ActivityPlanDto activityPlan) {
        ActivityPlanEvaluation planExpand = activityPlan.getPlanEvaluation();

        if (null == planExpand.getId()) {
            planExpand.setId(activityPlan.getId());
            planExpand.setCreateBy(activityPlan.getUserId());
            planExpand.setUpdateBy(activityPlan.getUserId());
            saveOrUpdate(planExpand);
        } else {
            planExpand.setUpdateBy(activityPlan.getUserId());
            updateById(planExpand);
        }
        return true;
    }

    @Override
    public void closeActivity(Long activityId) {
        OrderSearch query = new OrderSearch();
        query.setOrderType(OrderTypeEnum.ACTI_REGIST.getCode());
        query.setGoodType(GoodTypeEnum.ACTI_REGIST.getCode());
        query.setBizId(activityId);
        List<UserOrderVo> userOrderVos = userOrderService.selectAllList(query);
        for (UserOrderVo userOrderVo : userOrderVos) {
            OrderPayReq payReq = new OrderPayReq();
            payReq.setOrderNo(userOrderVo.getOrderNo());
            payReq.setUserId(userOrderVo.getUserId());
            payReq.setReason("活动已结束");
            userOrderService.orderCancel(payReq);
        }
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void successActivity(Long activityId) {
        //关闭未付款订单
        closeActivity(activityId);

        ActivityPlanVo detail = activityPlanService.detail(activityId);
        List<ActivityUserReward> activityUserRewardList = new ArrayList<>();

        List<ActivityEvaluation> activityEvaluationList = activityEvaluationService.lambdaQuery()
                                                                 .eq(ActivityEvaluation::getActivityId, activityId)
                                                                 .list();

        //活动需要发放的奖品
        Map<String, List<ActivityPlanRewardDto>> rewardMap = detail.getActivityRewardList().stream()
                                                                                 .collect(Collectors.groupingBy(
                                                                                         ActivityPlanReward::getGroup));

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        try {
            date = formatter.parse(formatter.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 总分排名发奖流程
        if (ActivityRankingMethodEnum.TOTAL_SCORE == detail.getRankingMethod()) {

            // 查询活动获奖用户信息
            List<ActivityRankingVo> rankingInfos = activityPlanMapper.selectActivityHighestScoreRankingInfo(detail.getId(), null,
                    detail.getRankingScore(), 9999);

            if (CollectionUtils.isEmpty(detail.getActivityRewardList())) {
                // 活动未关联奖品，忽略后续流程
                return;
            }

            // 活动关联奖品ID
            List<Long> activityRewardIds = detail.getActivityRewardList().stream()
                    .map(ActivityPlanReward::getId).collect(Collectors.toList());

            int ranking = 0;
            for (ActivityRankingVo rankingInfo : rankingInfos) {

                // 推送发奖消息给用户
                List<Long> collect = activityRewardService.sendReward(rankingInfo.getUserId(), activityId, activityRewardIds, date);

                // 活动奖品信息
                for (ActivityPlanRewardDto reward : detail.getActivityRewardList()) {

                    ActivityUserReward activityUserReward = new ActivityUserReward();
                    activityUserReward.setActivityId(activityId);
                    activityUserReward.setBizId(rankingInfo.getResourceId());
                    activityUserReward.setUserId(rankingInfo.getUserId());
                    activityUserReward.setRankingRule(detail.getRankingRule());
                    activityUserReward.setRanking(ranking++);
                    // 奖品发送状态
                    activityUserReward.setGrantFlag(collect.contains(reward.getId()) ? 1 : 0);
                    // 获取最高分时间
                    activityUserReward.setWinningTime(rankingInfo.getJoinDate());
                    activityUserReward.setCreateTime(date);
                    activityUserReward.setUpdateTime(date);
                    activityUserReward.setRewardId(reward.getRewardId());

                    // 添加发放记录
                    activityUserRewardList.add(activityUserReward);
                }

                // 若奖品数量超过1000，提交数据刷新缓存
                if (activityUserRewardList.size() > 1000) {

                    // 提交奖品发放记录
                    activityUserRewardService.saveBatch(activityUserRewardList);

                    // 清除缓存数据
                    activityUserRewardList.clear();
                }
            }

        } else {

            // 曲目排名发奖流程
            for (ActivityEvaluation activityEvaluation : activityEvaluationList) {

                List<ActivityRankingVo> activityRankingVos = activityEvaluationRecordService.queryRankingList(activityId,
                        activityEvaluation.getId(),detail.getRanking());
                for (int i = 0; i < activityRankingVos.size(); i++) {

                    ActivityRankingVo activityRankingVo = activityRankingVos.get(i);

                    List<ActivityPlanRewardDto> activityPlanRewardDtos = rewardMap.get(i + 1 + "");
                    if (CollectionUtils.isEmpty(activityPlanRewardDtos)) {
                        continue;
                    }

                    // 活动关联奖品ID
                    List<Long> activityRewardIds = activityPlanRewardDtos.stream()
                            .map(ActivityPlanReward::getId).collect(Collectors.toList());

                    //给用户发放奖品 传入用户id和活动id
                    List<Long> collect = activityRewardService.sendReward(activityRankingVo.getUserId(), activityId, activityRewardIds, date);

                    // 保存奖品发放记录
                    for (ActivityPlanRewardDto item : activityPlanRewardDtos) {

                        ActivityUserReward activityUserReward = new ActivityUserReward();
                        activityUserReward.setActivityId(activityId);
                        activityUserReward.setBizId(activityEvaluation.getId());
                        activityUserReward.setUserId(activityRankingVo.getUserId());
                        activityUserReward.setRankingRule(detail.getRankingRule());
                        activityUserReward.setRanking(i+1);
                        activityUserReward.setGrantFlag(0);
                        activityUserReward.setWinningTime(activityRankingVo.getJoinDate());
                        activityUserReward.setCreateTime(date);
                        activityUserReward.setUpdateTime(date);
                        activityUserReward.setRewardId(item.getRewardId());

                        // 奖品发送状态
                        if (collect.contains(item.getId())) {
                            activityUserReward.setGrantFlag(1);
                        }
                        activityUserRewardList.add(activityUserReward);
                    }

                }
            }

        }

        if (CollectionUtils.isNotEmpty(activityUserRewardList)) {
            activityUserRewardService.saveBatch(activityUserRewardList);
        }

        //发完奖后将库存归还
        // activityPlanRewardService.recoveryReward(activityId);
    }
}