package com.tykj.dev.device.train.task;

import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.train.dao.TrainThemeDao;
import com.tykj.dev.device.train.dao.TrainUserDao;
import com.tykj.dev.device.train.entity.TrainTheme;
import com.tykj.dev.device.train.entity.TrainUser;
import com.tykj.dev.device.train.service.TrainTaskService;
import com.tykj.dev.device.train.service.TrainThemeService;
import com.tykj.dev.device.user.subject.dao.UnitsDao;
import com.tykj.dev.device.user.subject.service.MgrcertService;
import com.tykj.dev.device.user.subject.service.UserService;
import com.tykj.dev.misc.base.BusinessEnum;
import com.tykj.dev.misc.base.StatusEnum;
import com.tykj.dev.socket.MyWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName TrainTask.java
 * @Description 培训定时任务 主要是 判断报名截止以及培训开始、培训结束
 * @createTime 2020年08月17日 23:20:00
 */
@Service
@Slf4j
public class TrainTask {
    @Autowired
    TrainThemeService trainThemeService;
    @Autowired
    TaskService taskService;
    @Autowired
    MgrcertService mgrcertService;
    @Autowired
    TrainTaskService trainTaskService;
    @Autowired
    UnitsDao unitsDao;
    @Autowired
    UserService userService;
    @Autowired
    MyWebSocket myWebSocket;

    @Autowired
    TrainUserDao trainUserDao;
    @Autowired
    TrainThemeDao trainThemeDao;

    @Scheduled(cron = "0 0/1 0 * * ? ")
    private void signUpDeadline() {
        trainThemeService.findAllStatus(StatusEnum.TRAIN1000.id).forEach(
                trainTheme -> {
//                    log.info("[培训] 检查报名时间是否结束");
                    long time = new Date().getTime();
                    if (trainTheme.getTrainTime().getTime() <= time) {
//                        log.info("[培训] 检查报名时间{}",trainTheme.getTrainId());
                        signUpEnd(trainTheme.getTrainId());
                    }
                }
        );
    }

    public void signUpEnd(Integer trainId) {
        TrainTheme trainTheme = trainThemeService.findById(trainId);
        //查询所有必须报名而没有报名的task 状态直接转为待培训
        trainTaskService.selectBillidAndBillType(trainId, BusinessEnum.TRAIN_SIGN_UP.id, StatusEnum.TRAIN1002.id).forEach(
                taskBto -> {
                    taskService.moveToEnd(taskBto);
                }
        );
        //查询主task
        TaskBto taskBto = trainTaskService.selectFatherIsNullAndBillidAndBillType(trainTheme.getTrainId(), BusinessEnum.TRAIN.id);
        //主task往下推待培训状态，0
        taskService.moveToSpecial(taskBto, StatusEnum.TRAIN1010, 0);
        //5 待培训
        trainTheme.setTrainStatus(StatusEnum.TRAIN1010.id);
        trainThemeService.save(trainTheme);
    }


    @Scheduled(cron = "0 0/1 0 * * ? ")
//        @Scheduled(cron = "0/30 * * * * ? ")
    private void trainingStarted() {
        log.info("[培训] 定时去推送培训中");
        long time=new Date().getTime();
        trainThemeService.findAllStatus(StatusEnum.TRAIN1010.id).forEach(
                trainTheme -> {
                   if (trainTheme.getStartTime().getTime() <= time){
                       inTraining(trainTheme.getTrainId());
                   }
                });

    }


    private void inTraining( Integer trainId) {
        TrainTheme trainTheme = trainThemeService.findById(trainId);
        //5 培训中
        TaskBto taskBto = trainTaskService.selectFatherIsNullAndBillidAndBillType(trainTheme.getTrainId(), BusinessEnum.TRAIN.id);
//      //主task往下推待培训状态，0
        taskService.moveToSpecial(taskBto, StatusEnum.TRAIN1004, 0);
        trainTheme.setTrainStatus(StatusEnum.TRAIN1004.id);
        //判断是否为线上培训 如是 则任务发给个人 如不是 则给单位推送任务。
        if (trainTheme.getTrainType()==1) {

        }else {
            List<Integer> userIds= trainUserDao.findAllByIsSignUpAndTrainId(1,trainId).stream().map(TrainUser::getUserId).collect(Collectors.toList());
            userIds.forEach(
                    userId-> onlineLearningTask(trainId,taskBto.getId(),trainTheme.getName(),userId,taskBto.getOwnUnit())
            );
        }
        trainThemeService.save(trainTheme);
    }


    /**
     * 线上培训业务  线上学习任务生成
     */
    private TaskBto onlineLearningTask(Integer trainId, Integer parentTaskId,String title,Integer userId,Integer ownUnitId){
        List<Integer> list=new ArrayList<>();
        list.add(userId);
        TaskBto taskBto =  new TaskBto(StatusEnum.TRAIN1012.id,title , parentTaskId, ".", trainId, BusinessEnum.TRAIN_STUDY.id, ownUnitId, 0, "online", list);
        taskBto.setCreateUserId(userId);
        return taskService.start(taskBto);
    }


//    @Scheduled(cron = "10 * * * * ?")
//    private void trainingEnd1() {
//        log.info("定时启动web推送");
//        myWebSocket.sendMessage1();
//    }
}
