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

import cn.teammodel.common.PK;
import cn.teammodel.controller.admin.service.CommonService;
import cn.teammodel.model.dto.admin.common.CommentDto;
import cn.teammodel.model.dto.admin.common.GCDto;
import cn.teammodel.model.entity.common.Comment;
import cn.teammodel.model.entity.school.ClassInfo;
import cn.teammodel.model.entity.school.School;
import cn.teammodel.model.vo.admin.GradeAndClassVo;
import cn.teammodel.repository.ClassRepository;
import cn.teammodel.repository.CommentRepository;
import cn.teammodel.repository.SchoolRepository;
import cn.teammodel.utils.MonthToNumberConverter;
import com.azure.cosmos.models.PartitionKey;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

import static java.time.LocalDate.now;

@Service
public class CommonServiceImpl implements CommonService {
    @Resource
    private SchoolRepository schoolRepository;
    @Resource
    private ClassRepository classRepository;
    @Resource
    private CommentRepository commentRepository;

    @Override
    public List<GradeAndClassVo> getGradeAndClass(GCDto gcDto) {
        List<GradeAndClassVo> gradeAndClassVos = new ArrayList<>();
        try {
            //获取当前学校该学段下详细信息
            List<School.Period> period = schoolRepository.findPeriodById(gcDto.getSchoolId(), gcDto.getPeriodId());
            List<ClassInfo> classes = classRepository.findClassBySchoolIdAndPeriodId(gcDto.getPeriodId(), String.format(PK.CLASS, gcDto.getSchoolId()));
            int year;
            int mon;
            int day;
            if (gcDto.getTime() != null && gcDto.getTime() != 0L) {
                LocalDate date = Instant.ofEpochMilli(gcDto.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
                year = date.getYear();
                mon = date.getMonthValue();
                day = date.getDayOfMonth();
            }else {
                year = now().getYear();
                Month month =   now().getMonth();
                mon =  MonthToNumberConverter.convertMonthToNumber(month.name());
                day = now().getDayOfMonth();
            }
            //处理年级ID
            for (ClassInfo classInfo : classes) {
                if(period.get(0).getId().equalsIgnoreCase(classInfo.getPeriodId())) {
                    for (School.Semester semester : period.get(0).getSemesters()) {
                        int time;
                        if(semester.getStart() == 1) {
                            if (mon == semester.getMonth())
                            {
                                time = day >= semester.getDay() ? 0 : 1;
                            }
                            else
                            {
                                time = mon > semester.getMonth() ? 0 : 1;
                            }
                            int eYear = year - time;
                            classInfo.setGrade(eYear- classInfo.getYear());
                        }
                    }

                }
            }
            List<String> grades = period.get(0).getGrades();
            int index = 0;
            //根据当前时间去判定各个年级的入学年
            int time = 0;
            if(period.get(0).getId().equalsIgnoreCase(gcDto.getPeriodId())) {
                for (School.Semester semester : period.get(0).getSemesters()) {
                    if(semester.getStart() == 1) {
                        if (mon == semester.getMonth())
                        {
                            time = day >= semester.getDay() ? 0 : 1;
                        }
                        else
                        {
                            time = mon > semester.getMonth() ? 0 : 1;
                        }
                    }
                }

            }
            for (String grade : grades) {
                GradeAndClassVo gradeAndClassVo = new GradeAndClassVo();
                gradeAndClassVo.setGradeId(index);
                gradeAndClassVo.setYear(year - time - index);
                gradeAndClassVo.setGradeName(grade);
                classes.stream().filter(classInfo -> classInfo.getGrade() == gradeAndClassVo.getGradeId()).forEach(classInfo -> {
                    GradeAndClassVo.CI ci = new GradeAndClassVo.CI();
                    ci.setClassId(classInfo.getId());
                    ci.setClassName(classInfo.getName());
                    ci.setYear(classInfo.getYear());
                    gradeAndClassVo.AddClass(ci);
                });
                index ++;
                gradeAndClassVos.add(gradeAndClassVo);
            }

            return gradeAndClassVos;
        }catch (Exception e) {

            throw new RuntimeException("获取当前学校当前学段年级班级信息失败" + e);
        }
    }

    @Override
    public Comment saveOrUpdateComment(Comment comment) {

        String formattedString = String.format("Comment-%s-%s-%s",
                comment.getSchool(),
                comment.getYear(),
                comment.getSemester());
        List<Comment> comments = commentRepository.findById(comment.getId(),comment.getSchool(),comment.getActivityType(),formattedString);
        Comment existingComment = comments.stream().findFirst().orElse(null);
        if (existingComment != null) {
            // 如果评论对象存在，则进行更新操作
            // 这里你可以根据需要更新评论对象的属性
            existingComment.setContentInfo(comment.getContentInfo());
            existingComment.setUpdateTime(Instant.now().toEpochMilli());

            //commentRepository.deleteById(existingComment.getId(),new PartitionKey(existingComment.getSchool()));
            // 最后保存更新后的评论对象
            return commentRepository.save(existingComment);
        } else {
            // 如果评论对象不存在，则创建新的记录

            comment.setCode(formattedString);
            comment.setCreateTime(Instant.now().toEpochMilli());
            return commentRepository.save(comment);
        }
    }

    @Override
    public List<String> deleteComment(CommentDto comment) {
        for (String id : comment.getIds()) {
            commentRepository.deleteById(id,new PartitionKey(comment.getCode()));
        }
        return comment.getIds();
    }

    @Override
    public List<Comment> getCommentById(Comment comment) {
        String formattedString = String.format("Comment-%s-%s-%s",
                comment.getSchool(),
                comment.getYear(),
                comment.getSemester());
        return commentRepository.findById(comment.getId(),comment.getSchool(),comment.getActivityType(),formattedString);
    }
}
