package com.malk.tonglibo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.malk.server.common.McR;
import com.malk.tonglibo.Mapper.MachineDataMapper;
import com.malk.tonglibo.entity.MachineData;
import com.malk.tonglibo.entity.RawDeviceData;
import com.malk.tonglibo.utils.DataBuffer;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 功能：
 * 作者：hanxue
 * 日期：2025/9/15 11:35
 */
@RestController
@RequestMapping
@Slf4j
public class machineController {

    @Autowired
    private DataBuffer dataBuffer;
    @Autowired
    private MachineDataMapper machineDataMapper;
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    /**
     * 同步设备数据
     * @param
     */

    @PostMapping("/device/data")
    public McR deviceData(@RequestBody String paramsStr){
        try {
            log.info("设备数据paramsStr：{}", paramsStr);
            String fixedStr = repairMalformedKFields(paramsStr);
            JSONObject params = JSONObject.parseObject(fixedStr);
            log.info("修复后设备数据JSON：{}", params);
            LocalDateTime time;
            try {
                time = LocalDateTime.parse((String) params.get("time"), FORMATTER);
            } catch (Exception e) {
                log.warn("时间解析失败：{}", params.get("time"));
                time = LocalDateTime.now();
            }
            String timeStr = time.format(OUTPUT_FORMATTER);
            String paramId = params.getString("id");
            Pattern kPattern = Pattern.compile("^k\\d+$");
            boolean hasValidData = false;
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                if (kPattern.matcher(key).matches()) {
                    try {
                        Object dataObj = entry.getValue();
                        if (dataObj instanceof List) {
                            List<?> rawDataList = (List<?>) dataObj;
                            List<String> data = new ArrayList<>();
                            // 转换为字符串，并判断是否有有效值
                            boolean fieldHasValidValue = false;
                            for (Object item : rawDataList) {
                                String strVal;
                                if (item == null) {
                                    strVal = "null";
                                } else {
                                    strVal = item.toString().trim();
                                }
                                data.add(strVal);
                                // 判断这个值是否是“有效值”
                                if (isValidDataValue(strVal)) {
                                    fieldHasValidValue = true;
                                }
                            }
                            // 只有当前字段至少有一个有效值，才放入缓冲队列
                            if (fieldHasValidValue) {
                                RawDeviceData raw = new RawDeviceData(paramId, time, timeStr, key, data);
                                if (dataBuffer.offer(raw)) {
                                    hasValidData = true;
                                } else {
                                    log.warn("缓冲队列已满，丢弃数据 设备编号={}, paramId={}", key, paramId);
                                }
                            } else {
                                log.debug("字段 {} 的所有值均为无效（全0或空），跳过：{}", key, data);
                            }
                        }
                    } catch (Exception fieldEx) {
                        log.error("处理字段 {} 时发生异常，已跳过：{}", key, fieldEx.getMessage());
                    }
                }
            }

            // ===== 最终判断：是否真的有有效数据 =====
            if (hasValidData) {
                return McR.success("设备数据接收成功");
            } else {
                log.warn("设备数据无效：所有 k* 字段均为 0 或空，paramId={}, time={}", paramId, timeStr);
                return McR.errorParam("未解析到有效数据");
            }

        } catch (Exception e) {
            log.error("设备数据同步异常：", e);
            return McR.errorParam("设备数据同步异常");
        }
    }


    @GetMapping("/device/getRunTimeData")
    public List<MachineData> deviceHeartbeat(){
        List machineData = machineDataMapper.selectLatestRuntimeByParamId();
        log.info("设备数据：{}", machineData);
        List result = new ArrayList();
        for(int i = 0; i < machineData.size(); i++){
            MachineData machinedata = (MachineData) machineData.get(i);
            Map map =new HashMap();
            map.put("content", machinedata.getMachineFlag());
            map.put("value", machinedata.getJqyxsh());
            result.add(map);
        }

        return result;
    }
    @GetMapping("/device/getZcnData")
    public List<MachineData> getDailyZcnAtEight() {
        List data = machineDataMapper.selectDailyZcnAtEight();
        List result = new ArrayList();
        for(int i = 0; i < data.size(); i++){
            MachineData machinedata = (MachineData) data.get(i);
            Map map =new HashMap();
            map.put("s", machinedata.getMachineFlag());
            map.put("y", machinedata.getZcn());
            map.put("x", machinedata.getTimestr());
            result.add(map);
        }
        return result;
    }

    private String getValue(List list,int index){
        if(index >= list.size()){
            return "";
        }else{
            return list.get(index).toString();
        }
    }

    private String safeGet(List<String> list, int index) {
        if (list == null) {
            return "";
        }
        if (index >= 0 && index < list.size()) {
            String value = list.get(index);
            return value != null ? value : "";
        }
        return "";
    }

    private String repairMalformedKFields(String input) {
        String result = input;
        // 1. 修复 "k1":] → "k1":[]
        result = result.replaceAll("(\"k\\d+\"\\s*:\\s*)\\]", "$1[]");
        // 2. 修复 "k1":  → "k1":[]
        result = result.replaceAll("(\"k\\d+\"\\s*:\\s*)([\\,\\}])", "$1[]$2");
        return result;
    }

    private boolean isValidDataValue(String value) {
        if (value == null || value.isEmpty() || "null".equalsIgnoreCase(value)) {
            return false;
        }
        return !value.matches("^0+(\\.0+)?$");
    }

}
