package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.params.AssignClazzParam;
import com.qmth.distributed.print.business.bean.params.TeachCourseParams;
import com.qmth.distributed.print.business.bean.params.TeachCourseSelectParam;
import com.qmth.distributed.print.business.bean.params.TeacherTeamParam;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.service.TeachCourseService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.log.OperationTypeEnum;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 教学课程 前端控制器
 * @Author: CaoZixuan
 * @Date: 2022-02-10
 */
@Api(tags = "教学课程Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_TEACH + "/course")
@Validated
//@Aac(strict = BOOL.FALSE, auth = BOOL.FALSE)
public class TeachCourseController {

    @Resource
    private TeachCourseService teachCourseService;

    @ApiOperation(value = "教学课程-查询")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findTeachCoursePage(@ApiParam(value = "学期ID") @RequestParam(required = false) String semesterId,
                                      @ApiParam(value = "考试ID") @RequestParam(required = false) String examId,
                                      @ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) String courseName,
                                      @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                      @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        if (semesterId == null) {
            throw ExceptionResultEnum.SEMESTER_ID_IS_NULL.exception();
        }
        if (examId == null) {
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        return ResultUtil.ok(
                teachCourseService.teachCoursePage(SystemConstant.convertIdToLong(examId), courseName, pageNumber,
                        pageSize));
    }

    @ApiOperation(value = "教学课程-手动添加课程")
    @RequestMapping(value = "/manual_create", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(detail = "手动添加教学课程，参数[{{teachCourseParams}}]", operationType = OperationTypeEnum.ADD)
    @Deprecated
    public Result manualCreate(@Valid @RequestBody TeachCourseParams teachCourseParams, BindingResult bindingResult) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(teachCourseService.manualCreate(teachCourseParams, requestUser));
    }

    @ApiOperation(value = "教学课程-课程表选择教学课程")
    @RequestMapping(value = "/select_create", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.ADD, detail = "添加课程操作，考试ID：{{teachCourseSelectParam.examId}}、课程代码：{{teachCourseSelectParam.courseCodeList}}")
    public Result selectCreate(@Valid @RequestBody TeachCourseSelectParam teachCourseSelectParam, BindingResult bindingResult) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        teachCourseService.selectCreate(teachCourseSelectParam, requestUser);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "教学课程-教学课程批量导入")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(detail = "教学课程批量导入", operationType = OperationTypeEnum.ADD)
    @Deprecated
    public Result importTeachCourse(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) throws IOException, NoSuchFieldException {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        teachCourseService.importTeachCourse(file, requestUser);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "教学课程-查找基础课程")
    @RequestMapping(value = "/find_basic_course", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicCourse() {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(teachCourseService.findBasicCourseByUser(requestUser));
    }

    @ApiOperation(value = "教学课程-批量删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.DELETE,detail = "删除操作，教学课程ID：[{{idList}}]")
    public Result deleteTeachCourse(@ApiParam(value = "选择的要删除的课程id集合", required = true) @RequestParam List<String> idList) {
        teachCourseService.deleteTeachCourseBatch(
                idList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList()));
        return ResultUtil.ok();
    }

    @ApiOperation(value = "教师团队-手动添加教师")
    @RequestMapping(value = "/manual_create_teacher", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(detail = "手动添加教师，参数[{{teacherTeamParam}}]", operationType = OperationTypeEnum.ADD)
    public Result manualCreateTeacher(@Valid @RequestBody TeacherTeamParam teacherTeamParam, BindingResult bindingResult) throws IllegalAccessException {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        teachCourseService.manualCreateTeacher(teacherTeamParam, requestUser);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "教师团队-用户表选择教师")
    @RequestMapping(value = "/select_create_teacher", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.ADD)
    public Result selectCreate(@ApiParam(value = "考试id", required = true) @RequestParam String teachCourseId,
                               @ApiParam(value = "教师id集合", required = true) @RequestParam List<String> userIdList) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        teachCourseService.selectCreateTeacher(SystemConstant.convertIdToLong(teachCourseId),
                userIdList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList()), requestUser);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "教师团队-批量导入教师")
    @RequestMapping(value = "/import_teacher", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(detail = "教学课程批量导入", operationType = OperationTypeEnum.ADD)
    @Deprecated
    public Result importTeacherTeam(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file, @ApiParam(value = "基础课程", required = true) @RequestParam Long basicCourseId)
            throws IOException, NoSuchFieldException, IllegalAccessException {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        teachCourseService.importTeacherTeam(file, basicCourseId, requestUser);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "教师团队-分页查询")
    @RequestMapping(value = "/teacher_team_page", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findTeachTeamPage(@ApiParam(value = "教学课程id", required = true) @RequestParam String teachCourseId,
                                    @ApiParam(value = "用户姓名工号（模糊查询）") @RequestParam(required = false) String userInfo,
                                    @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                    @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(
                teachCourseService.findTeacherTeamPage(SystemConstant.convertIdToLong(teachCourseId), userInfo,
                        pageNumber, pageSize));
    }

    @ApiOperation(value = "教师团队-根据机构查询")
    @RequestMapping(value = "/find_teacher_by_org", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findTeachCoursePage(@ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) Long orgId) {
        return ResultUtil.ok(teachCourseService.findUserByOrgId(orgId));
    }

    @ApiOperation(value = "教师团队管理-分配班级列表查询")
    @RequestMapping(value = "/find_clazz_list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findClazzList(@ApiParam(value = "教学课程id", required = true) @RequestParam String teachCourseId,
                                @ApiParam(value = "班级名称") @RequestParam(required = false) String clazzName) {
        return ResultUtil.ok(
                teachCourseService.findClazzDistributedStatus(SystemConstant.convertIdToLong(teachCourseId),
                        clazzName));
    }

    @ApiOperation(value = "教师团队管理-分配班级")
    @RequestMapping(value = "/assign_clazz", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "创建成功", response = EditResult.class)})
    @OperationLogDetail(detail = "分配班级，参数[{{assignClazzParam}}]", operationType = OperationTypeEnum.ADD)
    public Result assignClazz(@Valid @RequestBody AssignClazzParam assignClazzParam, BindingResult bindingResult) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        teachCourseService.assignClazz(assignClazzParam, requestUser);
        return ResultUtil.ok();
    }
}