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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.enums.CourseAdjustTypeEnum;
import com.xjrsoft.common.enums.EnabledMark;
import com.xjrsoft.module.courseTable.entity.CourseTable;
import com.xjrsoft.module.courseTable.service.ICourseTableService;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.room.entity.RoomBed;
import com.xjrsoft.module.schedule.dto.WfCourseAdjustDto;
import com.xjrsoft.module.schedule.entity.CourseTableBak;
import com.xjrsoft.module.schedule.entity.WfCourseAdjust;
import com.xjrsoft.module.schedule.mapper.WfCourseAdjustMapper;
import com.xjrsoft.module.schedule.service.ICourseTableBakService;
import com.xjrsoft.module.schedule.service.IWfCourseAdjustService;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @Author dzx
* @Date: 2024-02-03
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class WfCourseAdjustServiceImpl extends MPJBaseServiceImpl<WfCourseAdjustMapper, WfCourseAdjust> implements IWfCourseAdjustService {
    
    private final ICourseTableBakService courseTableBakService;
    private final ICourseTableService courseTableService;
    private final IUserService userService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancel(WfCourseAdjustDto dto) {
        WfCourseAdjust courseAdjust = this.getById(dto.getId());
        
        //查询出备份数据
        List<CourseTableBak> bakList = courseTableBakService.list(
                new QueryWrapper<CourseTableBak>().lambda()
                        .eq(CourseTableBak::getWfCourseAdjustId, dto.getId())
        );
        Map<Long, CourseTableBak> bakMap = new HashMap<>();
        for (CourseTableBak courseTableBak : bakList) {
            bakMap.put(courseTableBak.getId(), courseTableBak);
        }
        List<Long> courseIds = bakList.stream().map(CourseTableBak::getId).collect(Collectors.toList());
        if(!courseIds.isEmpty()){
            List<CourseTable> list = courseTableService.listByIds(courseIds);
            if(CourseAdjustTypeEnum.courseSubstitute.getCode().equals(courseAdjust.getAdjustType())){//顶课
                for (CourseTable courseTable : list) {
                    CourseTableBak tableBak = bakMap.get(courseTable.getId());
                    if(tableBak == null){
                        continue;
                    }
                    UpdateWrapper<CourseTable> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", courseTable.getId());
                    updateWrapper.setSql("adjust_type = null");
                    updateWrapper.setSql("teacher_id = '" + tableBak.getTeacherId() + "'");
                    updateWrapper.setSql("teacher_name = '" + tableBak.getTeacherName() + "'");
                    courseTableService.update(courseTable, updateWrapper);
                }
            }else if(CourseAdjustTypeEnum.courseExchange.getCode().equals(courseAdjust.getAdjustType())){
                for (CourseTable courseTable : list) {
                    CourseTableBak tableBak = bakMap.get(courseTable.getId());
                    if(tableBak == null){
                        continue;
                    }
                    UpdateWrapper<CourseTable> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", courseTable.getId());
                    updateWrapper.setSql("adjust_type = null");
                    updateWrapper.setSql("teacher_id = '" + tableBak.getTeacherId() + "'");
                    updateWrapper.setSql("teacher_name = '" + tableBak.getTeacherName() + "'");
                    updateWrapper.setSql("schedule_date = '" + tableBak.getScheduleDate() + "'");
                    updateWrapper.setSql("time_period = " + tableBak.getTimePeriod());
                    updateWrapper.setSql("time_number = " + tableBak.getTimeNumber());
                    updateWrapper.setSql("weeks = '" + tableBak.getWeeks() + "'");
                    updateWrapper.setSql("weeks_cn = '" + tableBak.getWeeksCn() + "'");
                    updateWrapper.setSql("course_id = " + tableBak.getCourseId());
                    updateWrapper.setSql("course_name = '" + tableBak.getCourseName() + "'");
                    courseTableService.update(courseTable, updateWrapper);
                }
            }
        }

        courseAdjust.setEnabledMark(EnabledMark.DISABLED.getCode());
        courseAdjust.setModifyDate(new Date());
        User user = userService.getById(StpUtil.getLoginIdAsLong());
        courseAdjust.setCancelReason("被" + user.getName() + "作废");
        this.updateById(courseAdjust);
        return true;
    }

    @Override
    public void backupsData(Long id) {
        try {
            WfCourseAdjust courseAdjust = this.getById(id);
            List<CourseTableBak> insertList = new ArrayList<>();
            if(CourseAdjustTypeEnum.courseSubstitute.getCode().equals(courseAdjust.getAdjustType())){//顶课
                String[] courseIds = courseAdjust.getCourseId().split(",");
                List<CourseTable> list = courseTableService.listByIds(Arrays.asList(courseIds));
                for (CourseTable courseTable : list) {
                    CourseTableBak tableBak = BeanUtil.toBean(courseTable, CourseTableBak.class);
                    tableBak.setWfCourseAdjustId(id);
                    insertList.add(tableBak);
                }
            }else if(CourseAdjustTypeEnum.courseExchange.getCode().equals(courseAdjust.getAdjustType())){
                List<String> ids = new ArrayList<>();
                String[] courseIds = courseAdjust.getCourseId().split(",");
                ids.addAll(Arrays.asList(courseIds));

                String[] exchangeCourseIds = courseAdjust.getExchangeCourseId().split(",");
                ids.addAll(Arrays.asList(exchangeCourseIds));

                List<CourseTable> list = courseTableService.listByIds(ids);
                for (CourseTable courseTable : list) {
                    CourseTableBak tableBak = BeanUtil.toBean(courseTable, CourseTableBak.class);
                    tableBak.setWfCourseAdjustId(id);
                    insertList.add(tableBak);
                }
            }

            if(!insertList.isEmpty()){
                courseTableBakService.saveBatch(insertList);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
