package cn.teammodel.controller.admin.service.impl;

import cn.teammodel.common.ErrorCode;
import cn.teammodel.config.exception.ServiceException;
import cn.teammodel.controller.admin.service.ArtService;
import cn.teammodel.model.dto.admin.art.ArtAnalysisDto;
import cn.teammodel.model.dto.admin.art.ArtFindDto;
import cn.teammodel.model.dto.admin.art.DataFileCommentDto;
import cn.teammodel.model.dto.admin.art.DataFileDto;
import cn.teammodel.model.dto.admin.common.GroupDto;
import cn.teammodel.model.dto.admin.common.RGroupList;
import cn.teammodel.model.dto.admin.common.RMember;
import cn.teammodel.model.vo.admin.ArtElementsVo;
import cn.teammodel.model.vo.admin.DataFileVo;
import cn.teammodel.repository.ArtRepository;
import cn.teammodel.utils.GroupUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
@Service
public class ArtServiceImpl implements ArtService {
    @Resource
    private ArtRepository artRepository;
    @Autowired
    private Environment env;
    @Override
    public List<ArtElementsVo> getArtList(ArtFindDto artFindDto, HttpServletRequest request) {
        List<ArtElementsVo> artElementsVos = artRepository.findPeriodById(artFindDto.getPeriodId(),"Art-"+ artFindDto.getCode(), artFindDto.getStartTime(), artFindDto.getEndTime());
        List<String> classIds = artElementsVos.stream()
                .map(ArtElementsVo::getClasses) // 正确的方法引用
                .flatMap(List::stream) // 将内部列表扁平化
                .collect(Collectors.toList());
        GroupDto groupDto = new GroupDto();
        groupDto.setIds(classIds);
        groupDto.setSchoolId(artFindDto.getCode());
        String url = env.getProperty("ies.server-url-group");
        //List<ClassInfo> classes = classRepository.findAllByCodeAndIdIn("Class-"+artFindDto.getCode(),classIds);
        Map<String, Object> groupId =  GroupUtil.getGroupId(groupDto,new GroupUtil(env), request,url);
        List<RGroupList> rGroupList = new ArrayList<>();
        List<RMember> rMembers = new ArrayList<>();
        for (Map.Entry<String, Object> entry : groupId.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key.equals("groups")) {
                String jsonGroups = JSON.toJSONString(value);
                rGroupList = JSON.parseObject(jsonGroups, new TypeReference<List<RGroupList>>() {});
            }
            if (key.equals("members")) {
                String jsonGroups = JSON.toJSONString(value);
                rMembers = JSON.parseObject(jsonGroups, new TypeReference<List<RMember>>() {});
            }
        }
        try {
            for (ArtElementsVo artElementsVo : artElementsVos) {
                List<String> classes1 = artElementsVo.getClasses();
                int stuInClassCount = 0;
                for(String classId : classes1) {
                    stuInClassCount += (int) rMembers.stream().filter(rMember -> rMember.getClassId().equals(classId)).count();
                    //stuInClassCount += studentRepository.countByClassIdAndCode(classId, String.format(PK.STUDENT, artFindDto.getCode()));
                    ArtElementsVo.ClassInfos classInfos = new ArtElementsVo.ClassInfos();
                    rGroupList.stream().filter(rGroupList1 -> rGroupList1.getId().equals(classId)).findFirst().ifPresent(rGroupList1 -> {
                        classInfos.setId(rGroupList1.getId());
                        classInfos.setName(rGroupList1.getName());
                    });
                    artElementsVo.addClassesInfos(classInfos);
                }
                artElementsVo.setCount(stuInClassCount);

            }
        } catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");
        }
        return artElementsVos;
    }

    @Override
    public List<RGroupList> getGroupList(GroupDto groupDto, HttpServletRequest request) {
        List<RGroupList> rGroupList = new ArrayList<>();
        String url = env.getProperty("ies.server-url-group");
        try {
            Map<String, Object> groupId =  GroupUtil.getGroupId(groupDto,new GroupUtil(env), request,url);
            //List<RMember> rMembers = new ArrayList<>();
            for (Map.Entry<String, Object> entry : groupId.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (key.equals("groups")) {
                    String jsonGroups = JSON.toJSONString(value);
                    rGroupList = JSON.parseObject(jsonGroups, new TypeReference<List<RGroupList>>() {});
                }
            }

        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return rGroupList;
    }

    @Override
    public List<DataFileVo> getPdfData(DataFileDto dataFileDto,HttpServletRequest request) {
        List<DataFileVo> dataFile = new ArrayList<>();
        String url = env.getProperty("ies.server-url-pdf-data");
        try {
            Map<String, Object> groupId =  GroupUtil.getGroupId(dataFileDto,new GroupUtil(env), request,url);
            //List<RMember> rMembers = new ArrayList<>();
            for (Map.Entry<String, Object> entry : groupId.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (key.equals("dataFiles")) {
                    String jsonGroups = JSON.toJSONString(value);
                    dataFile = JSON.parseObject(jsonGroups, new TypeReference<List<DataFileVo>>() {});
                }
            }
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return dataFile;
    }

    @Override
    public List<DataFileVo> updateComment(DataFileCommentDto dataFileCommentDto, HttpServletRequest request) {
        List<DataFileVo> dataFile = new ArrayList<>();
        String url = env.getProperty("ies.server-url-update-custom-comment");
        try {
            Map<String, Object> groupId =  GroupUtil.getGroupId(dataFileCommentDto,new GroupUtil(env), request,url);
            //List<RMember> rMembers = new ArrayList<>();
            for (Map.Entry<String, Object> entry : groupId.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (key.equals("dataFile")) {
                    String jsonGroups = JSON.toJSONString(value);
                    dataFile = JSON.parseObject(jsonGroups, new TypeReference<List<DataFileVo>>() {});
                }
            }
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return dataFile;
    }

    @Override
    public Map<String, Object> getArtAnalytics(ArtAnalysisDto artAnalysisDto, HttpServletRequest request) {
        Map<String, Object> analysis;
        String url = env.getProperty("ies.server-url-art-analysis");
        try {
            analysis =  GroupUtil.getGroupId(artAnalysisDto,new GroupUtil(env), request,url);
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return analysis;
    }
}
