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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.enums.CourseAdjustTypeEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.module.classtime.dto.AddClassTimeCalendarDto;
import com.xjrsoft.module.classtime.entity.ClassTimeCalendar;
import com.xjrsoft.module.classtime.mapper.ClassTimeCalendarMapper;
import com.xjrsoft.module.classtime.service.IClassTimeCalendarService;
import com.xjrsoft.module.courseTable.entity.CourseTable;
import com.xjrsoft.module.courseTable.service.ICourseTableService;
import com.xjrsoft.module.schedule.entity.CourseTableBak;
import com.xjrsoft.module.schedule.service.ICourseTableBakService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @title: 节假日调课设置
* @Author dzx
* @Date: 2024-09-26
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class ClassTimeCalendarServiceImpl extends MPJBaseServiceImpl<ClassTimeCalendarMapper, ClassTimeCalendar> implements IClassTimeCalendarService {
    private final ICourseTableService courseTableService;
    private final ICourseTableBakService courseTableBakService;

    @Override
    public Boolean add(AddClassTimeCalendarDto dto) {
        try {
            ClassTimeCalendar classTimeCalendar = BeanUtil.toBean(dto, ClassTimeCalendar.class);

            //1、查询补课日期的数据，将日期设置为补班日期然后新增
            List<CourseTable> list = courseTableService.list(
                    new QueryWrapper<CourseTable>().lambda()
                            .eq(CourseTable::getScheduleDate, dto.getReplaceDate())
                            .in(CourseTable::getTimeNumber, Arrays.asList(dto.getTimePeriod().split(",")))
            );
            if(list.isEmpty()){
                throw new MyException("未能查询到补课日期那天的课表信息，请联系管理员");
            }

            //2、删除补班日期的课表数据，包括调课和顶课，并肩删除的数据进行备份
            List<CourseTable> deleteList = courseTableService.list(
                    new QueryWrapper<CourseTable>().lambda()
                            .eq(CourseTable::getScheduleDate, dto.getSupplementDate())
                            .in(dto.getCoverType() == 1, CourseTable::getTimeNumber, Arrays.asList(dto.getTimePeriod().split(",")))
            );
            List<CourseTableBak> bakList = new ArrayList<>();
            for (CourseTable courseTable : deleteList) {
                CourseTableBak tableBak = BeanUtil.toBean(courseTable, CourseTableBak.class);
                tableBak.setWfCourseAdjustId(classTimeCalendar.getId());
                bakList.add(tableBak);
            }
            courseTableBakService.saveBatch(bakList);

            courseTableService.removeBatchByIds(deleteList.stream().map(CourseTable::getId).collect(Collectors.toList()));

            //3、将补课日期的数据查询出来，将日期改为补班日期进行新增
            List<CourseTable> insertList = new ArrayList<>();
            for (CourseTable courseTable : list) {
                courseTable.setId(null);
                courseTable.setWeeks(getNumberDayOfWeek(dto.getSupplementDate().getDayOfWeek()));
                courseTable.setWeeksCn(getChineseDayOfWeek(dto.getSupplementDate().getDayOfWeek()));
                courseTable.setScheduleDate(dto.getSupplementDate());
                courseTable.setAdjustType(CourseAdjustTypeEnum.courseReplace.getCode());
                insertList.add(courseTable);
            }

            courseTableService.saveBatch(insertList);

            classTimeCalendar.setCreateDate(new Date());
            boolean isSuccess = this.save(classTimeCalendar);
            return isSuccess;
        }catch (Exception e){
            log.error(e.getMessage(), e);
            if(e.getClass().equals(MyException.class)){
                throw new MyException(e.getMessage());
            }else{
                throw new MyException("添加出错，请联系管理员");
            }
        }
    }

    String getChineseDayOfWeek(DayOfWeek dayOfWeek) {
        switch (dayOfWeek) {
            case MONDAY:
                return "星期一";
            case TUESDAY:
                return "星期二";
            case WEDNESDAY:
                return "星期三";
            case THURSDAY:
                return "星期四";
            case FRIDAY:
                return "星期五";
            case SATURDAY:
                return "星期六";
            case SUNDAY:
                return "星期天";
            default:
                return "";
        }
    }
    Integer getNumberDayOfWeek(DayOfWeek dayOfWeek) {
        switch (dayOfWeek) {
            case MONDAY:
                return 1;
            case TUESDAY:
                return 2;
            case WEDNESDAY:
                return 3;
            case THURSDAY:
                return 4;
            case FRIDAY:
                return 5;
            case SATURDAY:
                return 6;
            case SUNDAY:
                return 7;
            default:
                return null;
        }
    }

    @Override
    public Boolean cancel(Long id) {
        try{
            ClassTimeCalendar calendar = this.getById(id);
            //1、作废后，删除新增的补班课表数据
            courseTableService.remove(
                    new QueryWrapper<CourseTable>().lambda()
                            .eq(CourseTable::getScheduleDate, calendar.getSupplementDate())
                            .eq(CourseTable::getAdjustType, CourseAdjustTypeEnum.courseReplace.getCode())
            );
            //查询出来备份的数据，并恢复到课表中
            List<CourseTableBak> list = courseTableBakService.list(
                    new QueryWrapper<CourseTableBak>().lambda()
                            .eq(CourseTableBak::getWfCourseAdjustId, calendar.getId())
            );
            List<CourseTable> insertList = new ArrayList<>();
            for (CourseTableBak courseTable : list) {
                CourseTable table = BeanUtil.toBean(courseTable, CourseTable.class);
                insertList.add(table);
            }

            courseTableService.saveBatch(insertList);

            calendar.setStatus(2);
            calendar.setModifyDate(new Date());
            return this.updateById(calendar);
        }catch (Exception e){
            log.error(e.getMessage(), e);
            if(e.getClass().equals(MyException.class)){
                throw new MyException(e.getMessage());
            }else{
                throw new MyException("添加出错，请联系管理员");
            }
        }
    }
}
