package com.qmth.themis.exam.websocketTemplete;

import com.alibaba.fastjson.JSONObject;
import com.qmth.themis.business.cache.ExamRecordCacheUtil;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.WebsocketDto;
import com.qmth.themis.business.enums.MonitorVideoSourceEnum;
import com.qmth.themis.business.enums.WebsocketTypeEnum;
import com.qmth.themis.business.service.TOeExamRecordService;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description: 考生端oe websocket模版
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/24
 */
@Component
public class WebSocketOeMessageTemplete {
    private final static Logger log = LoggerFactory.getLogger(WebSocketOeMessageTemplete.class);

    @Resource
    TOeExamRecordService tOeExamRecordService;

//    /**
//     * 客户端已下载试卷
//     *
//     * @param body
//     * @param time
//     * @return
//     */
//    @Deprecated
//    @Transactional
//    public WebsocketDto clientPaperDownload(String body, Long time) {
//        JSONObject jsonObject = JSONObject.parseObject(body);
//        log.info("clientPaperDownload jsonObject:{}", jsonObject.toJSONString());
//        if (Objects.isNull(jsonObject.get("recordId")) || Objects.equals(jsonObject.get("recordId"), "")) {
//            throw new BusinessException(ExceptionResultEnum.RECORD_ID_IS_NULL);
//        }
//        Long recordId = Long.parseLong(String.valueOf(jsonObject.get("recordId")));
//        Long examId = ExamRecordCacheUtil.getExamId(recordId);
//        if (Objects.isNull(examId)) {
//            throw new BusinessException(ExceptionResultEnum.NOT_FOUND_EXAM_RECORD);
//        }
//        ExamRecordCacheUtil.setPaperDownload(recordId, 0);
//        return new WebsocketDto(true);
//    }

    /**
     * 状态同步
     *
     * @param body
     * @param time
     * @return
     */
    @Transactional
    public WebsocketDto syncStatus(String body, Long time) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        log.info("syncStatus jsonObject:{}", jsonObject.toJSONString());
        if (Objects.isNull(jsonObject.get(SystemConstant.RECORD_ID)) || Objects.equals(jsonObject.get(SystemConstant.RECORD_ID), "")) {
            throw new BusinessException(ExceptionResultEnum.RECORD_ID_IS_NULL);
        }
        Long recordId = Long.parseLong(String.valueOf(jsonObject.get(SystemConstant.RECORD_ID)));
        if (Objects.isNull(jsonObject.get("progress")) || Objects.equals(jsonObject.get("progress"), "")) {
            throw new BusinessException("答题进度不能为空");
        }
        Double progress = Double.parseDouble(String.valueOf(jsonObject.get("progress")));
        if (Objects.isNull(jsonObject.get("durationSeconds")) || Objects.equals(jsonObject.get("durationSeconds"), "")) {
            throw new BusinessException("考试累计用时秒数不能为空");
        }
        Integer durationSeconds = Integer.parseInt((String.valueOf(jsonObject.get("durationSeconds"))));
        Long examId = ExamRecordCacheUtil.getExamId(recordId);
        if (Objects.isNull(examId)) {
            throw new BusinessException(ExceptionResultEnum.NOT_FOUND_EXAM_RECORD);
        }
        ExamRecordCacheUtil.setAnswerProgress(recordId, progress);
        ExamRecordCacheUtil.setDurationSeconds(recordId, durationSeconds);
        Long clientLastSyncTime = System.currentTimeMillis();
        ExamRecordCacheUtil.setClientLastSyncTime(recordId, clientLastSyncTime);
        tOeExamRecordService.sendExamRecordDataSaveMq(recordId, clientLastSyncTime);
        return this.syncAck(body, time);
    }

    /**
     * 同步确认
     *
     * @param body
     * @param time
     * @return
     */
    public WebsocketDto syncAck(String body, Long time) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        Long recordId = Long.parseLong(String.valueOf(jsonObject.get(SystemConstant.RECORD_ID)));
        Map<String, Object> map = new LinkedHashMap<>();
        map.put(SystemConstant.RECORD_ID, recordId);
        map.put(SystemConstant.ACK_MESSAGE, time);
        String monitorVideoSource = ExamRecordCacheUtil.getMonitorVideoSource(recordId);
        List<String> monitorVideoSourceList = null;
        if (Objects.nonNull(monitorVideoSource) && !Objects.equals(monitorVideoSource.trim().replaceAll(" ", ""), "")) {
            monitorVideoSourceList = Arrays.asList(monitorVideoSource.trim().toUpperCase().replaceAll(" ", "").split(","));
        }
        if (Objects.nonNull(monitorVideoSourceList) && monitorVideoSourceList.size() > 0 && monitorVideoSourceList.contains(MonitorVideoSourceEnum.MOBILE_FIRST.name())) {
            map.put(MonitorVideoSourceEnum.MOBILE_FIRST.name().toLowerCase(), ExamRecordCacheUtil.getMonitorStatus(recordId, MonitorVideoSourceEnum.MOBILE_FIRST));
        }
        if (Objects.nonNull(monitorVideoSourceList) && monitorVideoSourceList.size() > 0 && monitorVideoSourceList.contains(MonitorVideoSourceEnum.MOBILE_SECOND.name())) {
            map.put(MonitorVideoSourceEnum.MOBILE_SECOND.name().toLowerCase(), ExamRecordCacheUtil.getMonitorStatus(recordId, MonitorVideoSourceEnum.MOBILE_SECOND));
        }
        return new WebsocketDto(WebsocketTypeEnum.convertToName(Thread.currentThread().getStackTrace()[1].getMethodName()), map);
    }

    /**
     * 监考消息确认
     *
     * @param body
     * @param time
     * @return
     */
    public WebsocketDto invigilateNoticeAck(String body, Long time) {
        return new WebsocketDto(WebsocketTypeEnum.convertToName(Thread.currentThread().getStackTrace()[1].getMethodName()), Collections.singletonMap(SystemConstant.ACK_MESSAGE, time));
    }
}
