package com.ym.mec.web.controller;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderStudentDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.entity.ClassGroup;
import com.ym.mec.biz.dal.entity.ClassGroupTeacherMapper;
import com.ym.mec.biz.dal.enums.ClassGroupTypeEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.SalarySettlementTypeEnum;
import com.ym.mec.biz.dal.page.ClassGroupQueryInfo;
import com.ym.mec.biz.dal.page.EndCourseScheduleQueryInfo;
import com.ym.mec.biz.dal.page.queryMusicGroupCourseScheduleQueryInfo;
import com.ym.mec.biz.service.ClassGroupService;
import com.ym.mec.biz.service.ClassGroupTeacherMapperService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.QueryInfo;

@RequestMapping("classGroup")
@Api(tags = "班级服务")
@RestController
public class ClassGroupController extends BaseController {

    @Autowired
    private ClassGroupService classGroupService;
    @Autowired
    private ClassGroupTeacherMapperService classGroupTeacherMapperService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;

    @ApiOperation(value = "分页查询班级列表")
    @GetMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryPage')")
    public HttpResponseResult<PageInfo<ClassGroup>> queryPage(ClassGroupQueryInfo queryInfo) {
        queryInfo.setDelFlag(0);
        return succeed(classGroupService.queryPage(queryInfo));
    }

    @ApiOperation(value = "创建班级")
    @PostMapping("/create")
    @PreAuthorize("@pcs.hasPermissions('classGroup/create')")
    public HttpResponseResult<Boolean> create(@RequestBody ClassGroup classGroup) throws Exception {
        return succeed(classGroupService.create(classGroup));
    }

    @ApiOperation(value = "新增单技班班级")
    @PostMapping("/add")
    @PreAuthorize("@pcs.hasPermissions('classGroup/add')")
    public Object add(@RequestBody ClassGroup classGroup) throws Exception {
        return succeed(classGroupService.addClassGroup(classGroup, GroupType.MUSIC));
    }

    @ApiOperation(value = "新增合奏班")
    @PostMapping("/addMixClass")
    @PreAuthorize("@pcs.hasPermissions('classGroup/addMixClass')")
    public Object addMixClass(@ApiParam(value = "乐团编号", required = true) @RequestParam String musicGroupId,
                              @ApiParam(value = "班级名称", required = true) String name,
                              @ApiParam(value = "班级编号,号分割", required = true) String classGroupIds) throws Exception {
        return succeed(classGroupService.addMixClassGroup(musicGroupId, name, classGroupIds));
    }

    @ApiOperation(value = "新增提高班")
    @PostMapping("/addHighClass")
    @PreAuthorize("@pcs.hasPermissions('classGroup/addHighClass')")
    @ApiParam(value = "乐团提高班json", required = true)
    public Object addHighClass(@RequestBody List<HighClassGroupDto> highClassGroupDtoList) throws Exception {
        if (highClassGroupDtoList.size() <= 0) {
            return failed("参数不合法");
        }
        return succeed(classGroupService.addHighClassGroup(highClassGroupDtoList));
    }

    @ApiOperation(value = "删除单技班")
    @PostMapping("/delSingle")
    @PreAuthorize("@pcs.hasPermissions('classGroup/delSingle')")
    public Object delSingle(Integer classGroupId) {
        classGroupService.delSingle(classGroupId);
        return succeed();
    }

    @ApiOperation(value = "删除合奏班")
    @PostMapping("/delMix")
    @PreAuthorize("@pcs.hasPermissions('classGroup/delMix')")
    public Object delMix(Integer classGroupId) {
        classGroupService.delMix(classGroupId);
        return succeed();
    }

    @ApiOperation(value = "修改班级")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('classGroup/update')")
    public Object update(ClassGroup classGroup) {
        classGroup.setUpdateTime(new Date());
        classGroupService.update(classGroup);
        return succeed();
    }

    @ApiOperation(value = "合奏班相关班级获取")
    @GetMapping("/findClassGroupAboutMix")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findClassGroupAboutMix')")
    public HttpResponseResult findClassGroupAboutMix(@ApiParam(value = "乐团编号", required = true) @RequestParam String musicGroupId,
                                                     @ApiParam(value = "班级编号", required = false) Integer mixClassGroupId) {
        return succeed(classGroupService.findClassGroup(musicGroupId, mixClassGroupId));
    }

    @ApiOperation(value = "乐团单技班列表")
    @GetMapping("/findMusicGroupClass")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findMusicGroupClass')")
    public HttpResponseResult findMusicGroupClass(@ApiParam(value = "乐团编号", required = true) @RequestParam String musicGroupId) {
        return succeed(classGroupService.findAllNormalClassGroupByMusicGroupId(musicGroupId));
    }

    @ApiOperation(value = "获取未分班的单技班列表")
    @GetMapping("/findNoClassSubjects")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findNoClassSubjects')")
    public HttpResponseResult findNoClassSubjects(@ApiParam(value = "乐团编号", required = true) @RequestParam String musicGroupId) {
        return succeed(classGroupService.findNoClassSubjects(musicGroupId));
    }

    @ApiOperation(value = "乐团合奏班列表")
    @GetMapping("/findMixMusicGroupClass")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findMixMusicGroupClass')")
    public HttpResponseResult findMixMusicGroupClass(@ApiParam(value = "乐团编号", required = true) @RequestParam String musicGroupId) {
        return succeed(classGroupService.findAllMixClassGroupByMusicGroupId(musicGroupId));
    }

    @ApiOperation(value = "乐团所有班级列表")
    @GetMapping("/findAllClassGroupByMusicGroup")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findAllClassGroupByMusicGroup')")
    public HttpResponseResult findAllClassGroupByMusicGroup(String musicGroupId, String type) {
        return succeed(classGroupService.findAllClassGroupByMusicGroup(musicGroupId, type));
    }

    @ApiOperation(value = "乐团详情--班级详情列表")
    @GetMapping("/queryMusicGroupClassGroup")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryMusicGroupClassGroup')")
    public HttpResponseResult queryMusicGroupClassGroup(QueryInfo queryInfo) {
        return succeed(classGroupService.queryMusicGroupClassGroup(queryInfo));
    }

    @ApiOperation(value = "乐团详情--课酬调整列表（课酬调整）")
    @GetMapping("/queryMusicGroupCourseSchedule")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryMusicGroupCourseSchedule')")
    public HttpResponseResult queryMusicGroupCourseSchedule(queryMusicGroupCourseScheduleQueryInfo queryInfo) {
        return succeed(classGroupService.queryMusicGroupCourseSchedule(queryInfo));
    }

    @ApiOperation(value = "乐团详情--课表详情列表（课表详情）")
    @GetMapping("/queryMusicGroupCourseScheduleDetail")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryMusicGroupCourseScheduleDetail')")
    public HttpResponseResult queryMusicGroupCourseScheduleDetail(queryMusicGroupCourseScheduleQueryInfo queryInfo) {
        return succeed(classGroupService.queryMusicGroupCourseScheduleDetail(queryInfo));
    }

    @ApiOperation(value = "乐团班级老师设置")
    @PostMapping("/addClassGroupTeacher")
    @ApiParam(value = "乐团班级老师json", required = true)
    @PreAuthorize("@pcs.hasPermissions('classGroup/addClassGroupTeacher')")
    public HttpResponseResult addClassGroupTeacher(@RequestBody List<ClassGroupTeacherMapper> classGroupTeacherMapperList) {
        if (classGroupTeacherMapperList.size() <= 0) {
            return failed("参数不合法");
        }
        return succeed(classGroupTeacherMapperService.classGroupTeachersInsert(classGroupTeacherMapperList, true));
    }

    @ApiOperation(value = "获取乐团班级老师")
    @GetMapping("/findMusicGroupClassTeacher")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findMusicGroupClassTeacher')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "classGroupId", value = "班级编号", required = false, dataType = "Integer")})
    public HttpResponseResult findMusicGroupClassTeacher(String musicGroupId, Integer classGroupId) {
        return succeed(classGroupService.getClassGroupAndTeachers(musicGroupId, "NORMAL,MIX", classGroupId));
    }

    @ApiOperation(value = "获取乐团班级老师课酬")
    @GetMapping("/findMusicGroupClassTeacherSalary")
    @PreAuthorize("@pcs.hasPermissions('classGroup/findMusicGroupClassTeacherSalary')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "结算类型（1-基准课酬，4-梯度课酬）", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "classGroupId", value = "班级编号", required = false, dataType = "Integer")})
    public HttpResponseResult findMusicGroupClassTeacherSalary(String musicGroupId, SalarySettlementTypeEnum type, Integer classGroupId) {
        try {
            return succeed(classGroupService.getClassGroupAndTeacherSalary(musicGroupId, type, classGroupId));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }

    @ApiOperation(value = "乐团班级老师课酬确认")
    @PostMapping("/setClassGroupTeacherSalary")
    @PreAuthorize("@pcs.hasPermissions('classGroup/setClassGroupTeacherSalary')")
    @ApiParam(value = "乐团班级老师<包含相应课酬>json", required = true)
    public HttpResponseResult setClassGroupTeacherSalary(@RequestBody List<ClassGroupTeacherMapper> classGroupTeacherMapperList) throws Exception {
        if (classGroupTeacherMapperList.size() <= 0) {
            return failed("没有待确认的课酬，如需成团，请走下一步，确认\"发放清单\"");
        }
        return succeed(classGroupTeacherMapperService.classGroupTeacherMapperUpdate(classGroupTeacherMapperList));
    }

    @ApiOperation(value = "乐团班级设置，成团确认")
    @PostMapping("/addMusicGroupTeam")
    @PreAuthorize("@pcs.hasPermissions('classGroup/addMusicGroupTeam')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "teacherId", value = "老师编号", required = true, dataType = "Integer")})
    public Object addMusicGroupTeam(Integer teacherId, String musicGroupId, Integer improventClassesNum) throws Exception {
        if (teacherId == null || StringUtils.isEmpty(musicGroupId)) {
            return failed("参数校验错误");
        }
        classGroupService.addMusicGroupTeam(teacherId, musicGroupId, improventClassesNum);
        return succeed();
    }


    @ApiOperation(value = "调整班级(添加班级)")
    @PostMapping("/revisionAddClassGroup")
    @PreAuthorize("@pcs.hasPermissions('classGroup/revisionAddClassGroup')")
    @ApiImplicitParams({@ApiImplicitParam(name = "ClassGroup4MixDto", value = "添加班级结构", required = true, dataType = "String")})
    public HttpResponseResult revisionAddClassGroup(@RequestBody List<ClassGroup4MixDto> classGroup4MixDtos) throws Exception {
        if (CollectionUtils.isEmpty(classGroup4MixDtos)) {
            return failed("请填写班级信息");
        }
        return succeed(classGroupService.classGroupAdjust(classGroup4MixDtos));
    }

    @ApiOperation(value = "调整班级(临时调整)")
    @PostMapping("/revisionClassGroup")
    @PreAuthorize("@pcs.hasPermissions('classGroup/revisionClassGroup')")
    @ApiImplicitParams({@ApiImplicitParam(name = "ClassGroup4MixDto", value = "添加班级结构", required = true, dataType = "String")})
    public HttpResponseResult revisionClassGroup(@RequestBody List<ClassGroup4MixDto> classGroup4MixDtos) throws Exception {
        return succeed(classGroupService.classGroupSnap(classGroup4MixDtos));
    }

    @ApiOperation(value = "调整班级(调整老师，重排课)")
    @PostMapping("/classGroupUpdate")
    @PreAuthorize("@pcs.hasPermissions('classGroup/classGroupUpdate')")
    @ApiImplicitParams({@ApiImplicitParam(name = "ClassGroup4MixDto", value = "添加班级结构", required = true, dataType = "String")})
    public HttpResponseResult classGroupUpdate(@RequestBody List<ClassGroup4MixDto> classGroup4MixDtos) throws Exception {
        return succeed(classGroupService.classGroupUpdate(classGroup4MixDtos));
    }

    @ApiOperation(value = "小班报名详情")
    @GetMapping("/highClassGroups")
    @PreAuthorize("@pcs.hasPermissions('classGroup/highClassGroups')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
    public HttpResponseResult highClassGroups(String musicGroupId) throws Exception {
        return succeed(classGroupService.findClassGroupByMusicGroupIdAndSubjectId(musicGroupId, null));
    }

    @ApiOperation(value = "按班级类型查找班级（班级调整）")
    @GetMapping("/classGroupAndTeacher")
    @PreAuthorize("@pcs.hasPermissions('classGroup/classGroupAndTeacher')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "string"),
            @ApiImplicitParam(name = "type", value = "班级类型", required = true, dataType = "string"),
    })
    public HttpResponseResult classGroupAndTeacher(String musicGroupId, ClassGroupTypeEnum type) throws Exception {
        return succeed(classGroupService.getClassGroupAndTeacherByType(musicGroupId, type));
    }

    @ApiOperation(value = "获取所有班级列表")
    @GetMapping("/queryClassGroupPage")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryClassGroupPage')")
    public HttpResponseResult queryClassGroupPage(ClassGroupQueryInfo queryInfo) throws Exception {
        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(classGroupService.queryClassGroupPage(queryInfo));
    }

    @ApiOperation(value = "查询是否设置课酬")
    @GetMapping("/checkSetSalary")
    @PreAuthorize("@pcs.hasPermissions('classGroup/checkSetSalary')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "string")
    })
    public HttpResponseResult checkSetSalary(String musicGroupId) {
        return succeed(classGroupService.checkSetSalary(musicGroupId));
    }

    @PostMapping("/enumTest")
    public HttpResponseResult enumTest(@RequestBody TestDto testDto) {
        return succeed(testDto.getDelFlag().getMsg());
    }

    @GetMapping("queryUserInfo")
    public HttpResponseResult queryUserInfo(Integer userId) {
        SysUser sysUser = sysUserFeignService.queryUserById(userId);
        return succeed(sysUser.getUsername());
    }

    @ApiOperation(value = "查询班级老师")
    @GetMapping("/getClassGroupTeachers")
    @PreAuthorize("@pcs.hasPermissions('classGroup/getClassGroupTeachers')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classGroupId", value = "班级id", required = true, dataType = "int")
    })
    public HttpResponseResult getClassGroupTeachers(Integer classGroupId) {
        return succeed(classGroupTeacherMapperService.getClassGroupTeachers(classGroupId));
    }

    @ApiOperation(value = "清除班级未上课程")
    @PostMapping("/delClassNoStartCourse")
    @PreAuthorize("@pcs.hasPermissions('classGroup/delClassNoStartCourse')")
    @ApiImplicitParams({@ApiImplicitParam(name = "classGroupId", value = "班级id", required = true, dataType = "int")})
    public HttpResponseResult delClassNoStartCourse(Integer classGroupId) throws Exception {
        return succeed(classGroupService.delClassNoStartCourse(classGroupId));
    }

    @ApiOperation(value = "终极班级信息获取")
    @GetMapping("/superFindClassGroups")
    @PreAuthorize("@pcs.hasPermissions('classGroup/superFindClassGroups')")
    public HttpResponseResult superFindClassGroups(EndCourseScheduleQueryInfo queryInfo) {
        return succeed(classGroupService.endFindClassGroups(queryInfo));
    }

    @ApiOperation(value = "获取班级剩余课程类型对应的时长（分钟）")
    @GetMapping("/queryRemainCourseTypeDuration")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryRemainCourseTypeDuration')")
    public HttpResponseResult queryRemainCourseTypeDuration(String classGroupIdList) {
        return succeed(classGroupService.queryRemainCourseTypeDuration(classGroupIdList));
    }

    @ApiOperation(value = "进行中乐团-修改-班级详情-学员班级调整-班级剩余课次")
    @GetMapping("/classGroupSubCourseNum")
    @PreAuthorize("@pcs.hasPermissions('classGroup/classGroupSubCourseNum')")
    public HttpResponseResult classGroupSubCourseNum(Integer classGroupId) {
        return succeed(classGroupService.classGroupSubCourseNum(classGroupId));
    }

    @ApiOperation(value = "进行中乐团-修改-班级详情-学员班级调整-获取班级最大剩余可排课时长")
    @PostMapping("/querySubCourseTime")
    @PreAuthorize("@pcs.hasPermissions('classGroup/querySubCourseTime')")
    public HttpResponseResult querySubCourseTime(Integer classGroupId) {
        return succeed(classGroupService.querySubCourseTime(classGroupId));
    }

    @ApiOperation(value = "进行中乐团-修改-班级详情-班级合并-获取学员需要补交的费用以及需要退还的课程余额")
    @PostMapping("/queryStudentPaymentCalenders")
    @PreAuthorize("@pcs.hasPermissions('classGroup/queryStudentPaymentCalenders')")
    public HttpResponseResult queryStudentPaymentCalenders(@RequestBody MergeClassSplitClassAffirmDto mergeClassSplitClassAffirmDto) {
        Map<Integer, List<MusicGroupPaymentCalenderStudentDetail>> collect = classGroupService.queryStudentPaymentCalenders(mergeClassSplitClassAffirmDto.getMasterClassGroupId(),
                JSON.toJSONString(mergeClassSplitClassAffirmDto.getClassGroupStudents()),
                mergeClassSplitClassAffirmDto.getStudentIds())
                .stream().collect(Collectors.groupingBy(e -> e.getClassGroupId()));
        return succeed(collect);
    }

    @ApiOperation(value = "跨团班级合并提交")
    @PostMapping("/spanGroupMergeClassSplitClassAffirm")
    @PreAuthorize("@pcs.hasPermissions('classGroup/spanGroupMergeClassSplitClassAffirm')")
    public HttpResponseResult spanGroupMergeClassSplitClassAffirm(@RequestBody MergeClassSplitClassAffirmDto mergeClassSplitClassAffirmDto) throws Exception {
        return classGroupService.spanGroupMergeClassSplitClassAffirm(mergeClassSplitClassAffirmDto);
    }

    @ApiOperation(value = "进行中乐团-修改-班级详情-学员班级调整-获取所选班级最大可排课时长")
    @PostMapping("/getDefaultPaymentCalender")
    @PreAuthorize("@pcs.hasPermissions('classGroup/getDefaultPaymentCalender')")
    public HttpResponseResult studentClassAuditDetail(@RequestBody List<Integer> classGroupIds) {
        return succeed(classGroupService.getDefaultPaymentCalender(classGroupIds));
    }

    @ApiOperation(value = "进行中乐团-修改-班级详情-学员班级调整-合并结果确认")
    @PostMapping("/mergeClassSplitClassAffirm")
    @PreAuthorize("@pcs.hasPermissions('classGroup/mergeClassSplitClassAffirm')")
    public HttpResponseResult mergeClassSplitClassAffirm(@RequestBody MergeClassSplitClassAffirmDto mergeClassSplitClassAffirmDto) throws Exception {
        return classGroupService.mergeClassSplitClassAffirm(mergeClassSplitClassAffirmDto);
    }
}
