package com.yfd.monitor.conf;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.yfd.monitor.conf.exception.ControllerException;
import com.yfd.monitor.gdw2019.bean.Device;
import com.yfd.monitor.gdw2019.bean.DeviceChannel;
import com.yfd.monitor.gdw2019.transmit.cmd.impl.SIPCommander;
import com.yfd.monitor.storager.dao.DeviceChannelMapper;
import com.yfd.monitor.storager.dao.DeviceMapper;
import com.yfd.monitor.vmanager.bean.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sip.InvalidArgumentException;
import javax.sip.SipException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 动态定时任务
 */
@Component
public class MyCustomTask {
    @Autowired
    private SIPCommander cmder;

    @Autowired
    private DeviceChannelMapper channelMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    private static final Logger logger = LoggerFactory.getLogger(MyCustomTask.class);
    /**
     * 每天中午定时执行，更新录像时长 0 50 13 * 6 1   0 30 12 * * ?
     */
    @Scheduled(cron=" 0 30 12 * * ?")
    public void updateRecordTimes(){
        List<DeviceChannel> channels= channelMapper.queryChannelByOnLineNvr();
        String endTime= DateUtil.now();
        String startTime=DateUtil.format(DateUtil.offsetDay(DateUtil.date(),-90),"yyyy-MM-dd HH:mm:ss");
        try {
            for (DeviceChannel channel : channels) {
               Device device = deviceMapper.getDeviceByDeviceId(channel.getDeviceId());//获取录像机
               cmder.recordInfoQuery(device, channel.getChannelId(), startTime, endTime, 9999, null, null, null, null);
            }

        } catch (InvalidArgumentException | SipException | ParseException e) {
            logger.error("[命令发送失败] 查询录像: {}", e.getMessage());
            throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
        }
    }

    /**
     * 每分钟定时检测摄像头是否需要回归预置位
     */
    @Scheduled(cron="10 0/1 * * * ?")
    public void callPresetPos(){
        List<Map> devices= deviceMapper.getRiisPatrolDevices();
        try {
            for (Map map : devices) {
                if(ObjUtil.isNotEmpty(map.get("preset")) && ObjUtil.isNotEmpty(map.get("presettime")) && ObjUtil.isNotEmpty(map.get("changepresettime"))){
                    int  presettime=Integer.parseInt(map.get("presettime").toString());
                    String changepresettime=map.get("changepresettime").toString();
                    Date nextdate=DateUtil.offsetMinute(DateUtil.parse(changepresettime,"yyyy-MM-dd HH:mm:ss"),presettime);
                    logger.info("nextdate:"+DateUtil.format(nextdate,"yyyy-MM-dd HH:mm:ss"));
                    logger.info("nowdate:"+DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"));
                    if(DateUtil.date().isAfter(nextdate)){
                        Device patroldevice = deviceMapper.getDeviceByDeviceId(map.get("patroldevice_code").toString());
                        List<DeviceChannel> channels= channelMapper.queryAllChannels(map.get("patroldevice_code").toString());//获取一个默认通道
                        if(channels.size()>0){
                            cmder.frontEndCmd(patroldevice,channels.get(0).getChannelId() , 130, 0, Integer.parseInt(map.get("preset").toString()),0);
                            deviceMapper.updatePatroldeviceTime(map.get("patroldevice_code").toString(),"");
                        }
                   }
               }
           }
       } catch (InvalidArgumentException | SipException | ParseException e) {
            logger.error("[命令发送失败] 调用守望位回归: {}", e.getMessage());
            throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
        }
    }
}
