package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.ClassGroupTeacherMapperDao;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dto.CoursePostponeDto;
import com.ym.mec.biz.dal.dto.CreateCourseScheduleDto;
import com.ym.mec.biz.dal.dto.VipGroupCourseAdjustInfoDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.AuditStatusEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.TeachModeEnum;
import com.ym.mec.biz.dal.page.EndCourseScheduleQueryInfo;
import com.ym.mec.biz.dal.page.PracticeGroupQueryInfo;
import com.ym.mec.biz.dal.page.StudentAttendanceQueryInfo;
import com.ym.mec.biz.dal.page.VipGroupQueryInfo;
import com.ym.mec.biz.service.CourseScheduleComplaintsService;
import com.ym.mec.biz.service.CourseScheduleService;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.biz.service.StudentAttendanceService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Joburgess
 * @Date 2019/9/10
 */
@RequestMapping("courseSchedule")
@Api(tags = "课程计划服务")
@RestController
public class CourseScheduleController extends BaseController {

    @Autowired
    private CourseScheduleService scheduleService;
    @Autowired
    private StudentAttendanceService studentAttendanceService;
    @Autowired
    private ClassGroupTeacherMapperDao classGroupTeacherMapperDao;
    @Autowired
    private CourseScheduleComplaintsService courseScheduleComplaintsService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private MusicGroupService musicGroupService;
    @Autowired
    private EmployeeDao employeeDao;

    @ApiOperation(value = "排课")
    @PostMapping("/batchAddCourseSchedule")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/batchAddCourseSchedule')")
    public Object batchAddCourseSchedule(@RequestBody CreateCourseScheduleDto createCourseScheduleDto){
        if(Objects.isNull(createCourseScheduleDto.getMusicGroupID())){
            throw new BizException("请指定乐团");
        }
        
        MusicGroup musicGroup = musicGroupService.get(createCourseScheduleDto.getMusicGroupID());
        if(musicGroup == null){
        	return failed("乐团信息不存在");
        }
        
        List<ClassGroupTeacherMapper> byMusicGroup = classGroupTeacherMapperDao.findByMusicGroup(createCourseScheduleDto.getMusicGroupID());
        Map<Integer, List<ClassGroupTeacherMapper>> teacherByClassGroup = byMusicGroup.stream().collect(Collectors.groupingBy(ClassGroupTeacherMapper::getClassGroupId));

        createCourseScheduleDto.getCourseSchedules().forEach(courseSchedule -> {
            List<ClassGroupTeacherMapper> classGroupTeacherMappers = teacherByClassGroup.get(courseSchedule.getClassGroupId());
            if(CollectionUtils.isEmpty(classGroupTeacherMappers)){
                throw new BizException("乐团老师设置有误");
            }
            courseSchedule.setTeacherId(classGroupTeacherMappers.get(0).getUserId());
            courseSchedule.setActualTeacherId(classGroupTeacherMappers.get(0).getUserId());
            courseSchedule.setSchoolId(musicGroup.getSchoolId());
            courseSchedule.setMusicGroupId(musicGroup.getId());
            courseSchedule.setGroupType(GroupType.MUSIC);
            courseSchedule.setTeachMode(TeachModeEnum.OFFLINE);
        });

        scheduleService.createCourseSchedules(createCourseScheduleDto);
        return succeed();
    }

    @ApiOperation(value = "批量跟新排课")
    @PostMapping("/batchUpdateCourseSchedule/{musicGroupID}")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/batchUpdateCourseSchedule')")
    public Object batchUpdateCourseSchedule(@RequestBody List<CourseSchedule> courseSchedules,
                                            @ApiParam(value = "乐团编号", required = true) @PathVariable("musicGroupID") String musicGroupID){
        scheduleService.batchUpdateCourseSchedule(courseSchedules,musicGroupID);
        return succeed();
    }

    @ApiOperation(value = "批量删除课程")
    @PostMapping(value = "/bathDelete")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/bathDelete')")
    public Object bathDelete(String courseScheduleIds){
        if(StringUtils.isEmpty(courseScheduleIds)){
            throw new BizException("请指定课程编号");
        }
        long[] ints = Arrays.asList(courseScheduleIds.split(",")).stream().mapToLong(Long::parseLong).toArray();
        Long[] longs = ArrayUtils.toObject(ints);
        scheduleService.deleteCourseSchedules(Arrays.asList(longs));
        return succeed();
    }

    @ApiOperation(value = "获取vip课程计划")
    @PostMapping(value = "/findVipGroupCourseSchedules")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/findVipGroupCourseSchedules')")
    public Object findVipGroupCourseSchedules(VipGroupQueryInfo queryInfo){
        return succeed(scheduleService.findVipGroupCourseSchedules(queryInfo));
    }

    @ApiOperation(value = "根据月份获取乐团在该月有课的日期")
    @GetMapping("/getCourseScheduleDateByMonth")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/getCourseScheduleDateByMonth')")
        public Object getCourseScheduleDateByMonth(@ApiParam(value = "乐团编号", required = true) @RequestParam Long musicGroupID,
                                                   @ApiParam(value = "月份", required = true) @RequestParam Date month) {
        return succeed(scheduleService.getCourseScheduleDateByMonth(musicGroupID,month));
    }

    @ApiOperation(value = "根据课程ID查询正在或即将开始的课程")
    @GetMapping("/getCurrentCourseDetail/{courseID}")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/getCurrentCourseDetail')")
    public Object getCurrentCourseDetail(@ApiParam(value = "课程ID", required = true) @PathVariable("courseID") Long courseID){
        return succeed(scheduleService.getCurrentCourseDetail(courseID));
    }

    @ApiOperation(value = "根据班级ID获取当前课程的学生")
    @GetMapping("/getCurrentCourseStudents")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/getCurrentCourseStudents')")
    public Object getCurrentCourseStudents(@RequestBody StudentAttendanceQueryInfo queryInfo){
        return succeed(studentAttendanceService.getCurrentCourseStudents(queryInfo));
    }

    @ApiOperation(value = "课时调整")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/classStartDateAdjust','system')")
    @PostMapping(value = "/classStartDateAdjust",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object classStartDateAdjust(CourseSchedule courseSchedule){
        CourseSchedule oldCourseSchedule = scheduleService.get(courseSchedule.getId());
        if(Objects.isNull(oldCourseSchedule)){
            return failed("未找到指定课程");
        }
        if(Objects.isNull(courseSchedule.getClassGroupId())){
            courseSchedule.setClassGroupId(oldCourseSchedule.getClassGroupId());
        }
        List<CourseSchedule> courseSchedules=new ArrayList<>();
        courseSchedules.add(courseSchedule);
        scheduleService.courseAdjust(courseSchedules);
        return succeed();
    }

    @ApiOperation(value = "课时调整-批量")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/batchClassStartDateAdjust')")
    @PostMapping(value = "/batchClassStartDateAdjust")
    public Object batchClassStartDateAdjust(@RequestBody List<CourseSchedule> courseSchedules){
        scheduleService.courseAdjust(courseSchedules);
        return succeed();
    }

    @ApiOperation(value = "课时交换")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/courseSwap')")
    @GetMapping(value = "/courseSwap",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object courseSwap(Long courseScheduleId1,Long courseScheduleId2){
        if(Objects.isNull(courseScheduleId1)||Objects.isNull(courseScheduleId2)){
            return failed("请指定课程");
        }
        scheduleService.courseSwap(courseScheduleId1,courseScheduleId2);
        return succeed();
    }

    @ApiOperation(value = "课程投诉审核")
    @PostMapping(value = "/courseScheduleCommplaintAudit")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/courseScheduleCommplaintAudit')")
	public Object courseScheduleCommplaintAudit(Long id, Double teacherLiabilityRatio, Double studentLiabilityRatio, AuditStatusEnum status) {
		scheduleService.courseScheduleCommplaintAudit(id, teacherLiabilityRatio, studentLiabilityRatio, status);
		return succeed();
	}

    @ApiOperation(value = "检测乐团下所有的班级是否都已排课")
    @PostMapping(value = "/checkMusicGroupClassCourse")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/checkMusicGroupClassCourse')")
    public Object checkMusicGroupClassCourse(String musicGroupId){
        scheduleService.checkMusicGroupClassCourse(musicGroupId);
        return succeed();
    }

	@ApiOperation(value = "课酬调整")
	@PostMapping("/updateTeacherCoursesSalary")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/updateTeacherCoursesSalary')")
	public Object updateTeacherCoursesSalary(Long courseScheduleId, Integer teacherId, BigDecimal salary, BigDecimal subsidy, String scope) {
		return succeed(musicGroupService.updateTeacherCoursesSalary(courseScheduleId, teacherId, salary, subsidy, scope));
	}

    @ApiOperation(value = "删除乐团下所有未上的课时")
    @GetMapping("/batchDeleteMusicGroupNotStartCourse")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/batchDeleteMusicGroupNotStartCourse')")
	public Object batchDeleteMusicGroupNotStartCourse(String musicGroupId){
        scheduleService.batchDeleteMusicGroupNotStartCourse(musicGroupId,GroupType.MUSIC);
        return succeed();
    }

	@ApiOperation(value = "乐团详情--课酬调整--课程教师列表")
	@GetMapping("/queryTeacherSalary")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/queryTeacherSalary')")
	public Object queryTeacherSalary(Integer courseScheduleId) {
		return succeed(musicGroupService.queryTeacherSalary(courseScheduleId));
	}

    @ApiOperation(value = "根据班级获取课程计划")
    @GetMapping("/findCourseScheduleByClassGroup")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/findCourseScheduleByClassGroup')")
	public Object findCourseScheduleByClassGroup(Integer classGroupId){
        return succeed(scheduleService.findCourseScheduleByClassGroup(classGroupId));
    }
    
    @ApiOperation(value = "查询课程投诉详情")
	@GetMapping("/queryCourseScheduleComplaintsDetail")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/queryCourseScheduleComplaintsDetail')")
    public Object queryCourseScheduleComplaintsDetail(Long courseScheduleComplaintsId){
    	CourseScheduleComplaints complaints = courseScheduleComplaintsService.get(courseScheduleComplaintsId);
    	if(complaints == null){
    		return failed("参数输入不正确");
    	}
    	
    	SysUser user = sysUserFeignService.queryUserById(complaints.getUserId());
    	complaints.getUser().setUsername(user.getUsername());
    	
    	CourseSchedule courseSchedule = scheduleService.get(complaints.getCourseScheduleId());
    	SysUser teacher = sysUserFeignService.queryUserById(courseSchedule.getActualTeacherId());
    	courseSchedule.getTeacher().setUsername(teacher.getUsername());
    	
    	ModelMap model = new ModelMap();
    	model.put("complaints", complaints);
    	model.put("courseSchedule", courseSchedule);
    	
    	return succeed(model);
    }

    @ApiOperation(value = "vip课批量调整")
    @PostMapping("/vipCourseAdjust")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/vipCourseAdjust')")
    public Object vipCourseAdjust(@RequestBody VipGroupCourseAdjustInfoDto vipGroupCourseAdjustInfo){
        scheduleService.vipCourseAdjust(vipGroupCourseAdjustInfo);
        return succeed();
    }

    @ApiOperation(value = "vip课批量新增")
    @PostMapping("/batchAppendVipGroupCourses")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/batchAppendVipGroupCourses')")
    public Object batchAppendVipGroupCourses(@RequestBody VipGroupCourseAdjustInfoDto vipGroupCourseAdjustInfo){
        scheduleService.batchAppendVipGroupCourses(vipGroupCourseAdjustInfo);
        return succeed();
    }

    @ApiOperation(value = "终极课表获取")
    @GetMapping("/superFindCourseSchedules")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/superFindCourseSchedules')")
    public Object superFindCourseSchedules(EndCourseScheduleQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if(!sysUser.getIsSuperAdmin()){
            Employee employee = employeeDao.get(sysUser.getId());
            if (org.apache.commons.lang3.StringUtils.isEmpty(queryInfo.getOrganIdList())) {
                queryInfo.setOrganIdList(employee.getOrganIdList());
            }else if(org.apache.commons.lang3.StringUtils.isEmpty(employee.getOrganIdList())){
                return failed("用户所在分部异常");
            }else {
                List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
                if(!list.containsAll(Arrays.asList(queryInfo.getOrganIdList().split(",")))){
                    return failed("非法请求");
                }
            }
        }
        return succeed(scheduleService.endFindCourseSchedules(queryInfo));
    }

    @ApiOperation(value = "课程顺延")
    @PostMapping("/coursePostpone")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/coursePostpone')")
    public Object coursePostpone(CoursePostponeDto coursePostPoneInfo){
        scheduleService.coursePostpone(coursePostPoneInfo);
        return succeed();
    }

    @ApiOperation(value = "陪练课调整")
    @PostMapping("/practiceCourseAdjust")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/practiceCourseAdjust')")
    public Object practiceCourseAdjust(CourseSchedule courseSchedule){
        scheduleService.practiceCourseAdjust(courseSchedule);
        return succeed();
    }

    @ApiOperation(value = "陪练课老师调整")
    @PostMapping("/practiceCourseTeacherAdjust")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/practiceCourseTeacherAdjust')")
    public Object practiceCourseTeacherAdjust(Long courseScheduleId,Integer teacherId){
        scheduleService.practiceCourseTeacherAdjust(courseScheduleId,teacherId);
        return succeed();
    }

    @ApiOperation(value = "陪练课课程组老师调整")
    @PostMapping("/practiceGroupTeacherAdjust")
    @PreAuthorize("@pcs.hasPermissions('courseSchedule/practiceGroupTeacherAdjust')")
    public Object practiceGroupTeacherAdjust(String practiceGroupId, Integer teacherId){
        scheduleService.practiceGroupTeacherAdjust(practiceGroupId,teacherId);
        return succeed();
    }
}

