package com.mortals.xhx.daemon.task;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.base.framework.ws.message.SendToAllRequest;
import com.mortals.xhx.base.framework.ws.message.UserJoinNoticeRequest;
import com.mortals.xhx.base.framework.ws.util.WebSocketUtil;
import com.mortals.xhx.common.code.DeviceOnlineStatusEnum;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.module.device.model.DeviceLogEntity;
import com.mortals.xhx.module.device.model.DeviceLogQuery;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * 设备状态任务
 *
 * @author: zxfei
 * @date: 2022/3/9 15:19
 */
@CommonsLog
@Service("DeviceStatTask")
public class DeviceStatTaskImpl implements ITaskExcuteService {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceLogService deviceLogService;


    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("设备状态统计，开始执行");
        doDeviceUpOrDown();
        doDeviceLogDel();
        log.info("设备状态统计，结束执行");
    }

    /**
     * 统计更新设备状态
     */
    private void doDeviceUpOrDown() {
        int timeout = GlobalSysInfo.getParamIntValue(ParamKey.SYS_PARAM_HEADBEAT_TIMEOUT, 60) * 1000;

        try {
            //获取所有设备，针对每个设备查询最近指定秒的日志，如果没有则更新下线
            deviceService.getCacheList().stream()
                    .filter(f -> f.getDeviceOnlineStatus() == DeviceOnlineStatusEnum.在线.getValue())
                    .peek(device -> {
                        DeviceLogQuery query = new DeviceLogQuery();

                        query.setCreateTimeStart(DateUtils.getStrDateTime(new Date(System.currentTimeMillis() - timeout)));
                        DeviceLogEntity deviceLogEntity = deviceLogService.selectOne(query);
                        if (ObjectUtils.isEmpty(deviceLogEntity)) {
                            //更新设备下线
                            device.setOfflineTime(new Date());
                            device.setDeviceOnlineStatus(DeviceOnlineStatusEnum.离线.getValue());
                            deviceService.update(device);

                            WebSocketUtil.broadcast(SendToAllRequest.TYPE,new SendToAllRequest().setContent(JSON.toJSONString(device)));

                        }
                    }).count();
        } catch (Exception e) {
            log.error("更新设备状态任务异常，结束执行", e);
        }
        log.info("更新设备状态任务，结束执行");
    }


    /**
     * 定时清除设备日志
     */
    private void doDeviceLogDel() {
        //默认保存30天日志
        int timeout = -GlobalSysInfo.getParamIntValue(ParamKey.SYS_PARAM_LOG_TIME, 30);
        try {
            DeviceLogQuery query = new DeviceLogQuery();
            query.setCreateTimeEnd(DateUtils.getStrDateTime(DateUtils.addCurrDate(timeout)));
            Long[] ids = deviceLogService.find(query).stream().map(DeviceLogEntity::getId).toArray(Long[]::new);
            if (!ObjectUtils.isEmpty(ids)) {
                deviceLogService.remove(ids, null);
            }
        } catch (Exception e) {
            log.error("设备日志删除任务异常，结束执行", e);
        }
        log.info("设备日志删除任务，结束执行");
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }


}
