package com.qmth.themis.task.listener.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qmth.themis.business.cache.ExamRecordCacheUtil;
import com.qmth.themis.business.cache.bean.ExamStudentCacheBean;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.MqDto;
import com.qmth.themis.business.entity.TEExam;
import com.qmth.themis.business.entity.TEExamActivity;
import com.qmth.themis.business.entity.TOeExamRecord;
import com.qmth.themis.business.enums.MqTagEnum;
import com.qmth.themis.business.service.TMRocketMessageService;
import com.qmth.themis.business.util.JacksonUtil;
import com.qmth.themis.task.enums.QuartzTaskEnum;
import com.qmth.themis.task.listener.service.MqTaskLogicService;
import com.qmth.themis.task.quartz.ExamActivityFinalPrepareTimeJob;
import com.qmth.themis.task.quartz.ExamActivityJob;
import com.qmth.themis.task.quartz.ExamStudentJob;
import com.qmth.themis.task.service.QuartzService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: mq执行逻辑 impl
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/31
 */
@Service
public class MqTaskLogicServiceImpl implements MqTaskLogicService {
    private final static Logger log = LoggerFactory.getLogger(MqTaskLogicServiceImpl.class);

    @Resource
    TMRocketMessageService tmRocketMessageService;

    @Resource
    QuartzService quartzService;

    /**
     * mq最大重试次数逻辑
     *
     * @param mqDto
     * @param key
     */
    @Override
    @Transactional
    public void execMqMaxReconsumeTime(MqDto mqDto, String key) {
        //超过最大重试次数，保存到数据库，后续可以发短信通知系统管理人员
        tmRocketMessageService.saveMqMessageError(mqDto, key);
    }

    @Override
    @Transactional
    public void execMqQuartzLogic(MqDto mqDto, String key) {
        Map<String, Object> tranMap = mqDto.getProperties();
        String oper = String.valueOf(tranMap.get(SystemConstant.OPER));
        Object o = JacksonUtil.parseJson(tranMap.get(SystemConstant.EXAM));
        String tag = mqDto.getTag();
        TEExam teExam = JSONObject.toJavaObject(JSONObject.parseObject(String.valueOf(o)), TEExam.class);
        if (Objects.equals(tag, MqTagEnum.EXAM_ACTIVITY.name())) {//考场任务
            JSONArray jsonArray = (JSONArray) JSONArray.parse(String.valueOf(mqDto.getBody()));
            for (int i = 0; i < jsonArray.size(); i++) {
                TEExamActivity teExamActivity = JSONObject.toJavaObject((JSON) jsonArray.get(i), TEExamActivity.class);
                if (Objects.equals(SystemConstant.DELETE, oper)) {
                    quartzService.deleteJob(String.valueOf(teExamActivity.getId()), QuartzTaskEnum.EXAM_ACTIVITY_JOB_GROUP_NAME.name());
                } else if (Objects.equals(SystemConstant.INSERT, oper)) {
                    quartzService.deleteJob(String.valueOf(teExamActivity.getId()), QuartzTaskEnum.EXAM_ACTIVITY_JOB_GROUP_NAME.name());
                    if (Objects.nonNull(teExam.getEnable()) && teExam.getEnable().intValue() == 1 && Objects.nonNull(teExamActivity.getEnable()) && teExamActivity.getEnable().intValue() == 1) {
                        this.setCron(teExamActivity.getFinishTime(), String.valueOf(teExamActivity.getId()), ExamActivityJob.class, QuartzTaskEnum.EXAM_ACTIVITY_JOB_GROUP_NAME);
                    }
                }
            }
        } else if (Objects.equals(tag, MqTagEnum.EXAM_STUDENT.name())) {//考生任务
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(mqDto.getBody()));
            ExamStudentCacheBean examStudentCacheBean = JSONObject.toJavaObject(jsonObject, ExamStudentCacheBean.class);
            Long recordId = Long.parseLong(String.valueOf(mqDto.getObjId()));
            if (Objects.equals(SystemConstant.DELETE, oper)) {
                quartzService.deleteJob(examStudentCacheBean.getId() + "-" + recordId, QuartzTaskEnum.EXAM_STUDENT_JOB_GROUP_NAME.name());
            } else if (Objects.equals(SystemConstant.INSERT, oper)) {
                quartzService.deleteJob(examStudentCacheBean.getId() + "-" + recordId, QuartzTaskEnum.EXAM_STUDENT_JOB_GROUP_NAME.name());
                if (Objects.nonNull(examStudentCacheBean.getEnable()) && examStudentCacheBean.getEnable().intValue() == 1) {
                    this.setCron(ExamRecordCacheUtil.getExamFinalFinishTime(recordId), examStudentCacheBean.getId() + "-" + recordId, ExamStudentJob.class, QuartzTaskEnum.EXAM_STUDENT_JOB_GROUP_NAME);
                }
            }
        } else if (Objects.equals(tag, MqTagEnum.EXAM_ACTIVITY_FINAL_PREPARE_TIME.name())) {//考场最后开考时间任务
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(mqDto.getBody()));
            TOeExamRecord tOeExamRecord = JSONObject.toJavaObject(jsonObject, TOeExamRecord.class);
            if (Objects.equals(SystemConstant.DELETE, oper)) {
                quartzService.deleteJob(String.valueOf(tOeExamRecord.getId()), QuartzTaskEnum.EXAM_ACTIVITY_FINAL_PREPARE_TIME_JOB_GROUP_NAME.name());
            } else if (Objects.equals(SystemConstant.INSERT, oper)) {
                quartzService.deleteJob(String.valueOf(tOeExamRecord.getId()), QuartzTaskEnum.EXAM_ACTIVITY_FINAL_PREPARE_TIME_JOB_GROUP_NAME.name());
                Integer openingSecondsTemp = tOeExamRecord.getOpeningSeconds();
                openingSecondsTemp = Objects.nonNull(openingSecondsTemp) && openingSecondsTemp.intValue() == 0 ? SystemConstant.DEFAULT_OPENING_SECONDS : openingSecondsTemp;
                Long finalPrepareTime = tOeExamRecord.getStartTime() + (openingSecondsTemp * 1000);
                this.setCron(finalPrepareTime, String.valueOf(tOeExamRecord.getId()), ExamActivityFinalPrepareTimeJob.class, QuartzTaskEnum.EXAM_ACTIVITY_FINAL_PREPARE_TIME_JOB_GROUP_NAME);
            }
        }
//        else if (Objects.equals(tag, MqTagEnum.EXAM_AUDIO.name())) {//考试语音
//            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(mqDto.getBody()));
//            TEAudio teAudio = JSONObject.toJavaObject(jsonObject, TEAudio.class);
//            Long examId = Long.parseLong(String.valueOf(mqDto.getObjId()));
//            if (Objects.equals(SystemConstant.DELETE, oper)) {
//                quartzService.deleteJob(teAudio.getId() + "-" + teAudio.getActivityId() + "-" + examId, QuartzTaskEnum.EXAM_AUDIO_JOB_GROUP_NAME.name());
//            } else if (Objects.equals(SystemConstant.INSERT, oper)) {
//                quartzService.deleteJob(teAudio.getId() + "-" + teAudio.getActivityId() + "-" + examId, QuartzTaskEnum.EXAM_AUDIO_JOB_GROUP_NAME.name());
//                Long execTime = (Long) tranMap.get(SystemConstant.EXEC_TIME);
//                Long realExecTime = (Long) tranMap.get(SystemConstant.REAL_EXEC_TIME);
//                this.setCron(execTime, teAudio.getId() + "-" + teAudio.getActivityId() + "-" + examId + "-" + realExecTime, ExamAudioJob.class, QuartzTaskEnum.EXAM_AUDIO_JOB_GROUP_NAME);
//            }
//        }
        tmRocketMessageService.saveMqMessageSuccess(mqDto, key);
    }

    /**
     * 设置quart cron
     *
     * @param finishTime
     * @param jobName
     * @param cls
     * @param quartzTaskEnum
     */
    public void setCron(Long finishTime, String jobName, Class cls, QuartzTaskEnum quartzTaskEnum) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(finishTime);
//                    calendar.add(Calendar.SECOND, 30);
        if (calendar.getTime().getTime() > System.currentTimeMillis()) {
            int year = calendar.get(Calendar.YEAR);//获取年份
            int month = calendar.get(Calendar.MONTH) + 1;//获取月份
            int day = calendar.get(Calendar.DATE);//获取日
            int hour = calendar.get(Calendar.HOUR_OF_DAY);//小时
            int minute = calendar.get(Calendar.MINUTE);//分
            int second = calendar.get(Calendar.SECOND);//秒
            String cron = second + " " + minute + " " + hour + " " + day + " " + month + " ? " + year;
            log.info("cron:{}", cron);
            //执行一次性延时任务
            Map mapJob = new HashMap();
            mapJob.put(SystemConstant.NAME, jobName);
            quartzService.addJob(cls, jobName, quartzTaskEnum.name(), cron, mapJob);
        }
    }
}
