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

import com.dayaedu.cbs.openfeign.service.CbsSubjectService;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsSubjectApiWrapper;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.service.SubjectService;
import com.yonge.cooleshow.biz.dal.wrapper.SubjectWrapper;
import com.yonge.toolset.base.page.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CbsSubjectServiceImpl implements CbsSubjectService {

    private static final Logger log = LoggerFactory.getLogger(CbsSubjectServiceImpl.class);

    @Resource
    private SubjectService subjectService;

    public Boolean checkSubjectEnable(CbsSubjectApiWrapper.CheckSubjectDto checkSubjectDto) {
        Subject subject = subjectService.getDao().getByCbsId(checkSubjectDto.getSubjectId());
        if (subject != null){
            return true;
        }
        return false;
    }

    public List<CbsSubjectApiWrapper.Subject> list(CbsSubjectApiWrapper.SubjectQuery query) {
        SubjectWrapper.SubjectQuery subjectQuery = new SubjectWrapper.SubjectQuery();
        subjectQuery.setPage(1);
        subjectQuery.setRows(999);
        subjectQuery.setEnableFlag(query.getEnable());
        List<Long> subjectIds = query.getSubjectIds();
        if (CollectionUtils.isNotEmpty(subjectIds)) {
            subjectQuery.setSubjectIds(subjectIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
        }
        PageInfo<SubjectWrapper.Subject> subjectPageInfo = subjectService.selectPage(subjectQuery);
        Map<Long, String> cbsSubjectIdNameMap = subjectPageInfo.getRows().stream()
            .filter(Objects::nonNull)
            .filter(subject -> subject.getCbsSubjectId() != null && subject.getName() != null)
            .collect(Collectors.toMap(SubjectWrapper.Subject::getCbsSubjectId, SubjectWrapper.Subject::getName));
        List<CbsSubjectApiWrapper.Subject> subjects = subjectService.getDao().queryCbsList(query);
        for (CbsSubjectApiWrapper.Subject subject : subjects) {
            Long cbsSubjectId = subject.getCbsSubjectId();
            if (cbsSubjectIdNameMap.containsKey(cbsSubjectId)) {
                subject.setSubjectName(cbsSubjectIdNameMap.get(cbsSubjectId));
            }
        }
        return subjects;
    }
}