package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.bean.params.BasicCourseParams;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicCourse;
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.service.BasicCourseService;
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.transaction.annotation.Transactional;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "课程Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_BASIC + "/course")
@Validated
public class BasicCourseController {

    @Resource
    private PrintCommonService printCommonService;

    @Resource
    private BasicCourseService basicCourseService;

    @ApiOperation(value = "模糊查询")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public Result query(@RequestParam(value = "param", required = false) String param, @RequestParam(value = "printPlanId", required = false) List<String> printPlanId,
                        @RequestParam(value = "teachingRoomId", required = false) Long teachingRoomId) {
        if (Objects.isNull(printPlanId)) {
            printPlanId = new ArrayList<>();
        }
        List<Long> printPlanIdList = printPlanId.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList());
        List<BasicCourse> userDtos = printCommonService.list(param, printPlanIdList, teachingRoomId);
        return ResultUtil.ok(userDtos);
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.DELETE, detail = "删除操作，课程ID：{{course.id}}")
    public Result remove(@RequestBody BasicCourse course) {
        boolean isSuccess = printCommonService.remove(course.getId());
        return ResultUtil.ok(isSuccess);
    }

    @ApiOperation(value = "课程管理-查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicCourseList(@ApiParam(value = "所属机构id") @RequestParam(required = false) String belongOrgId, @ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) String courseName,
                                      @ApiParam(value = "创建时间（起始位置）") @RequestParam(required = false) String startCreateTime, @ApiParam(value = "创建时间（终止位置）") @RequestParam(required = false) String endCreateTime,
                                      @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(basicCourseService.basicCoursePage(SystemConstant.convertIdToLong(belongOrgId), courseName,
                SystemConstant.convertIdToLong(startCreateTime), SystemConstant.convertIdToLong(endCreateTime),
                pageNumber, pageSize));
    }

    @ApiOperation(value = "课程管理-新增/编辑")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.SAVE, detail = "新增/编辑操作，课程ID：{{basicCourseParams.id}}、课程代码：{{basicCourseParams.courseCode}}、课程名称：{{basicCourseParams.courseName}}")
    @Transactional
    public Result saveBasicCourse(@Valid @RequestBody BasicCourseParams basicCourseParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Long l = basicCourseService.saveBasicCourse(basicCourseParams, sysUser);
        //        if (!CollectionUtils.isEmpty(basicCourseParams.getTeachIdSet())) {
        //            teachCourseService.updateByCourseIdAndTeacherList(basicCourseParams.getId(), basicCourseParams.getTeachIdSet());
        //        }
        return ResultUtil.ok(l);
    }

    @ApiOperation(value = "课程管理-批量删除")
    @RequestMapping(value = "/delete_batch", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.DELETE)
    public Result enableBasicCourse(@ApiParam(value = "选择的要删除的课程id集合", required = true) @RequestParam List<Long> idList) {
        return ResultUtil.ok(basicCourseService.removeBasicCourseBatch(idList));
    }

    @ApiOperation(value = "课程管理-根据查询条件批量删除")
    @RequestMapping(value = "/delete_by_query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = EditResult.class)})
    @OperationLogDetail(detail =
            "根据查询条件[所属机构id[{{belongOrgId}}],课程名称（模糊查询）[{{courseName}}],创建时间（起始位置）[{{startCreateTime}}],"
                    + "创建时间（终止位置）[{{endCreateTime}}],状态[{{enable}}],启用&禁用操作[{{enableOperate}}]]批量启用/禁用课程", operationType = OperationTypeEnum.DELETE)
    public Result enableBasicCourseByQuery(@ApiParam(value = "所属机构id") @RequestParam(required = false) String belongOrgId,
                                           @ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) String courseName, @ApiParam(value = "创建时间（起始位置）") @RequestParam(required = false) String startCreateTime,
                                           @ApiParam(value = "创建时间（终止位置）") @RequestParam(required = false) String endCreateTime) {
        // 禁用条件
        if (!SystemConstant.strNotNull(belongOrgId) && !SystemConstant.strNotNull(courseName) && !SystemConstant.strNotNull(startCreateTime) && !SystemConstant.strNotNull(endCreateTime)) {
            throw ExceptionResultEnum.ERROR.exception("请选择要禁用的条件");
        }
        return ResultUtil.ok(
                basicCourseService.removeBasicCourseBatchByQuery(SystemConstant.convertIdToLong(belongOrgId), courseName, SystemConstant.convertIdToLong(startCreateTime),
                        SystemConstant.convertIdToLong(endCreateTime)));
    }

    @ApiOperation(value = "课程基本信息管理-批量导入")
    @RequestMapping(value = "/data_import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.IMPORT)
    @Transactional
    public Result basicCourseImportAsync(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file)
            throws Exception {
        basicCourseService.executeImportBasicCourseLogic(file);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "课程管理-导出")
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息")})
    @OperationLogDetail(operationType = OperationTypeEnum.EXPORT)
    public void export(@ApiParam(value = "所属机构id") @RequestParam(required = false) String belongOrgId, @ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) String courseName,
                       @ApiParam(value = "创建时间（起始位置）") @RequestParam(required = false) String startCreateTime, @ApiParam(value = "创建时间（终止位置）") @RequestParam(required = false) String endCreateTime,
                       HttpServletResponse response) throws Exception {
        basicCourseService.exportData(response, SystemConstant.convertIdToLong(belongOrgId), courseName, SystemConstant.convertIdToLong(startCreateTime), SystemConstant.convertIdToLong(endCreateTime));
    }

    @ApiOperation(value = "课程管理-查询")
    @RequestMapping(value = "/list_by_org", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicCourseListByOrg(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                           @ApiParam(value = "所属机构id", required = true) @RequestParam String belongOrgId,
                                           @ApiParam(value = "课程名称") @RequestParam(required = false) String courseName) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(basicCourseService.listByOrgId(SystemConstant.convertIdToLong(belongOrgId), SystemConstant.convertIdToLong(examId),courseName, sysUser));
    }
}

