package org.jeecg.modules.job;

import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.entity.BuMaintenanceHistory;
import org.jeecg.modules.device.entity.BuMaintenanceStatus;
import org.jeecg.modules.device.service.IBuDeviceService;
import org.jeecg.modules.device.service.IBuMaintenanceHistoryService;
import org.jeecg.modules.device.service.IBuMaintenanceStatusService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

public class DeviceMaintenanceJob implements Job {

    @Autowired
    private IBuMaintenanceStatusService buMaintenanceStatusService;
    @Autowired
    private IBuDeviceService buDeviceService;
    @Autowired
    private IBuMaintenanceHistoryService buMaintenanceHistoryService;

//    private String parameter;
//
//    public void setParameter(String parameter) {
//        this.parameter = parameter;
//    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<BuMaintenanceStatus> buMaintenanceStatuss = buMaintenanceStatusService.list();
        Date nowTime = new Date();
        for (BuMaintenanceStatus list : buMaintenanceStatuss){
            Date time = list.getUpdateTime();//上次维保时间
            long count = Integer.parseInt(list.getTimeLimit());
            long difference = nowTime.getTime() - time.getTime();//获取上次维保到现在的时差
            long value = count * 24 * 60 * 1000;
            if (difference > value) {//判断是否大于设置的维保时间限制
//                LocalDate localDate = nowTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//                Date newTime = java.sql.Date.valueOf(localDate);
//                list.setUpdateTime(newTime);
//                buMaintenanceStatusService.updateById(list);
                BuDevice buDevice = buDeviceService.getById(list.getDeviceId());
                //需新增提醒机制，放在后台通知页面，还是大屏页面待定
                BuMaintenanceHistory buMaintenanceHistory = new BuMaintenanceHistory();
                buMaintenanceHistory.setStatus(0);
                buMaintenanceHistory.setDeviceId(list.getDeviceId());
                buMaintenanceHistory.setDeviceCode(list.getDeviceCode());
                buMaintenanceHistory.setDeviceType(list.getDeviceType());
                buMaintenanceHistory.setSender("admin");
//                buMaintenanceHistory.setSendTime(new Date());
                buMaintenanceHistory.setMsgContent(buDevice.getDeviceName() + "已经达到维保期限，请尽快安排维保工作！");
                buMaintenanceHistory.setSpare("设备维保提醒");
                buMaintenanceHistoryService.save(buMaintenanceHistory);
            }
        }


    }
}
