package com.xjrsoft.module.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.module.base.dto.BaseClassCoursePageDto;
import com.xjrsoft.module.base.dto.ClassCourseReuseDto;
import com.xjrsoft.module.base.entity.BaseClassCourse;
import com.xjrsoft.module.base.entity.ClassCourseTextbook;
import com.xjrsoft.module.base.entity.CourseBookInfo;
import com.xjrsoft.module.base.mapper.BaseClassCourseMapper;
import com.xjrsoft.module.base.service.IBaseClassCourseService;
import com.xjrsoft.module.base.vo.BaseClassCoursePageVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
* @title: 班级课程
* @Author brealinxx
* @Date: 2024-06-04
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class BaseClassCourseServiceImpl extends MPJBaseServiceImpl<BaseClassCourseMapper, BaseClassCourse> implements IBaseClassCourseService {
    private final BaseClassCourseMapper baseClassCourseMapper;

    @Override
    public Page<BaseClassCoursePageVo> getPage(Page<BaseClassCoursePageVo> page, BaseClassCoursePageDto dto) {
        return baseClassCourseMapper.getPage(page, dto);
    }

    @Override
    public List<CourseBookInfo> getAllCourseBook(Long[] classIds, Long subjectGroupId, Long semester){
        return baseClassCourseMapper.getAllCourseBook(classIds, subjectGroupId, semester);
    }

    @Override
    public List<CourseBookInfo> getSelectedCourseBook(Long[] subjectGroupId, Long semester){
        return baseClassCourseMapper.getSelectedCourseBook(subjectGroupId, semester);
    }

    @Override
    @Transactional
    public Boolean updateAddCourseBook(ClassCourseTextbook dto){
        if (dto.getClassIds() == null || dto.getClassIds().length == 0 || dto.getBaseSemesterId() == null || dto.getBaseSemesterId() == 0) {
            return false;
        }

        boolean isSuccess = false;

        List<Long> classIdList = Arrays.asList(dto.getClassIds());
        //删除班级的这学期的所有课程教材
        LambdaQueryWrapper<BaseClassCourse> baseClassCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseClassCourseLambdaQueryWrapper
                .in(BaseClassCourse::getClassId, classIdList)
                .eq(BaseClassCourse::getBaseSemesterId, dto.getBaseSemesterId())
        ;
        isSuccess = this.remove(baseClassCourseLambdaQueryWrapper);

        List<BaseClassCourse> baseClassCourseList = new ArrayList<>();
        for (Long classId : dto.getClassIds()){
            for (String id : dto.getIds()){
                String[] idArr = id.split("_");
                if(idArr[0].equals("") || idArr[1].equals("")){
                    continue;
                }
                Long courseId = Long.parseLong(idArr[0]);
                Long textbookId = Long.parseLong(idArr[1]);
                baseClassCourseList.add(new BaseClassCourse(){{
                    setBaseSemesterId(dto.getBaseSemesterId());
                    setClassId(classId);
                    setCourseId(courseId);
                    setTextbookId(textbookId);
                }});
            }
        }

        isSuccess = this.saveBatch(baseClassCourseList);

        return isSuccess;
        //baseClassCourseMapper.updateAddClassCourseTextbooks(classId, courseId, textbookId);
    }

    @Override
    public void updateRemoveCourseBook(Long classId, Long courseId, Long textbookId){
        baseClassCourseMapper.updateRemoveClassCourseTextbooks(classId, courseId, textbookId);
    }

    @Override
    public void markExistingRecordsAsDeleted(Long newClassId, Long sourceClassId){
        baseClassCourseMapper.markExistingRecordsAsDeleted(newClassId, sourceClassId);
    }

    @Override
    @Transactional
    public Boolean duplicateCourseBook(ClassCourseReuseDto dto){
        LambdaQueryWrapper<BaseClassCourse> baseClassCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseClassCourseLambdaQueryWrapper
                .eq(dto.getOldClassId() != null && dto.getOldClassId() > 0, BaseClassCourse::getClassId, dto.getOldClassId())
                .eq(dto.getOldBaseSemesterId() != null && dto.getOldBaseSemesterId() > 0, BaseClassCourse::getBaseSemesterId, dto.getOldBaseSemesterId())
                ;
        List<BaseClassCourse> baseClassCourseList = this.list(baseClassCourseLambdaQueryWrapper);
        if(baseClassCourseList == null || baseClassCourseList.isEmpty()){
            throw new MyException("该学期的该班级没有可以复用的课程！");
        }

        boolean isSuccess = false;

        //删除班级的所有课程教材
        LambdaQueryWrapper<BaseClassCourse> removeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        removeLambdaQueryWrapper
                .in(BaseClassCourse::getClassId, dto.getNewClassIds())
                .eq(BaseClassCourse::getBaseSemesterId, dto.getNewBaseSemesterId())
        ;
        isSuccess = this.remove(removeLambdaQueryWrapper);

        List<BaseClassCourse> newBaseClassCourseList = new ArrayList<>();
        for (Long newClassId : dto.getNewClassIds()){
            for (BaseClassCourse baseClassCourse : baseClassCourseList){
                Long courseId = baseClassCourse.getCourseId();
                Long textbookId = baseClassCourse.getTextbookId();
                newBaseClassCourseList.add(new BaseClassCourse(){{
                    setBaseSemesterId(dto.getNewBaseSemesterId());
                    setClassId(newClassId);
                    setCourseId(courseId);
                    setTextbookId(textbookId);
                }});
            }
        }

        isSuccess = this.saveBatch(newBaseClassCourseList);
        return isSuccess;
        //baseClassCourseMapper.insertClassCourseTextbookCombinations(newClassId, sourceClassId, semester);
    }

    @Override
    public Map<String, Map<String, Object>> getSemesterTree() {
        List<Map<String, Object>> semesterData = baseClassCourseMapper.getAllSemesterNames();

        Map<String, Map<String, Object>> tree = new TreeMap<>();

        for (Map<String, Object> data : semesterData) {
            String name = (String) data.get("name");
            String[] parts = name.split("年");
            String year = parts[0]; // 年份
            String semesterType = parts[1].substring(0, parts[1].length() - 1); // 学期类型(春期/秋期)
            Long id = Long.parseLong(data.get("id").toString());

            if (!tree.containsKey(year + "年")) {
                tree.put(year + "年", new HashMap<>());
            }

            Map<String, Object> yearMap = tree.get(year + "年");

            if (semesterType.equals("春")) {
                yearMap.put("springName", name);
                yearMap.put("springId", id);
            } else if (semesterType.equals("秋")) {
                yearMap.put("autumnName", name);
                yearMap.put("autumnId", id);
            }
        }

        return tree;
    }

    @Override
    public Long GetClassIdByName(String name){
        return baseClassCourseMapper.getClassIdByName(name);
    }

    @Override
    public Long GetCourseIdByName(String name){
        return baseClassCourseMapper.getCourseIdByName(name);
    }

    @Override
    public Long GetTextbookIdByName(String name){
        return baseClassCourseMapper.getBookIdByName(name);
    }

    @Override
    public Long GetBaseSemesterIdByName(String name) {
        return baseClassCourseMapper.getBaseSemesterIdByName(name);
    }

    @Override
    public boolean checkExits(Long classId,Long courseId,Long textbookId){
        return baseClassCourseMapper.checkExits(classId, courseId, textbookId);
    }

    @Override
    public boolean checkExitsWithoutTextbook(Long classId, Long courseId) {
        return this.baseMapper.checkExitsWithoutTextbook(classId, courseId);
    }
}
