package com.qmth.themis.backend.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.qmth.themis.business.annotation.ApiJsonObject;
import com.qmth.themis.business.annotation.ApiJsonProperty;
import com.qmth.themis.business.config.SystemConfig;
import com.qmth.themis.business.dto.cache.TEStudentCacheDto;
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.service.TEStudentService;
import com.qmth.themis.business.util.RedisUtil;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;

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

    @Resource
    TEStudentService teStudentService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    SystemConfig systemConfig;

    @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 = "分页页码", required = true) @RequestParam int pageNumber, @ApiParam(value = "分页数", required = true) @RequestParam int pageSize) {
        IPage<TEStudentDto> teExamStudentIPage = teStudentService.studentQuery(new Page<>(pageNumber, pageSize), identity, name, enable);
        if (teExamStudentIPage.getRecords() != null && teExamStudentIPage.getRecords().size() > 0) {
            for (TEStudentDto dto : teExamStudentIPage.getRecords()) {
                if (StringUtils.isNotBlank(dto.getBasePhotoPath())) {
                    dto.setBasePhotoPath(systemConfig.getProperty("aliyun.oss.url") + "/" + dto.getBasePhotoPath());
                }
            }
        }
        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("id")) || Objects.equals(mapParameter.get("id"), "")) {
            throw new BusinessException(ExceptionResultEnum.STUDENT_ID_IS_NULL);
        }
        Long id = Long.parseLong(String.valueOf(mapParameter.get("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);
        Gson gson = new Gson();
        TEStudentCacheDto teStudentCacheDto = gson.fromJson(gson.toJson(teStudent), TEStudentCacheDto.class);
        redisUtil.setStudent(teStudent.getId(), teStudentCacheDto);
        return ResultUtil.ok(Collections.singletonMap("success", true));
    }

    @ApiOperation(value = "学生修改密码接口")
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    @Transactional
    public Result studentUpdatePwd(@ApiJsonObject(name = "studentUpdatePwd", value = {
            @ApiJsonProperty(key = "id", type = "long", example = "1", description = "用户ID"),
            @ApiJsonProperty(key = "password", description = "新密码")
    }) @ApiParam(value = "学生信息", required = true) @RequestBody Map<String, Object> mapParameter) {
        if (Objects.isNull(mapParameter.get("id")) || Objects.equals(mapParameter.get("id"), "")) {
            throw new BusinessException(ExceptionResultEnum.STUDENT_ID_IS_NULL);
        }
        Long id = Long.parseLong(String.valueOf(mapParameter.get("id")));
        if (Objects.isNull(mapParameter.get("password")) || Objects.equals(mapParameter.get("password"), "")) {
            throw new BusinessException(ExceptionResultEnum.PASSWORD_IS_NULL);
        }
        String password = String.valueOf(mapParameter.get("password"));
        TEStudent teStudent = teStudentService.getById(id);
        if (Objects.isNull(teStudent)) {
            throw new BusinessException(ExceptionResultEnum.STUDENT_INFO_IS_NULL);
        }
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        teStudent.setPassword(password);
        teStudent.setUpdateId(tbUser.getId());
        teStudentService.updateById(teStudent);
        Gson gson = new Gson();
        TEStudentCacheDto teStudentCacheDto = gson.fromJson(gson.toJson(teStudent), TEStudentCacheDto.class);
        redisUtil.setStudent(teStudent.getId(), teStudentCacheDto);
        return ResultUtil.ok(Collections.singletonMap("success", 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", required = false) @RequestParam(required = false) Long examId, @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber, @ApiParam(value = "分页数", required = true) @RequestParam 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 = "/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) {
        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));
    }
}
