package com.qmth.themis.backend.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.themis.business.dto.MqDto;
import com.qmth.themis.business.entity.TBUser;
import com.qmth.themis.business.entity.TEExam;
import com.qmth.themis.business.entity.TEExamActivity;
import com.qmth.themis.business.enums.FieldUniqueEnum;
import com.qmth.themis.business.enums.MqTagEnum;
import com.qmth.themis.business.enums.MqTopicEnum;
import com.qmth.themis.business.service.MqDtoService;
import com.qmth.themis.business.service.TEExamActivityService;
import com.qmth.themis.business.service.TEExamService;
import com.qmth.themis.business.util.JacksonUtil;
import com.qmth.themis.business.util.RedisUtil;
import com.qmth.themis.business.util.ServletUtil;
import com.qmth.themis.common.contanst.Constants;
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.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 考试场次 前端控制器
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/25
 */
@Api(tags = "考试场次Controller")
@RestController
@RequestMapping("/${prefix.url.admin}/activity")
public class TEExamActivityController {
    private final static Logger log = LoggerFactory.getLogger(TEExamActivityController.class);

    @Resource
    TEExamActivityService teExamActivityService;

    @Resource
    MqDtoService mqDtoService;

    @Resource
    TEExamService teExamService;

    @Resource
    RedisUtil redisUtil;

    @ApiOperation(value = "考试场次修改/新增接口")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @Transactional
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    public Result save(@ApiParam(value = "考试场次信息", required = true) @RequestBody List<TEExamActivity> teExamActivityList) {
        if (Objects.isNull(teExamActivityList) || teExamActivityList.size() == 0) {
            throw new BusinessException(ExceptionResultEnum.EXAM_INFO_IS_NULL);
        }
        Long examId = null;
        try {
            TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
            teExamActivityList.forEach(s -> {
                if (Objects.nonNull(s.getId())) {
                    s.setUpdateId(tbUser.getId());
                } else {
                    s.setId(Constants.idGen.next());
                    s.setCreateId(tbUser.getId());
                    s.setCode(String.valueOf(redisUtil.getRedisActivityCodeSequence(s.getExamId())));
                }
                teExamActivityService.saveOrUpdate(s);
            });
            examId = teExamActivityList.get(0).getExamId();
            for(TEExamActivity ac:teExamActivityList){
                teExamActivityService.updateExamActivityCacheBean(ac.getId());
            }
            TEExam teExam = teExamService.getById(teExamActivityList.get(0).getExamId());
            if (Objects.nonNull(teExam.getForceFinish()) && teExam.getForceFinish().intValue() == 1) {
                //新增quartz任务,发送mq消息start
                Map<String, Object> prop = new HashMap<>();
                prop.put("oper", "insert");
                prop.put("exam", teExam);
                MqDto mqDto = new MqDto(MqTopicEnum.THEMIS_TOPIC.getCode(), MqTagEnum.EXAM_ACTIVITY.name(), JacksonUtil.parseJson(teExamActivityList), MqTagEnum.EXAM_ACTIVITY, String.valueOf(teExam.getId()), prop, tbUser.getName());
                mqDtoService.assembleSendOneWayMsg(mqDto);
                //新增quartz任务,发送mq消息end
            }
        } catch (Exception e) {
            log.error("请求出错", e);
            if (Objects.nonNull(examId) && Objects.nonNull(teExamActivityList) && (Objects.nonNull(teExamActivityList) && teExamActivityList.size() > 0 && Objects.nonNull(teExamActivityList.get(0)))) {
                redisUtil.setRedisActivityCodeSequence(examId, Integer.parseInt(teExamActivityList.get(0).getCode()) - 1);
            }
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw new BusinessException("机构id[" + teExamActivityList.get(0).getExamId() + "]下的" + FieldUniqueEnum.convertToCode(columnStr) + "数据不允许重复插入");
            } else if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
        return ResultUtil.ok(Collections.singletonMap("success", true));
    }

    @ApiOperation(value = "考试场次查询接口")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试场次信息", response = TEExamActivity.class)})
    public Result query(@ApiParam(value = "主键", required = false) @RequestParam(required = false) Long id, @ApiParam(value = "考试批次id", required = false) @RequestParam(required = false) Long examId, @ApiParam(value = "考试场次编码", required = false) @RequestParam(required = false) String code, @ApiParam(value = "开始日期", required = false) @RequestParam(required = false) Long startDate, @ApiParam(value = "结束日期", required = false) @RequestParam(required = false) Long finishDate, @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber, @ApiParam(value = "分页数", required = true) @RequestParam int pageSize) {
        return ResultUtil.ok(teExamActivityService.examActivityQuery(new Page<>(pageNumber, pageSize), id, examId, code, startDate, finishDate));
    }
}
