package cn.iocoder.yudao.module.iot.framework.mqtt.consumer.impl;

import cn.iocoder.yudao.module.iot.framework.mqtt.entity.MqttData;
import cn.iocoder.yudao.module.iot.service.device.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableAsync
@Slf4j
@EnableScheduling
public class AsyncService {
    @Resource
    @Lazy
    private DeviceService deviceService;


    /**地址转换进制*/
    //@Async
//	public String transferBase(MqttData data, String equipmentId) {
//		//data数据改变标记
//		boolean isTransfer = false;
//		IoPoint vo = new IoPoint();
//		vo.setEquipmentsId(equipmentId);
//		vo.setDeviceId(data.getDeviceID());
//		vo.setTransferDataType("---");
//		List<IoPoint> pointList = ioPointService.list(ioPointService.buildQueryWrapper(vo));
//		if(pointList!=null && pointList.size()>0){
//			//先转进制
//			for (IoPoint point: pointList) {
//				if(data.getDeviceData().containsKey(point.getPointCode()) && StringUtils.isNotBlank(point.getSourceDataType())){
//					String value = data.getDeviceData().get(point.getPointCode()).getV();
//					//防止有些数乱填
//					if(value.contains("."))continue;
//					if(StringUtils.isNotBlank(value) && StringUtils.isNotBlank(point.getSourceDataType())){
//						isTransfer = true;
//						value = transferBase(value,point.getSourceDataType(),point.getTransferDataType());
//						value = factor(value,point.getFactor());
//						data.getDeviceData().get(point.getPointCode()).setV(value);
//					}
//				}
//			}
//		}
//		//再进行公式计算
//		Map<String, String> valueMap = getValueMap(data);
//		vo.setTransferDataType("");
//		vo.setCalAddresses("---");
//		pointList = ioPointService.list(ioPointService.buildQueryWrapper(vo));
//		for (IoPoint point: pointList) {
//			if(data.getDeviceData().containsKey(point.getPointCode()) && StringUtils.isNotBlank(point.getCalAddresses())){
//				try {
//					isTransfer = true;
//					String result = FormulaCalculator.calFormula(point.getCalAddresses(),valueMap);
//					data.getDeviceData().get(point.getPointCode()).setV(result);
//				} catch (ScriptException e) {
//					log.error("calFormula point:"+point.toString());
//				}
//			}
//		}
//		if(isTransfer)
//			return JSON.toJSONString(data);
//		else
//			return null;
//	}

    /**
     * 系数
     **/
    private String factor(String value, String factor) {
        if (StringUtils.isNotBlank(factor)) {
            return String.format("%.2f", Double.parseDouble(value) * Double.parseDouble(factor));
        }
        return value;
    }

    private Map<String, String> getValueMap(MqttData data) {
        Map<String, String> valueMap = new HashMap<>();
        for (String key : data.getDeviceData().keySet()) {
            valueMap.put(key, data.getDeviceData().get(key).getV());
        }
        return valueMap;
    }

    /**
     * java 代码将给定的值value，从一个进制转换到另一个进制，进制取值可能为binary,octal,hexadecimal,decimal等
     */
    private String transferBase(String value, String originBase, String transferBase) {
        switch (transferBase) {
            case "decimal": {
                switch (originBase) {
                    case "binary":
                        value = convertBase(value, 2, 10);
                        break;
                    case "octal":
                        value = convertBase(value, 8, 10);
                        break;
                    case "hexadecimal":
                        value = convertBase(value, 16, 10);
                    case "hexfloat":
                        value = hexToDecimal(value);
                }
            }
            break;
            default:
                log.debug("数据未进行转换！：(value,originBase,transferBase)(" + value + "," + originBase + "," + transferBase + ")");
        }
        return value;
    }

    private static String hexToDecimal(String value) {
        return String.valueOf(Integer.parseInt(value, 16));
    }


    public static String convertBase(String value, int fromBase, int toBase) {
        return String.valueOf(Integer.parseInt(value, fromBase));
    }

    public static void main(String[] args) {
        String value = "479624"; // 要转换的值
        int fromBase = 16; // 起始进制
        int toBase = 10; // 目标进制

        String convertedValue = convertBase(value, fromBase, toBase);
        System.out.println("Converted value: " + convertedValue);


        int intValue = Integer.parseInt(value, 16); // 将十六进制字符串解析为十进制整数
        System.out.println(intValue);

        intValue = Integer.parseInt("476c", 16); // 将十六进制字符串解析为十进制整数
        System.out.println(intValue);

        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        Date date = calendar.getTime();
        long timestamp = date.getTime() / 1000; // 将时间戳转换为秒

        System.out.println("当天 00:00:00 的时间戳：" + timestamp);
    }
}
