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 deviceId = params.getString("id");
            Pattern kPattern = Pattern.compile("^k\\d+$");
            boolean hasValidData = false;
            // 遍历所有 k* 字段，放入缓冲队列
            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<String> data = new ArrayList<>();
                            for (Object item : (List<?>) dataObj) {
                                if (item instanceof Number) {
                                    data.add(item.toString());
                                } else if (item == null) {
                                    data.add("null");
                                } else {
                                    data.add(item.toString());
                                }
                            }
                            // 创建原始数据对象，放入缓冲队列
                            RawDeviceData raw = new RawDeviceData(deviceId, time, timeStr, key, data);
                            if (dataBuffer.offer(raw)) {
                                hasValidData = true;
                            } else {
                                log.warn("缓冲队列已满，丢弃数据 key={}, deviceId={}", key, deviceId);
                            }
                        }
                    } catch (Exception fieldEx) {
                        log.error("处理字段 {} 时发生异常，已跳过：{}", key, fieldEx.getMessage());
                    }
                }
            }
            // 立即返回成功，不等待数据库写入
            if (hasValidData) {
                return McR.success("设备数据接收成功");
            } else {
                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.getMachineNo());
            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.getMachineNo());
            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":[]
        //    （即冒号后直接跟逗号或其他字符，中间无内容）
        //    先找这种结构："k1": ,  或 "k1": }
        result = result.replaceAll("(\"k\\d+\"\\s*:\\s*)([\\,\\}])", "$1[]$2");
        return result;
    }

}
