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

import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
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.dal.dataobject.qhse.cert.IotMeasureCertDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.measure.IotMeasureBookDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.measure.IotMeasureDetectDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.cert.IotMeasureCertMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.measure.IotMeasureBookMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.measure.IotMeasureDetectMapper;
import cn.iocoder.yudao.module.pms.message.PmsMessage;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

@Component
public class CertJob implements JobHandler {
    @Resource
    private IotMeasureCertMapper iotMeasureCertMapper;
    @Resource
    private IotMeasureBookMapper iotMeasureBookMapper;
    @Resource
    private IotMeasureDetectMapper iotMeasureDetectMapper;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private PmsMessage pmsMessage;

    @Override
    @TenantIgnore
    @DataPermission(enable = false)
    public String execute(String param) throws Exception {
        List<IotMeasureCertDO> iotMeasureCertDOS = iotMeasureCertMapper.selectList();
        List<IotMeasureCertDO> needMessage = new ArrayList<>();
        iotMeasureCertDOS.forEach(item -> {
            LocalDateTime certExpire = item.getCertExpire();
            LocalDateTime expireMinus10Days = certExpire.minusDays(10);
            if (expireMinus10Days.isBefore(LocalDateTime.now())) {
                needMessage.add(item);
            }
            if (certExpire.isBefore(LocalDateTime.now())) {
                //证书已过期的话，更新expired为true
                item.setExpired(true);
            } else  {
                if (ChronoUnit.DAYS.between(LocalDateTime.now(), certExpire) < 60) {
                    item.setAlertWarn(true);//设置为60天预警过期
                }
                item.setExpired(false);
            }
        });
        //添加消息提醒逻辑,异步发送消息
        CompletableFuture.runAsync(() -> {
            needMessage.forEach(item -> {
                Long deptId = item.getDeptId();
                String userName = item.getUserName();
                List<AdminUserRespDTO> userListByDeptId = adminUserApi.getUserListByDeptId(deptId);
                userListByDeptId.stream().filter(e -> e.getNickname().equals(userName)).findFirst().ifPresent(adminUserRespDTO -> {
                   pmsMessage.sendMessage(item.getId(), item.getCertName(), PmsConstants.GENERATE_QHSE_CERT, adminUserRespDTO.getId(), adminUserRespDTO.getMobile());
                });
            });
        });
        iotMeasureCertMapper.updateBatch(iotMeasureCertDOS);
        //处理计量器具的检测是否过期
        List<IotMeasureBookDO> iotMeasureBookDOS1 = iotMeasureBookMapper.selectList();
        List<IotMeasureDetectDO> iotMeasureDetectDOS = iotMeasureDetectMapper.selectList();
        iotMeasureBookDOS1.forEach(item -> {
            iotMeasureDetectDOS.stream()
                    .filter(e -> e.getMeasureId().equals(item.getId()))
                    .map(IotMeasureDetectDO::getValidityPeriod) // 提取日期
                    .filter(Objects::nonNull) // 过滤掉null
                    .max(LocalDateTime::compareTo) // 取最大日期
                    .ifPresent(maxDate -> {
                        // 判断：最大日期 是否在 当前时间 之前
                        if (maxDate.isBefore(LocalDateTime.now())) {
                            item.setExpired(true);
                        }
                        //如果相差不到90天了就进行预警
                        if (maxDate.isAfter(LocalDateTime.now()) && ChronoUnit.DAYS.between(LocalDateTime.now(), maxDate) < 90) {
                            item.setAlertWarn(true);
                        }
                        iotMeasureBookMapper.updateById(item);
                    });
        });


//        List<IotMeasureDetectDO> collect = iotMeasureDetectMapper.selectList().stream().filter(e -> Objects.nonNull(e.getValidityPeriod()) && (e.getValidityPeriod().isBefore(LocalDateTime.now()))).collect(Collectors.toList());
//        if (CollUtil.isNotEmpty(collect)) {
//            Set<Long> collect1 = collect.stream().map(IotMeasureDetectDO::getMeasureId).collect(Collectors.toSet());
//            List<IotMeasureBookDO> iotMeasureBookDOS = iotMeasureBookMapper.selectByIds(collect1);
//            iotMeasureBookDOS.forEach(item -> item.setExpired(true));
//            iotMeasureBookMapper.updateBatch(iotMeasureBookDOS);
//        }
        return "执行成功";
    }
}
