package com.artfess.xqxt.meeting.schedule;

import com.artfess.base.util.StringUtil;
import com.artfess.file.util.DeleteFileUtil;
import com.artfess.redis.util.RedisUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.param.DictModel;
import com.artfess.xqxt.meeting.dao.MeetingDao;
import com.artfess.xqxt.meeting.m900.bean.ConferenceStatus;
import com.artfess.xqxt.meeting.m900.response.GetConferenceStatusResponse;
import com.artfess.xqxt.meeting.manager.MeetingManager;
import com.artfess.xqxt.meeting.manager.ZTEManager;
import com.artfess.xqxt.meeting.model.Meeting;
import com.artfess.xqxt.meeting.utils.BizUtil;
import com.artfess.xqxt.meeting.vo.HistoryConferenceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
@Slf4j
public class Schedule {

    @Resource
    MeetingDao meetingDao;
    @Resource
    MeetingManager meetingManager;
    @Resource
    SysDictionaryManager sysDictionaryManager;
    @Resource
    ZTEManager zteManager;

    @Resource
    RedisUtil redisUtil;

    private static String KEY_  = "MEETING_SEND_KEY";

    private static int THRESHOLD = 1000;

    /**
     * 企业微信端消息推送，根据会议中选项进行推送消息，如果没有消息推送时间选项，将在五分钟的时候进行提醒
     *
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void send(){
        log.info("\n------------------------------\t定时任务【企业微信通知推送】执行---开始-------------------------------\n" );
        System.out.println("*******************************定时会议通知开始****************************");
        List<Meeting> sendList = meetingDao.select4SendMsg();
        if (sendList.size()<=0) return;
        Long nowTime = new Date().getTime();
        for (Meeting meeting : sendList){
            Long startTime = meeting.getStartTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            if(StringUtil.isEmpty(meeting.getRemindTime())){
                //  会议开始时通知
                Long senTime = nowTime-startTime;
                if ( senTime <= 30000 && senTime >= 0){
                    meetingManager.sendMsg(meeting,4);
                    break;
                }
            }
            List<String> list = Arrays.asList(meeting.getRemindTime().split(","));
            Long sendTime = 0L;
            if(list.contains("2")){
                //  会议开始时通知
                sendTime = startTime;
                Long senTime = nowTime-sendTime;
                if ( senTime <= 30000 && senTime >= 0){
                    meetingManager.sendMsg(meeting,4);
                }
            }
            if(list.contains("3")){
                // 5分钟的时候
                sendTime = startTime-5*60*1000;
                Long senTime = nowTime-sendTime;
                if ( senTime <= 30000 && senTime >= 0){
                    meetingManager.sendMsg(meeting,4);
                }
            }
            if(list.contains("3")){
                // 10分钟
                sendTime = startTime-15*60*1000;
                Long senTime = nowTime-sendTime;
                if ( senTime <= 30000 && senTime >= 0){
                    meetingManager.sendMsg(meeting,4);
                }
            }
            if(list.contains("5")){
                // 1小时
                sendTime = startTime-60*60*1000;
                Long senTime = nowTime-sendTime;
                if ( senTime <= 30000 && senTime >= 0){
                    meetingManager.sendMsg(meeting,4);
                }
            }
            if(list.contains("6")){
                // 已弃用
                sendTime = startTime-24*60*60*1000;
                Long senTime = nowTime-sendTime;
                if ( senTime <= 30000 && senTime >= 0){
                    meetingManager.sendMsg(meeting,4);
                }
            }
            System.out.println("*******************************定时会议通知结束****************************");
        }
        log.info("\n------------------------------\t定时任务【企业微信通知推送】执行---结束-------------------------------\n" );
        Object o = redisUtil.get(KEY_);
        if(null == o){
            redisUtil.set(KEY_, 1);
        }else {
            Integer num = (Integer)o;
            if(num > THRESHOLD){
                System.gc();
                num = 0;
            }
            num ++;
            redisUtil.set(KEY_, num);
        }
        sendList = null;
        nowTime = null;
    }

    /**
     * 会议状态修改，
     * 1.将未开始的会议根据时间修改为进行中
     * 2.将一开始的会议根据结束时间修改为已结束
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void updateStatus(){
        log.info("\n------------------------------\t定时任务【会议状态修改】执行---开始-------------------------------\n" );
        //未开始会议
        List<Meeting> list = meetingDao.selectByStatus(1);
        LocalDateTime now = LocalDateTime.now();
        for (Meeting meeting : list){
            Duration duration = Duration.between(now, meeting.getStartTime());
            long millis = duration.toMillis();
            if (now.isAfter(meeting.getStartTime()) || now.isEqual(meeting.getStartTime()) || millis < (1000*30)){
                meetingManager.updateStatusOver(meeting,2);
            }
        }
        //已开始会议
        List<Meeting> runList = meetingDao.selectByStatus(2);
        for (Meeting meeting : runList){
            if (meeting.getMeetingType()==1) {
                if (now.isAfter(meeting.getEndTime()) || now.isEqual(meeting.getEndTime())) {
                    meetingManager.updateStatusOver(meeting, 3);
                }
            } else if (meeting.getMeetingType()==2){
//                LocalDateTime endTime = meeting.getEndTime();
                if (now.isAfter(meeting.getEndTime()) || now.isEqual(meeting.getEndTime())) {
                    meetingManager.updateStatusOver(meeting, 3);
                }else {
                    if(StringUtil.isNotEmpty(meeting.getConferenceNumber())){
                        HistoryConferenceVO historyConferenceVO = new  HistoryConferenceVO();
                        historyConferenceVO.setConferenceNumber(meeting.getConferenceNumber());
                        historyConferenceVO.setPage(1);
                        historyConferenceVO.setNumPerPage(10);
                        historyConferenceVO.setOption(1);
                        List<ConferenceStatus> historyConferenceList = zteManager.getHistoryConferenceList(historyConferenceVO);
                        if(null != historyConferenceList && historyConferenceList.size() > 0){
                            meetingManager.updateStatusOver(meeting, 3);
                        }
                    }
                }
            }
        }
        log.info("\n------------------------------\t定时任务【会议状态修改】执行---结束-------------------------------\n" );
        Object o = redisUtil.get(KEY_);
        if(null == o){
            redisUtil.set(KEY_, 1);
        }else {
            Integer num = (Integer)o;
            if(num > THRESHOLD){
                System.gc();
                num = 0;
            }
            num ++;
            redisUtil.set(KEY_, num);
        }
        list = null;
        now = null;
        runList = null;
    }


    /**
     * 从中兴会控平台同步待开会议列表，测试环境下需要关闭定时任务，测试环境下注释中兴调用
     */
//    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional
    public void synMeetingByZte(){
        log.info("\n------------------------------\t定时任务【中兴会议列表数据同步】执行---开始-------------------------------\n" );
        log.info("\n------------------------------\t定时任务【同步正在进行的会议任务】执行.........\n" );
        meetingManager.synConferenceInfo();
        log.info("\n------------------------------\t定时任务【同步预约的会议任务】执行.........\n" );
        meetingManager.synConferenceReserved();
        log.info("\n------------------------------\t定时任务【中兴会议列表数据同步】执行---结束-------------------------------\n" );
    }
}
