package com.qmth.themis.admin.api;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.themis.business.annotation.Logs;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.TBUser;
import com.qmth.themis.business.entity.TEExamCourse;
import com.qmth.themis.business.enums.FieldUniqueEnum;
import com.qmth.themis.business.enums.LogEnum;
import com.qmth.themis.business.service.TEExamCourseService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Objects;

/**
 * @Description: 考试科目 前端控制器
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/25
 */
@Api(tags = "考试科目Controller")
@RestController
@RequestMapping(SystemConstant.PREFIX_URL_ADMIN + "/exam")
@Validated
public class TEExamCourseController {
    private final static Logger log = LoggerFactory.getLogger(TEExamCourseController.class);

    @Resource
    TEExamCourseService teExamCourseService;

    @ApiOperation(value = "考试科目修改接口")
    @RequestMapping(value = "/course/save", method = RequestMethod.POST)
    @Transactional
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    @Logs(value = LogEnum.EXAM_COURSE)
    public Result save(@ApiParam(value = "考试科目信息", required = true) @RequestBody TEExamCourse teExamCourse) {
        if (Objects.isNull(teExamCourse) || Objects.equals(teExamCourse, "")) {
            throw new BusinessException(ExceptionResultEnum.COURSE_INFO_IS_NULL);
        }
        try {
            TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
            UpdateWrapper<TEExamCourse> teExamCourseUpdateWrapper = new UpdateWrapper<>();
            teExamCourseUpdateWrapper.lambda().set(TEExamCourse::getObjectiveShuffle, teExamCourse.getObjectiveShuffle())
                    .set(TEExamCourse::getOptionShuffle, teExamCourse.getOptionShuffle())
                    .set(TEExamCourse::getUpdateId, tbUser.getId())
                    .set(TEExamCourse::getUpdateTime, System.currentTimeMillis())
                    .set(TEExamCourse::getMobilePhotoUpload, teExamCourse.getMobilePhotoUpload())
                    .eq(TEExamCourse::getExamId, teExamCourse.getExamId()).eq(TEExamCourse::getCourseCode, teExamCourse.getCourseCode());
            teExamCourseService.update(teExamCourseUpdateWrapper);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw new BusinessException("机构id[" + teExamCourse.getExamId() + "]下的" + FieldUniqueEnum.convertToCode(columnStr) + "数据不允许重复插入");
            } else if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
        teExamCourseService.updateExamCourseCacheBean(teExamCourse.getExamId(), teExamCourse.getCourseCode());
        return ResultUtil.ok(true);
    }

    @ApiOperation(value = "考试科目查询接口")
    @RequestMapping(value = "/course/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = TEExamCourse.class)})
    public Result query(@ApiParam(value = "id", required = false) @RequestParam(required = false) Long id,
                        @ApiParam(value = "考试批次id", required = true) @RequestParam Long examId,
                        @ApiParam(value = "科目编码", required = false) @RequestParam(required = false) String courseCode,
                        @ApiParam(value = "科目名称", required = false) @RequestParam(required = false) String courseName,
                        @ApiParam(value = "是否已绑定试卷", required = false) @RequestParam(required = false) Integer hasPaper,
                        @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) int pageNumber,
                        @ApiParam(value = "分页数", required = true) @RequestParam @Min(1) @Max(SystemConstant.SELECT_PAGE_SIZE_MAX) int pageSize) {
        if (Objects.isNull(examId) || Objects.equals(examId, "")) {
            throw new BusinessException(ExceptionResultEnum.EXAM_ID_IS_NULL);
        }
        return ResultUtil.ok(teExamCourseService.examCourseQuery(new Page<>(pageNumber, pageSize), id, examId, courseCode, courseName, hasPaper));
    }
}
