package com.qmth.themis.admin.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.themis.business.annotation.ApiJsonObject;
import com.qmth.themis.business.annotation.ApiJsonProperty;
import com.qmth.themis.business.bean.StudentParams;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.response.TEStudentDto;
import com.qmth.themis.business.entity.TBUser;
import com.qmth.themis.business.entity.TEStudent;
import com.qmth.themis.business.entity.TOeExamRecord;
import com.qmth.themis.business.enums.MonitorVideoSourceEnum;
import com.qmth.themis.business.service.ThemisCacheService;
import com.qmth.themis.business.service.TEStudentService;
import com.qmth.themis.business.util.OssUtil;
import com.qmth.themis.business.util.ServletUtil;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.exception.BusinessException;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
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.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 学生档案 前端控制器
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/25
 */
@Api(tags = "学生档案Controller")
@RestController
@RequestMapping(SystemConstant.PREFIX_URL_ADMIN + "/student")
@Validated
public class TEStudentController {

    @Resource
    TEStudentService teStudentService;

    @Resource
    OssUtil ossUtil;

    @Resource
    ThemisCacheService themisCacheService;

    @ApiOperation(value = "学生查询接口")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考生信息", response = TEStudentDto.class)})
    public Result query(@ApiParam(value = "证件号", required = false) @RequestParam(required = false) String identity,
                        @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String name,
                        @ApiParam(value = "是否启用", required = false) @RequestParam(required = false) Integer enable,
                        @ApiParam(value = "是否有照片(true为有，false为无)", required = false) @RequestParam(required = false) Boolean photo,
                        @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) int pageNumber,
                        @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) int pageSize) {
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        IPage<TEStudentDto> teExamStudentIPage = teStudentService.studentQuery(new Page<>(pageNumber, pageSize), identity, name, enable, tbUser.getOrgId(), photo);
        if (teExamStudentIPage.getRecords() != null && teExamStudentIPage.getRecords().size() > 0) {
            for (TEStudentDto dto : teExamStudentIPage.getRecords()) {
                if (StringUtils.isNotBlank(dto.getBasePhotoPath())) {
                    dto.setBasePhotoPath(ossUtil.getAliYunOssPublicDomain().getPublicUrl() + "/" + dto.getBasePhotoPath());
                }
                if (Objects.isNull(dto.getUpdateName())) {
                    dto.setUpdateName(dto.getCreateName());
                }
                if (Objects.isNull(dto.getUpdateTime())) {
                    dto.setUpdateTime(dto.getCreateTime());
                }
            }
        }
        return ResultUtil.ok(teExamStudentIPage);
    }

    @ApiOperation(value = "学生停用/启用接口")
    @RequestMapping(value = "/toggle", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    @Transactional
    public Result studentToggle(@ApiJsonObject(name = "studentToggle", value = {
            @ApiJsonProperty(key = "id", type = "long", example = "1", description = "学生ID"),
            @ApiJsonProperty(key = "enable", type = "long", example = "1", description = "是否启用")
    }) @ApiParam(value = "学生信息", required = true) @RequestBody Map<String, Object> mapParameter) {
        if (Objects.isNull(mapParameter.get(SystemConstant.ID)) || Objects.equals(mapParameter.get(SystemConstant.ID), "")) {
            throw new BusinessException(ExceptionResultEnum.STUDENT_ID_IS_NULL);
        }
        Long id = Long.parseLong(String.valueOf(mapParameter.get(SystemConstant.ID)));
        if (Objects.isNull(mapParameter.get("enable")) || Objects.equals(mapParameter.get("enable"), "")) {
            throw new BusinessException(ExceptionResultEnum.ENABLE_IS_NULL);
        }
        Integer enable = Integer.parseInt(String.valueOf(mapParameter.get("enable")));
        TEStudent teStudent = teStudentService.getById(id);
        if (Objects.isNull(teStudent)) {
            throw new BusinessException(ExceptionResultEnum.STUDENT_NO);
        }
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        teStudent.setEnable(enable);
        teStudent.setUpdateId(tbUser.getId());
        teStudentService.updateById(teStudent);
        themisCacheService.updateStudentAccountCache(teStudent.getId());
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "学生修改密码接口")
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    public Result studentUpdatePwd(@Validated @RequestBody StudentParams studentParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        teStudentService.updatePwd(studentParams);
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "学生考试记录查询接口")
    @RequestMapping(value = "/exam_record/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "学生考试记录信息", response = TOeExamRecord.class)})
    public Result examRecordQuery(@ApiParam(value = "学生ID", required = true) @RequestParam Long studentId,
                                  @ApiParam(value = "考试id") @RequestParam(required = false) Long examId,
                                  @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) int pageNumber,
                                  @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) int pageSize) {
        if (Objects.isNull(studentId) || Objects.equals(studentId, "")) {
            throw new BusinessException(ExceptionResultEnum.STUDENT_ID_IS_NULL);
        }
        return ResultUtil.ok(teStudentService.studentExamRecordQuery(new Page<>(pageNumber, pageSize), studentId, examId));
    }

    @ApiOperation(value = "学生视频监考回放查询接口")
    @RequestMapping(value = "/exam_record/video/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "学生视频监考回放信息", response = TOeExamRecord.class)})
    public Result examRecordVideoQuery(@ApiParam(value = "考试记录id", required = true) @RequestParam(required = true) Long examRecordId,
                                       @ApiParam(value = "视频源") @RequestParam(required = false) MonitorVideoSourceEnum monitorRecord,
                                       @ApiParam(value = "是否查询轨迹日志") @RequestParam(required = false) Boolean log,
                                       @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) int pageNumber,
                                       @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) int pageSize) {
        return ResultUtil.ok(teStudentService.examRecordVideoQuery(new Page<>(pageNumber, pageSize), examRecordId, monitorRecord, log));
    }

    @ApiOperation(value = "底照上传")
    @RequestMapping(value = "/base_photo/upload", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "结果信息")})
    public Result photoUpload(@ApiParam(value = "证件号", required = true) @RequestParam String identity,
                              @ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file,
                              @ApiParam(value = "md5", required = true) @RequestParam String md5,
                              @ApiParam(value = "是否覆盖已有底照") @RequestParam(required = false) Boolean cover) {
        if (StringUtils.isBlank(identity)) {
            throw new BusinessException("证件号不能为空");
        }
        if (file == null) {
            throw new BusinessException("文件不能为空");
        }
        if (StringUtils.isBlank(md5)) {
            throw new BusinessException("md5不能为空");
        }
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        return ResultUtil.ok(teStudentService.photoUpload(tbUser.getOrgId(), identity, file, md5, cover));
    }
}
