package yangtz.cs.liu.campus.controller.time;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.time.SchoolSchedule;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassService;
import yangtz.cs.liu.campus.service.time.ISchoolTimeTableService;
import yangtz.cs.liu.campus.domain.time.SchoolTimeTable;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;
import yangtz.cs.liu.campus.vo.time.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static yangtz.cs.liu.campus.constant.EmployeeType.EMPLOYEE;

/**
 * 学校时间表
 */
@RestController
@RequestMapping("/schoolTimeTable")
public class SchoolTimeTableController extends BaseController {

    @Autowired
    private ISchoolTimeTableService schoolTimeTableService;

    @Autowired
    private ISchoolClassService schoolClassService;

    /**
     * 新增班级课程表
     * @author yang
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated List<SchoolTimeTable> list) {
        if(StringUtils.isNull(list)){
            throw new ServiceException("课表为空");
        }
        for(SchoolTimeTable schoolTimeTable : list){
            if(StringUtils.isNull(schoolTimeTable.getId())){  //id为空表示新增
                schoolTimeTableService.save(schoolTimeTable);
            }else {
                schoolTimeTableService.updateById(schoolTimeTable); //id存在表示修改
            }

        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 删除课程
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@PathVariable("ids") List<Long> ids) {
        return toAjax(schoolTimeTableService.removeByIds(ids));
    }

    /**
     * 查询单个课程详情
     * @param id
     * @return
     */
    @GetMapping("/queryOne/{id}")
    public AjaxResult queryOne(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolTimeTableService.getById(id));
    }

    /**
     * 查询 课程表管理&班主任课程表
     * @param schoolTimeTable
     * 班级id 学期
     * @return
     */
    @GetMapping("/getSchoolSchedule")
    public TableDataInfo getSchoolSchedule(SchoolTimeTable schoolTimeTable) {
        if(StringUtils.isNull(schoolTimeTable.getClassId())){
            //throw new ServiceException("未选择班级");
            return getDataTable(new ArrayList<>());
        }
        if(StringUtils.isNull(schoolTimeTable.getTermId())){
            throw new ServiceException("未选择学期");
        }

        List<TableVO> list = schoolTimeTableService.selectSchoolSchedule(schoolTimeTable);
        return getDataTable(list);
    }

    /**
     *  课程表管理新增或修改
     * 班级id 学期
     * @return
     */
    @PostMapping("/addSchoolSchedule/{classId}/{termId}")
    public AjaxResult addSchoolSchedule(@RequestBody List<TableVO> list,
                                           @PathVariable("classId") Long classId,
                                           @PathVariable("termId") Integer termId) {
        return toAjax(schoolTimeTableService.addSchoolSchedule(list,classId,termId));
    }


    /**
     * 课程表导出excel
     * @author yang
     */
   @PostMapping("/exportSchedule")
    public Boolean exportSchedule(@RequestBody List<ScheduleVo> list,@Validated String path) {
       return schoolTimeTableService.exportSchedule(list,path);
    }

    //导出excel
    @PostMapping("/exportTable/{classId}/{termId}")
    public void exportTable(HttpServletResponse response,
                            @PathVariable("classId") Long classId,
                            @PathVariable("termId") Integer termId) {
        List<ExportScheduleVo> list = schoolTimeTableService.exportTable(classId,termId);
        ExcelUtil<ExportScheduleVo> util = new ExcelUtil<>(ExportScheduleVo.class);
        util.exportExcel(response, list, "课程表");
    }

    /**
     * 课表导入
     */
    @PostMapping("/importTable/{classId}/{termId}")
    public AjaxResult importTable(MultipartFile file,@PathVariable("classId") Long classId,
                                  @PathVariable("termId") Integer termId) throws Exception {
        ExcelUtil<ExportScheduleVo> util = new ExcelUtil<ExportScheduleVo>(ExportScheduleVo.class);
        List<ExportScheduleVo> list = util.importExcel(file.getInputStream());
        //先校验
        schoolTimeTableService.checkImport(list);
        //数据导入
        String message = schoolTimeTableService.importData(list,classId,termId);
        return AjaxResult.success(message);
    }

    /**
     * 课程表导入excel
     * @author yang
     */
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestPart SchoolTimeTable schoolTimeTable,MultipartFile file) throws Exception {
//        ExcelUtil<ScheduleVo> util = new ExcelUtil<ScheduleVo>(ScheduleVo.class);
//        List<ScheduleVo> list = util.importExcel(file.getInputStream());
        //先校验
//        schoolTimeTableService.checkImport(list);
//        String message = schoolBudgetService.importSchoolBudgetVoList(list);
        return AjaxResult.success(schoolTimeTableService.importExcel(schoolTimeTable,file));
    }



    /**
     * 加载 单个班级列表
     */
    @GetMapping("/getSchoolClassById")
    @ResponseBody
    public SchoolClass getSchoolClassById(HttpServletRequest request) {
        Long id = Long.parseLong(request.getParameter("id"));
        SchoolClass schoolClass = schoolClassService.getById(id);
        return schoolClass;
    }

    /**
     * 加载 整个班级列表
     */
    @GetMapping("/getSchoolClassList")
    public List<SchoolClass> getSchoolClassList(SchoolClass schoolClass) {
        return schoolTimeTableService.getSchoolClassList(schoolClass);
    }

    /**
     * 获取个人工作，我的课程
     * @return
     */
    @GetMapping("/getMyTable")
    public TableDataInfo getMyTable(){
        Long teacherId = getUserId();
        //获取当前登录用户
        SysUser user = getLoginUser().getUser();
        if(user.getEmployeeType().equals(EMPLOYEE)){
            //throw new ServiceException("您的用户类型为职工，无法查询个人课表");
            return getDataTable(new ArrayList<>());
        }
        List<TableVO> list = schoolTimeTableService.getTeacherTable(teacherId);
        return getDataTable(list);
    }

//    /**
//     * 查询课程列表
//     * @param schoolTimeTable
//     * @return
//     */
//    @GetMapping("/list")
//    public TableDataInfo list(SchoolTimeTable schoolTimeTable) {
//        startPage();
//        List<SchoolCourseTableVO> list = schoolTimeTableService.selectSchoolTimeTableList(schoolTimeTable);
//        return getDataTable(list);
//    }


//    /**
//     * 保存课表
//     */
//    @PostMapping("/saveSchedule")
//    public AjaxResult saveSchedule(@RequestBody @Validated List<SchoolSchedule> list) {
//        if(StringUtils.isNull(list)){
//            throw new ServiceException("课表不能为空");
//        }
//        schoolTimeTableService.saveSchedule(list);
//        return AjaxResult.success();
//    }


//    /**
//     * 保存课程
//     */
//    @PostMapping("/save")
//    public AjaxResult save(List<SchoolTimeTable> list) {
//        if (StringUtils.isNull(list)) {
//            throw new BaseException("课表不能为空");
//        }
//
//        return toAjax(schoolTimeTableService.updateSchoolTimeTable(schoolTimeTable));
//    }

//    /**
//     * 制作 课程表
//     */
//    @PostMapping("/getCourseSchedule/{id}")
//    public AjaxResult getCourseSchedule(SchoolTimeTable schoolTimeTable ,@PathVariable("id") Long id) {
//        //如果classid 不存在就返回一个空课程表
//        SchoolClass schoolClass = schoolClassService.getById(id);
//        if(StringUtils.isNotNull(schoolClass)){
//            schoolTimeTable.setGradeId(schoolClass.getGradeId());
//            schoolTimeTable.setClassId(Long.valueOf(schoolClass.getClassValue()));
//        }
//        List<SchoolCourseSchedule> list = schoolTimeTableService.getCourseSchedule(schoolTimeTable);
//        return AjaxResult.success(list);
//    }

//    /**
//     * 加载班级树形列表
//     */
//    @GetMapping("/getClassTreeData")
//    @ResponseBody
//    public List<Ztree> getClassTreeData() {
//        List<Ztree> ztrees = schoolTimeTableService.selectSchoolClassListForTreeNew(new SchoolClass());
//        return ztrees;
//    }

//    /**
//     * 导入数据
//     */
//    @PostMapping("/importDataSchedule")
//    @ResponseBody
//    public AjaxResult importDataSchedule(MultipartFile file, boolean updateSupport, HttpServletRequest request) throws Exception
//    {
//        SchoolTimeTable schoolTimeTable = new SchoolTimeTable();
//        ExcelUtil<SchoolSchedule> util = new ExcelUtil<SchoolSchedule>(SchoolSchedule.class);
//        List<SchoolSchedule> list = util.importExcel(file.getInputStream());
//        String message = schoolTimeTableService.importExamDetailSchedule(list, updateSupport, schoolTimeTable);
//        return AjaxResult.success(message);
//    }

    /**
     * 制作课程表
     * @param data
     * @return
     */
    @PostMapping("/makeSchedule")
    public List<SchoolSchedule> getSchedule(@RequestBody OriginalData data) {

        ClassScheduling classScheduling = new ClassScheduling();
        Map<Integer, GradeInfo> gradeInfo = new HashMap<Integer, GradeInfo>();
        GradeInfo gi = null;
        List<SubjectInfo> subjectInfos = new ArrayList<SubjectInfo>();
        Map<Integer, ClassInfo> classInfos = new HashMap<Integer, ClassInfo>();
        gi = new GradeInfo(data.getGradeValue(), data.getGradeValue().toString(), data.getClassValue(), data.getWeekPerDay(), data.getDayPerLess(), data.getLessonAtAM(), data.getLessonAtPM(), data.getLessonAtAM() + data.getLessonAtPM());
        //课程代号shuxue,课程名称：数学,主副课1，课程节数5
        for (Integer i = 0; i < data.getSubjectToTeacherList().size(); i++) {
            SubjectToTeacher var = data.getSubjectToTeacherList().get(i);
            subjectInfos.add(new SubjectInfo(var.getCourseId(), var.getCourseName(), var.getAttributes(), var.getSubjectCount()));
        }
        gi.setSubjectInfos(subjectInfos);  //将年级的科目信息存放
        ClassInfo classInfo = new ClassInfo();
        classInfo.setClassName(data.getClassValue().toString());
        Map<SubjectInfo, String> subjectTeachers = new HashMap<SubjectInfo, String>();

        for (Integer i = 0; i < data.getSubjectToTeacherList().size(); i++) {
            SubjectToTeacher var = data.getSubjectToTeacherList().get(i);
            subjectTeachers.put(new SubjectInfo(var.getCourseId(), var.getCourseName(), var.getAttributes(), var.getSubjectCount()), var.getTeacherId().toString());
        }

        classInfo.setSubjectTeachers(subjectTeachers);
        classInfos.put(data.getClassValue(), classInfo);
        gi.setClassInfos(classInfos);
        gradeInfo.put(data.getGradeValue(), gi);
        //年级，班级for循环至此结束
        //获取指定位置的list
        List<FirstSubjectInfoVo> subjectInfoList = new ArrayList<>();
        for(SubjectToTeacher subject : data.getSubjectToTeacherList()){
            if(StringUtils.isNotNull(subject.getSubjectInfoList())){  //如果有指定位置
                for(SubjectInfoVo subjectInfoVo : subject.getSubjectInfoList()){  //指定位置循环
                    FirstSubjectInfoVo firstSubjectInfoVo = new FirstSubjectInfoVo();
                    firstSubjectInfoVo.setDay(subjectInfoVo.getDay());
                    firstSubjectInfoVo.setNumber(subjectInfoVo.getNumber());
                    firstSubjectInfoVo.setFlag(subjectInfoVo.getFlag());
                    firstSubjectInfoVo.setSubjectInfo(new SubjectInfo(subject.getCourseId(),subject.getCourseName(),null,null));
                    subjectInfoList.add(firstSubjectInfoVo);
                }

            }
        }

        //安排指定位置是否安排某科目科目
        if(StringUtils.isNotNull(subjectInfoList)){
            List<SchedulePositionInfo> canInfoList = new ArrayList<>();
            List<SchedulePositionInfo> canNotInfoList = new ArrayList<>();
            for(FirstSubjectInfoVo subjectInfoVo : subjectInfoList){  //指定位置安排
                if(subjectInfoVo.getFlag().equals("0")){  //0表示安排某课
                    if(subjectInfoVo.getNumber().equals("上午")){
                        for(Integer i=0 ;i<data.getLessonAtAM();i++){
                            SubjectInfo subject = subjectInfoVo.getSubjectInfo();
                            canInfoList.add(new SchedulePositionInfo(data.getGradeValue(),data.getClassValue(),subjectInfoVo.getDay(),i,new SubjectInfo(subject.getCourseId(),subject.getCourseName(),subject.getAttributes(),1),""));
                        }
                    }
                    if(subjectInfoVo.getNumber().equals("下午")){
                        for(Integer i=data.getLessonAtAM();i<data.getLessonAtAM()+ data.getLessonAtAM();i++){
                            SubjectInfo subject = subjectInfoVo.getSubjectInfo();
                            canInfoList.add(new SchedulePositionInfo(data.getGradeValue(),data.getClassValue(),subjectInfoVo.getDay(),i,new SubjectInfo(subject.getCourseId(),subject.getCourseName(),subject.getAttributes(),1),""));
                        }
                    }
                    if(!subjectInfoVo.getNumber().equals("上午") && !subjectInfoVo.getNumber().equals("下午")){
                        SubjectInfo subject = subjectInfoVo.getSubjectInfo();
                        canInfoList.add(new SchedulePositionInfo(data.getGradeValue(),data.getClassValue(),subjectInfoVo.getDay(),Integer.parseInt(subjectInfoVo.getNumber()),new SubjectInfo(subject.getCourseId(),subject.getCourseName(),subject.getAttributes(),1),""));
                    }

                }
                if(StringUtils.isNotNull(canInfoList)){
                    classScheduling.setUdfFixedSubjectList(canInfoList);  //安排某课初始化
                }
                if(subjectInfoVo.getFlag().equals("1")){  //1表示不安排某课
                    if(subjectInfoVo.getNumber().equals("上午")){
                        for(Integer i=0 ;i<data.getLessonAtAM();i++){
                            SubjectInfo subject = subjectInfoVo.getSubjectInfo();
                            canNotInfoList.add(new SchedulePositionInfo(data.getGradeValue(),data.getClassValue(),subjectInfoVo.getDay(),i,new SubjectInfo(subject.getCourseId(),subject.getCourseName(),subject.getAttributes(),1),""));
                        }
                    }
                    if(subjectInfoVo.getNumber().equals("下午")){
                        for(Integer i=data.getLessonAtAM();i<data.getLessonAtAM()+ data.getLessonAtAM();i++){
                            SubjectInfo subject = subjectInfoVo.getSubjectInfo();
                            canNotInfoList.add(new SchedulePositionInfo(data.getGradeValue(),data.getClassValue(),subjectInfoVo.getDay(),i,new SubjectInfo(subject.getCourseId(),subject.getCourseName(),subject.getAttributes(),1),""));
                        }
                    }
                    if(!subjectInfoVo.getNumber().equals("上午") && !subjectInfoVo.getNumber().equals("下午")){
                        SubjectInfo subject = subjectInfoVo.getSubjectInfo();
                        canNotInfoList.add(new SchedulePositionInfo(data.getGradeValue(),data.getClassValue(),subjectInfoVo.getDay(),Integer.parseInt(subjectInfoVo.getNumber()),new SubjectInfo(subject.getCourseId(),subject.getCourseName(),subject.getAttributes(),1),""));
                    }

                }
                if(StringUtils.isNotNull(canNotInfoList)){
                    classScheduling.setCanNotSubjectList(canNotInfoList);  //不能安排某课 外部初始化
                }

            }
        }

        classScheduling.setGradeInfoMap(gradeInfo);  //输入年级班级信息
        if(StringUtils.isNotNull(data.getContinueNum()) && data.getContinueNum()>0){
            classScheduling.setContinueNum(data.getContinueNum());
        }
        classScheduling.setGradeInfoMap(gradeInfo);  //输入年级班级信息
        classScheduling.setSchoolTimeRules(data.getSchoolTimeRules());
        classScheduling.makeLessonTable();  //制作课时表
        //返回前端list
        List<SchoolSchedule> list = new ArrayList<>();

        for (Map.Entry<Integer, Map<Integer, Map<Integer, Map<Integer, SchedulePositionInfo>>>> item : classScheduling.getScheduleInfos().entrySet()) {
//           for (Map.Entry<Integer, Map<Integer, Map<Integer, SchedulePositionInfo>>> itemItem : item.getValue().entrySet()) //{   //年级循环
            Map<Integer, Map<Integer, Map<Integer, SchedulePositionInfo>>> itemItem = item.getValue();
            System.out.println("_________________" + data.getGradeValue() + "年级" + data.getClassValue() + "班__________");
            for(Integer i=0;i<data.getDayPerLess();i++){ //循环课程数
                SchoolSchedule schoolSchedule = new SchoolSchedule();
                schoolSchedule.setYearValue(data.getYearValue());
                schoolSchedule.setSeason(data.getSeason());
                schoolSchedule.setGradeValue(data.getGradeValue());
                schoolSchedule.setClassValue(data.getClassValue());
                schoolSchedule.setTimeSort(i+1);
                schoolSchedule.setSortName("第"+(i+1)+"节课");
                if(i == 1){
                    System.out.println("---");
                }
                if(i.equals(data.getLessonAtAM())){
                    System.out.println("---");
                }
                if(i.equals(data.getLessonAtAM()+data.getLessonAtPM())){
                    System.out.println("---");
                }
                System.out.print("第" + (i+1) + "节课  ");
                for(Integer day=0; day< data.getWeekPerDay();day++){  //循环天数
                    Map<Integer, Map<Integer, SchedulePositionInfo>> itemItemItem = itemItem.get(data.getClassValue());
                    Map<Integer, SchedulePositionInfo> itemItemItemItem = itemItemItem.get(day);
                    SchedulePositionInfo schedulePositionInfo = itemItemItemItem.get(i);
                    String subjectName = "";
                    if(StringUtils.isNotNull(schedulePositionInfo.getSubjectInfo())){
                        subjectName = schedulePositionInfo.getSubjectInfo().getCourseName();
                    }
                    String subjectCode = "";
                    if(StringUtils.isNotNull(schedulePositionInfo.getSubjectInfo())){
                        subjectCode = schedulePositionInfo.getSubjectInfo().getCourseId()+"";
                    }
                    switch (day){
                        case 0 : schoolSchedule.setMonday(subjectName);
                            schoolSchedule.setMondayId(subjectCode);break;
                        case 1 : schoolSchedule.setTuesday(subjectName);
                            schoolSchedule.setTuesdayId(subjectCode);break;
                        case 2 : schoolSchedule.setWednesday(subjectName);
                            schoolSchedule.setWednesdayId(subjectCode);break;
                        case 3 : schoolSchedule.setThursday(subjectName);
                            schoolSchedule.setThursdayId(subjectCode);break;
                        case 4 : schoolSchedule.setFriday(subjectName);
                            schoolSchedule.setFridayId(subjectCode);break;
                        case 5 : schoolSchedule.setSaturday(subjectName);
                            schoolSchedule.setSaturdayId(subjectCode);break;
                        case 6 : schoolSchedule.setSunday(subjectName);
                            schoolSchedule.setSundayId(subjectCode);break;
                    }

                    if (schedulePositionInfo.getSubjectInfo() != null) {
//                        System.out.print(subjectName + "(" + fillStringLength(schedulePositionInfo.getTeacher().toString(),3) + ")   ");
                          System.out.print(subjectName + "   ");
                    } else {
                        System.out.print("--  ");
                    }

                }
                System.out.println();
                list.add(schoolSchedule);
            }
        }
        return list;
    }


    private static String fillStringLength(String value,Integer len){
        String result = value;
        if(value.length()<len){
            for(Integer l=0;l<len-value.length();l++){
                result+="  ";
            }
        }
        return result;
    }

}
