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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.ActivityRegistrationDao;
import com.yonge.cooleshow.biz.dal.dao.SubjectDao;
import com.yonge.cooleshow.biz.dal.dto.search.ActivityRegistrationSearch;
import com.yonge.cooleshow.biz.dal.entity.ActivityEvaluationRecord;
import com.yonge.cooleshow.biz.dal.entity.ActivityPlan;
import com.yonge.cooleshow.biz.dal.entity.ActivityRegistration;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.enums.activity.ActivityRankingMethodEnum;
import com.yonge.cooleshow.biz.dal.service.ActivityEvaluationRecordService;
import com.yonge.cooleshow.biz.dal.service.ActivityPlanService;
import com.yonge.cooleshow.biz.dal.service.ActivityRegistrationService;
import com.yonge.cooleshow.biz.dal.service.SubjectService;
import com.yonge.cooleshow.biz.dal.vo.ActivityRegistrationVo;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityRegistrationServiceImpl extends ServiceImpl<ActivityRegistrationDao, ActivityRegistration> implements ActivityRegistrationService {

    @Autowired
    private ActivityEvaluationRecordService activityEvaluationRecordService;
    @Autowired
    private ActivityPlanService activityPlanService;
    @Autowired
    private SubjectService subjectService;
	@Override
    public ActivityRegistrationVo detail(Long id) {
        return baseMapper.detail(id);
    }
    
    @Override
    public IPage<ActivityRegistrationVo> selectPage(IPage<ActivityRegistrationVo> page, ActivityRegistrationSearch query) {

        // 活动参与用户信息
        List<ActivityRegistrationVo> activityUserInfos = baseMapper.selectPage(page, query);

        List<Long> userIds = activityUserInfos.stream()
                .map(ActivityRegistration::getUserId).distinct().collect(Collectors.toList());

        ActivityPlan activity = activityPlanService.getById(query.getActivityId());
        // 查询用户活动评测获排名最高记录
        if (CollectionUtils.isNotEmpty(userIds) && Objects.nonNull(activity)) {

            if (ActivityRankingMethodEnum.TOTAL_SCORE == activity.getRankingMethod()) {

                // 总分排名
                Map<Long, ActivityEvaluationRecord> collect = activityEvaluationRecordService.list(Wrappers.<ActivityEvaluationRecord>lambdaQuery()
                        .eq(ActivityEvaluationRecord::getActivityId, activity.getId())
                        .in(ActivityEvaluationRecord::getUserId, userIds)
                        .eq(ActivityEvaluationRecord::getRankingMethod, activity.getRankingMethod().getCode())).stream()
                        .collect(Collectors.toMap(ActivityEvaluationRecord::getUserId, Function.identity(), (o, n) -> n));

                // 声部信息
                List<Long> subjectIds = collect.values().stream()
                        .map(ActivityEvaluationRecord::getResourceId)
                        .filter(Objects::nonNull).distinct().collect(Collectors.toList());

                Map<Long, String> subjectNameMap = subjectService.findBySubjectByIdList(subjectIds).stream()
                        .collect(Collectors.toMap(Subject::getId, Subject::getName, (o, n) -> n));

                ActivityEvaluationRecord record;
                for (ActivityRegistrationVo item : activityUserInfos) {

                    if (collect.containsKey(item.getUserId())) {

                        record = collect.get(item.getUserId());
                        // 重置当前时间为用户最高排名时间
                        item.score(record.getScore())
                                .subjectName(subjectNameMap.getOrDefault(record.getResourceId(), ""))
                                .scoreTime(record.getCreateTime());

                    }
                }

            } else {

                // 单曲排名
                Map<Long, ActivityEvaluationRecord> collect = activityEvaluationRecordService.queryActivityUserHighestRankingInfo(query.getActivityId(), userIds).stream()
                        .collect(Collectors.toMap(ActivityEvaluationRecord::getUserId, Function.identity(), (o, n) -> n));

                ActivityEvaluationRecord record;
                for (ActivityRegistrationVo item : activityUserInfos) {

                    if (collect.containsKey(item.getUserId())) {

                        record = collect.get(item.getUserId());
                        // 重置当前时间为用户最高排名时间
                        item.score(record.getScore())
                                .times(record.getTimes())
                                .setCreateTime(record.getCreateTime());
                    }
                }
            }
        }

        return page.setRecords(activityUserInfos);
    }

    @Override
    public YesOrNoEnum getRegistration(Long userId, Long activityId) {
        Integer count = this.lambdaQuery()
                            .eq(ActivityRegistration::getUserId, userId)
                            .eq(ActivityRegistration::getActivityId, activityId)
                            .count();
        return count>0? YesOrNoEnum.YES:YesOrNoEnum.NO;

    }

}