package com.qmth.themis.backend.api;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.backend.InvigilateListWarningBean;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.AuthDto;
import com.qmth.themis.business.dto.response.TIeWarningNotifyDto;
import com.qmth.themis.business.entity.TBUser;
import com.qmth.themis.business.entity.TIeInvigilateWarnInfo;
import com.qmth.themis.business.enums.RoleEnum;
import com.qmth.themis.business.service.TIeInvigilateWarnInfoService;
import com.qmth.themis.business.service.TOeExamRecordService;
import com.qmth.themis.business.util.RedisUtil;
import com.qmth.themis.business.util.ServletUtil;
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.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}/invigilate/warn")
public class TIeInvigilateWarnInfoController {

    @Resource
    RedisUtil redisUtil;

    @Resource
    TIeInvigilateWarnInfoService tIeInvigilateWarnInfoService;

    @Resource
    TOeExamRecordService tOeExamRecordService;

    @ApiOperation(value = "预警提醒接口")
    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "{\"count\":1}", response = Result.class)})
    public Result notify(@ApiParam(value = "考试批次id", required = false) @RequestParam(required = false) Long examId,
                         @ApiParam(value = "考试场次id", required = false) @RequestParam(required = false) Long examActivityId,
                         @ApiParam(value = "虚拟考场代码", required = false) @RequestParam(required = false) String roomCode) {
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.userOauth + "::" + tbUser.getId());
        //如果有监考员角色，只能查看自己所监考的考场，巡考员和管理员则可以查看全部考场
        Long userId = null;
        if (authDto.getRoleCodes().toString().contains(RoleEnum.INVIGILATE.name())) {
            userId = tbUser.getId();
        }
        Integer count = tIeInvigilateWarnInfoService.warningCount(examId, examActivityId, roomCode, userId);
        return ResultUtil.ok(Collections.singletonMap(SystemConstant.COUNT, count));
    }

    @ApiOperation(value = "预警提醒列表接口")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "监考预警信息", response = InvigilateListWarningBean.class)})
    public Result list(@ApiParam(value = "考试批次id", required = false) @RequestParam(required = false) Long examId,
                       @ApiParam(value = "考试场次id", required = false) @RequestParam(required = false) Long examActivityId,
                       @ApiParam(value = "虚拟考场代码", required = false) @RequestParam(required = false) String roomCode,
                       @ApiParam(value = "审阅状态", required = false) @RequestParam(required = false) Integer approveStatus,
                       @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String name,
                       @ApiParam(value = "证件号", required = false) @RequestParam(required = false) String identity,
                       @ApiParam(value = "陌生人脸min", required = false) @RequestParam(required = false) Integer minMultipleFaceCount,
                       @ApiParam(value = "陌生人脸max", required = false) @RequestParam(required = false) Integer maxMultipleFaceCount,
                       @ApiParam(value = "异常处理min", required = false) @RequestParam(required = false) Integer minExceptionCount,
                       @ApiParam(value = "异常处理max", required = false) @RequestParam(required = false) Integer maxExceptionCount,
                       @ApiParam(value = "预警量min", required = false) @RequestParam(required = false) Integer minWarningCount,
                       @ApiParam(value = "预警量max", required = false) @RequestParam(required = false) Integer maxWarningCount,
                       @ApiParam(value = "客户端网络通信状态", required = false) @RequestParam(required = false) String clientWebsocketStatus,
                       @ApiParam(value = "监控设备通信状态", required = false) @RequestParam(required = false) String monitorStatusSource,
                       @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber,
                       @ApiParam(value = "分页数", required = true) @RequestParam int pageSize) {
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.userOauth + "::" + tbUser.getId());
        //如果有监考员角色，只能查看自己所监考的考场，巡考员和管理员则可以查看全部考场
        Long userId = null;
        if (authDto.getRoleCodes().toString().contains(RoleEnum.INVIGILATE.name())) {
            userId = tbUser.getId();
        }
        return ResultUtil.ok(tOeExamRecordService.invigilatePageWarningList(new Page<>(pageNumber, pageSize), examId, examActivityId, roomCode, approveStatus, name, identity, minMultipleFaceCount, maxMultipleFaceCount, minExceptionCount, maxExceptionCount, minWarningCount, maxWarningCount, clientWebsocketStatus, monitorStatusSource, userId));
    }

    @ApiOperation(value = "预警消息接口")
    @RequestMapping(value = "/message", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "预警通知信息", response = TIeWarningNotifyDto.class)})
    public Result warningMessage(@ApiParam(value = "考试批次id", required = false) @RequestParam(required = false) Long examId) {
        TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
        AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.userOauth + "::" + tbUser.getId());
        //如果有监考员角色，只能查看自己所监考的考场，巡考员和管理员则可以查看全部考场
        Long userId = null;
        if (authDto.getRoleCodes().toString().contains(RoleEnum.INVIGILATE.name())) {
            userId = tbUser.getId();
        }
        return ResultUtil.ok(tIeInvigilateWarnInfoService.warningMessage(examId, userId, tbUser.getOrgId()));
    }

    @ApiOperation(value = "预警修改阅读状态接口")
    @RequestMapping(value = "/save/status", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
    @Transactional
    public Result saveWarnStatus(@ApiJsonObject(name = "saveWarnStatus", value = {
            @ApiJsonProperty(key = "warningIds", description = "预警id数组", required = true),
            @ApiJsonProperty(key = "approveStatus", type = "long", example = "1", description = "审阅状态，0：未阅，1：已阅", required = true)
    }) @ApiParam(value = "监考员信息", required = true) @RequestBody Map<String, Object> mapParameter) {
        if (Objects.isNull(mapParameter.get("warningIds")) || Objects.equals(mapParameter.get("warningIds"), "")) {
            throw new BusinessException("预警id不能为空");
        }
        List<String> warningIds = (List<String>) mapParameter.get("warningIds");
        if (warningIds.size() > 0) {
            if (Objects.isNull(mapParameter.get("approveStatus")) || Objects.equals(mapParameter.get("approveStatus"), "")) {
                throw new BusinessException("审阅状态不能为空");
            }
            List<Long> warningTranIds = new ArrayList<>();
            warningIds.forEach(s -> {
                warningTranIds.add(Long.parseLong(s));
            });
            Integer approveStatus = Integer.parseInt(String.valueOf(mapParameter.get("approveStatus")));
            UpdateWrapper<TIeInvigilateWarnInfo> tIeInvigilateWarnInfoUpdateWrapper = new UpdateWrapper<>();
            tIeInvigilateWarnInfoUpdateWrapper.lambda().set(TIeInvigilateWarnInfo::getApproveStatus, approveStatus)
                    .in(TIeInvigilateWarnInfo::getId, warningTranIds);
            tIeInvigilateWarnInfoService.update(tIeInvigilateWarnInfoUpdateWrapper);
        }
        return ResultUtil.ok(Collections.singletonMap("success", true));
    }
}
