package cn.iocoder.yudao.module.pms.job.alarm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.pms.constant.PmsConstants;
import cn.iocoder.yudao.module.pms.controller.admin.iotdeviceperson.vo.IotDevicePersonPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotDevicePageReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.alarm.IotAlarmSettingDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotdeviceperson.IotDevicePersonDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.tdparams.IotTdParamsDO;
import cn.iocoder.yudao.module.pms.dal.mysql.TDDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.alarm.IotAlarmSettingMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.tdparams.IotTdParamsMapper;
import cn.iocoder.yudao.module.pms.message.PmsMessage;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.iotdeviceperson.IotDevicePersonService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.util.date.DateUtils.generateTimestamp;

@Component
@Slf4j
public class AlarmJob implements JobHandler {
    @Resource
    private IotAlarmSettingMapper alarmSettingMapper;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Resource
    private TDDeviceMapper tdDeviceMapper;
    @Resource
    private PmsMessage pmsMessage;
    @Autowired
    private IotDevicePersonService iotDevicePersonService;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private IotTdParamsMapper iotTdParamsMapper;

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        //查询出所有的设置了区间阈值的设备与分类
        List<IotAlarmSettingDO> alarmSettingDOS = alarmSettingMapper.selectList();
        IotDevicePageReqVO reqVO = new IotDevicePageReqVO();
        reqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotDeviceDO> list = iotDeviceService.getIotDeviceTdPage(reqVO, null).getList();
        //获取十分钟前的时间
        DateTime tenMinute = DateUtil.offsetMinute(new Date(), -10);
        String tenMinuteString = tenMinute.toString(DatePattern.NORM_DATETIME_FORMAT);
        String now = DateUtil.now();
        Timestamp start = generateTimestamp(tenMinuteString);
        Timestamp end = generateTimestamp(now);
        List<IotDeviceDO> collect = list.stream().filter(e -> e.getIfInline() == 3).collect(Collectors.toList());
        collect.forEach(f ->{
            //调用延凡接口获取该设备的所有参数
//            List<ThingsModelDTO> tdParams = iotDeviceService.getTdParams(f);
            List<IotTdParamsDO> tdParams = iotTdParamsMapper.selectList("device_id", f.getId());
            tdParams.forEach(model ->{
                //获取设备id与属性标识相同的告警配置
                alarmSettingDOS.stream().filter(g -> g.getDeviceId().equals(f.getId())&&g.getPropertyCode().equals(model.getIdentifier())).forEach(t -> {
                    String maxValue = t.getMaxValue();
                    String minValue = t.getMinValue();
                    Integer count = tdDeviceMapper.selectRangeCount(f.getDeviceCode(), t.getPropertyCode(), start, end, maxValue, minValue);
                    if (Objects.nonNull(count)&&count == 0) {
                        //准备告警，设置该设备该属性为其他颜色
                        model.setIfAlarm("alarm");
                        iotTdParamsMapper.updateById(model);
                        IotDevicePersonPageReqVO pageReqVO = new IotDevicePersonPageReqVO();
                        pageReqVO.setDeviceIds(ImmutableList.of(f.getId()));
                        List<IotDevicePersonDO> persons = iotDevicePersonService.getPersonsByDeviceIds(pageReqVO);
                        if (CollUtil.isNotEmpty(persons)) {
                            AdminUserRespDTO user = adminUserApi.getUser(persons.get(0).getPersonId());
                            if (Objects.nonNull(user)) {
                                pmsMessage.sendMessage(f.getId(), f.getDeviceCode()+f.getDeviceName()+","+model.getModelName(), PmsConstants.ALARM_MESSAGE, user.getId(), user.getMobile());
                            }
                        }
                    }
                });
            });
        });

        return "";
    }
}
