package com.qmth.teachcloud.task.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.boot.redis.uid.RedisMachineService;
import com.qmth.distributed.print.business.entity.ExamDetail;
import com.qmth.distributed.print.business.entity.ExamPrintPlan;
import com.qmth.distributed.print.business.enums.PrintPlanStatusEnum;
import com.qmth.distributed.print.business.service.*;
import com.qmth.teachcloud.common.bean.dto.MqDto;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.service.OrgCenterDataDisposeService;
import com.qmth.teachcloud.common.service.SysConfigService;
import com.qmth.teachcloud.common.service.SysUserService;
import com.qmth.teachcloud.common.util.RedisUtil;
import com.qmth.teachcloud.task.job.service.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description: job service impl
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/3/31
 */
@Service
public class JobServiceImpl implements JobService {
    private final static Logger log = LoggerFactory.getLogger(JobServiceImpl.class);

    @Resource
    OrgCenterDataDisposeService orgCenterDataDisposeService;

    @Resource
    ExamPrintPlanService examPrintPlanService;

    @Resource
    ExamDetailService examDetailService;

    @Resource
    PrintCommonService printCommonService;

    @Autowired
    ExamTaskService examTaskService;

    @Autowired
    BasicMessageService basicMessageService;

    @Autowired
    DataSyncService dataSyncService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    RedisMachineService redisMachineService;

    @Resource
    SysUserService sysUserService;

    @Override
    public void updateSchoolInfo() throws IOException {
        orgCenterDataDisposeService.updateSchoolInfo();
    }

    /**
     * 更新印刷计划状态
     */
    @Override
    @Transactional
    public void updatePrintPlan() {
        QueryWrapper<ExamPrintPlan> examPrintPlanQueryWrapper = new QueryWrapper<>();
        examPrintPlanQueryWrapper.lambda().ne(ExamPrintPlan::getStatus, PrintPlanStatusEnum.END);
        List<ExamPrintPlan> examPrintPlanList = examPrintPlanService.list(examPrintPlanQueryWrapper);
        if (Objects.nonNull(examPrintPlanList) && examPrintPlanList.size() > 0) {
            for (ExamPrintPlan examPrintPlan : examPrintPlanList) {
                QueryWrapper<ExamDetail> examDetailQueryWrapper = new QueryWrapper<>();
                examDetailQueryWrapper.lambda().eq(ExamDetail::getPrintPlanId, examPrintPlan.getId());
                List<ExamDetail> examDetailList = examDetailService.list(examDetailQueryWrapper);
                if (Objects.nonNull(examDetailList) && examDetailList.size() > 0) {
                    Long maxEndTime = examDetailList.stream().mapToLong(i -> i.getExamEndTime()).max().getAsLong();
                    if (System.currentTimeMillis() >= maxEndTime.longValue()) {
                        examPrintPlan.setStatus(PrintPlanStatusEnum.END);
                    }
                }
            }
        }
        examPrintPlanService.saveOrUpdateBatch(examPrintPlanList);

        // 2021-05-20 同步数据到云阅卷
//        SysConfig sysConfig = sysConfigService.getByKey("sys.code.enable");
//        if (Objects.nonNull(sysConfig) && sysConfig.getConfigValue() == "true") {
//            dataSyncService.syncToCloudReview();
//        }
    }

    /**
     * 重新生成pdf失败任务
     *
     * @throws IOException
     */
    @Override
    public void resetCreatePdfTask() throws IOException {
        printCommonService.resetCreatePdfTask();
    }

    @Override
    public void sendSmsExpireTask() {
        examTaskService.sendSmsExpireTask();
    }

    @Override
    public void sendSmsOverdueTask() {
        examTaskService.sendSmsOverdueTask();
    }

    @Override
    public void resendSmsTask() {
        basicMessageService.resendSmsTask();
    }

    @Override
    public void syncData() {
        // 2021-05-20 同步数据到云阅卷
//        dataSyncService.syncToCloudReview();
    }

    @Override
    public void machineHeart() {
        redisUtil.set(SystemConstant.TASK_MACHINE_ID + redisMachineService.getMachineId(), redisMachineService.getMachineId(), 30, TimeUnit.SECONDS);
    }

    @Override
    public void autoPushUserErrorData() throws IllegalAccessException {
        sysUserService.autoPushUserErrorData();
    }

    @Override
    public void needPushAgain() throws IllegalAccessException {
        SysUser requestUser = new SysUser();
        requestUser.setId(1L);
        sysUserService.needPushAgainOperate(requestUser);
    }

    /**
     * 组装job
     *
     * @param redisKey
     */
    @Override
    public void assembleJob(String redisKey) {
        Long size = redisUtil.getHashSize(redisKey);
        if (Objects.nonNull(size) && size.longValue() > 0) {
            log.info("redisKey:{}缓冲区的消息数为:{}", redisKey, size);
            Map map = redisUtil.getHashEntries(redisKey);
            map.forEach((k, v) -> {
                MqDto mqDto = (MqDto) v;
                redisUtil.sendMessage(mqDto.getTopic(), mqDto);
            });
        }
    }
}
