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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.pms.controller.admin.vo.DeviceVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.YfDeviceDO;
import cn.iocoder.yudao.module.pms.dal.mysql.IotDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.TDDeviceMapper;
import cn.iocoder.yudao.module.pms.service.yanfan.YfDeviceService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class TdCronJob implements JobHandler {
    @Autowired
    private YfDeviceService yfDeviceService;
    @Resource
    private IotDeviceMapper iotDeviceMapper;
    @Autowired
    private TDDeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        List<String> codes = new ArrayList<>();
        List<YfDeviceDO> allDevice = yfDeviceService.getAllDevice();
        allDevice.forEach(d -> {
            codes.add(d.getSerialNumber());
        });
        List<IotDeviceDO> devices = iotDeviceMapper.selectByCodeIn(codes);
        for (IotDeviceDO device : devices) {
            String deviceCode = device.getDeviceCode();
            allDevice.stream().filter(e -> e.getSerialNumber().equals(deviceCode)).findFirst().ifPresent(e -> {
                device.setYfDeviceId(e.getDeviceId());
                Integer i = deviceMapper.tableIfExist(e.getSerialNumber().toLowerCase());
                if (i==1) {
                    List<DeviceVO> deviceVOS = deviceMapper.selectLastTime(e.getSerialNumber());
                    if (CollUtil.isNotEmpty(deviceVOS)) {
                        Timestamp ts = deviceVOS.get(0).getTs();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = sdf.format(ts);
                        device.setLastInlineTime(format);
                    }
                }
                if (e.getStatus()==1) {//未激活状态

                    if (StringUtils.isNotBlank(device.getLastInlineTime())) {
                        try {
                            if (DateUtils.checkIfFullDayDifference(device.getLastInlineTime())) {
                                device.setIfInline(4);
                            } else {
                                device.setIfInline(3);
                            }
                        } catch (Exception ex) {
                            throw new RuntimeException(ex.getMessage());
                        }
                    } else {
                        device.setIfInline(4);
                    }

                    Object lat = redisTemplate.opsForHash().get("TSLV:" + device.getDeviceCode(), "lat");
                    if (Objects.nonNull(lat)) {
                        JSONObject jsonObject = JSON.parseObject(lat.toString());
                        device.setLat(Double.valueOf((String) jsonObject.get("value")));
                    }
                    Object lng = redisTemplate.opsForHash().get("TSLV:" + device.getDeviceCode(), "lng");
                    if (Objects.nonNull(lng)) {
                        JSONObject jsonObject = JSON.parseObject(lng.toString());
                        device.setLng(Double.valueOf((String) jsonObject.get("value")));
                    }
                    Object online = redisTemplate.opsForHash().get("TSLV:" + device.getDeviceCode(), "online");
                    if (Objects.nonNull(online)) {
                        JSONObject jsonObject = JSON.parseObject(online.toString());
                        String value = String.valueOf(jsonObject.get("value"));
                        device.setIfInline("true".equals(value)?3:4);
                    }
                } else {
                        if (StringUtils.isNotBlank(device.getLastInlineTime())) {
                            if (DateUtils.checkIfFullDayDifference(device.getLastInlineTime())) {
                                device.setIfInline(4);
                            } else {
                                device.setIfInline(e.getStatus());
                            }
                        } else {
                            device.setIfInline(4);
                        }
                    }
                iotDeviceMapper.updateTdCron(device);
            });
        }
//        iotDeviceMapper.updateBatch(devices);
        return "";
    }


    public static void main(String[] args) {
        String abc = "2026-01-21 10:25:40";
        System.out.println(DateUtils.checkIfFullDayDifference(abc));
    }
}
