package com.yeejoin.amos.kgd.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.kgd.mapper.AnalysisResultMapper;
import com.yeejoin.amos.kgd.model.AnalysisResult;
import com.yeejoin.amos.kgd.service.AnalysisResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class AnalysisResultServiceImpl extends ServiceImpl<AnalysisResultMapper, AnalysisResult> {
    @Autowired
    AnalysisResultMapper analysisResultMapper;

    // 根据 deviceId ,根据设备ID查询数据，幅值与时间
    public JSONObject getDataByDeviceId(String deviceId) {
        int highFrequencyNumber = analysisResultMapper.queryHighFrequencyNumber(deviceId);
        List<AnalysisResult> analysisResultList = analysisResultMapper.queryHighFrequencyData(deviceId, highFrequencyNumber);
        if (analysisResultList == null || analysisResultList.isEmpty()) {
            return null;
        }
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (AnalysisResult analysisResult : analysisResultList) {
            String originData = analysisResult.getData();
            JSONObject jsonData = JSONObject.parseObject(originData);
            JSONArray seriesData = jsonData.getJSONArray("幅值(m/s2)");
            if(seriesData == null) {
                seriesData = jsonData.getJSONArray("幅值(A)");
                jsonData.remove("幅值(A)");
            }else{
                jsonData.remove("幅值(m/s2)");
            }
            JSONArray axisData = jsonData.getJSONArray("时间(s)");
            // 遍历axisData，将每个元素转换为int并重新设置
            for (int i = 0; i < axisData.size(); i++) {
                int value = axisData.getIntValue(i); // 获取并转换为int
                axisData.set(i, value); // 重新设置为int类型的值
            }
            jsonData.remove("时间(s)");
            jsonData.put("seriesData", seriesData);
            jsonData.put("axisData", axisData);
            jsonData.put("num", analysisResult.getVarName());
            jsonArray.add(jsonData);
        }
        result.put("records", jsonArray);
        System.out.println("result:" + result.toString());
        return result;
    }

    // 根据 deviceId 查询 AnalysisData幅值与频率，返回 JSON 格式数据
    public JSONObject getAnalysisDataByDeviceId(String deviceId) {
        int highFrequencyNumber = analysisResultMapper.queryHighFrequencyNumber(deviceId);
        List<AnalysisResult> analysisResultList = analysisResultMapper.queryHighFrequencyAnalysisData(deviceId, highFrequencyNumber);
        if(analysisResultList == null || analysisResultList.isEmpty()){
            return null;
        }
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (AnalysisResult analysisResult : analysisResultList) {
            JSONObject jsonAnalysisData = JSONObject.parseObject(analysisResult.getAnalysisData());
            jsonAnalysisData.put("seriesData", jsonAnalysisData.getJSONArray("幅值(dB)"));
            jsonAnalysisData.put("axisData", jsonAnalysisData.getJSONArray("频率(Hz)"));
            jsonAnalysisData.remove("幅值(dB)");
            jsonAnalysisData.remove("频率(Hz)");
            jsonAnalysisData.put("num", analysisResult.getVarName());
            jsonArray.add(jsonAnalysisData);
        }
        result.put("records", jsonArray);
        return result;
    }


    public JSONArray getVarNameByDeviceId(String deviceId){
        List<String> varNameList = analysisResultMapper.queryVarName(deviceId);
        if(varNameList == null || varNameList.isEmpty()){
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        for(int i = 0; i < varNameList.size(); i++){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("text", varNameList.get(i));
            jsonObject.put("value",varNameList.get(i));
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }


    public JSONObject getAnalysisDataByDeviceIdAndVarName(String deviceId, String varName) {
        AnalysisResult analysisResult = analysisResultMapper.queryAnalysisData(deviceId, varName);
        if (analysisResult == null) {
            return null;
        }
        String data = analysisResult.getData();
        JSONObject jsonData = JSONObject.parseObject(data);
        JSONArray seriesData = jsonData.getJSONArray("幅值(m/s2)");
        if(seriesData == null) {
            seriesData = jsonData.getJSONArray("幅值(A)");
            jsonData.remove("幅值(A)");
        }else{
            jsonData.remove("幅值(m/s2)");
        }
        JSONArray axisData = jsonData.getJSONArray("时间(s)");
        jsonData.remove("时间(s)");
        jsonData.put("seriesData", seriesData);
        jsonData.put("axisData", axisData);
       // jsonData.put("legend", axisData.size());
        return jsonData;
    }

    public JSONObject getFaultRateByDeviceIdAndStatus(String deviceId, String varName) {
        AnalysisResult analysisResult = analysisResultMapper.queryAnalysisResultRate(deviceId, varName);
        if (analysisResult.getAnalysisResultRate() == null) {
            return null;
        }
        String analysisResultRate = analysisResult.getAnalysisResultRate();
        JSONObject jsonAnalysisResultRate = JSONObject.parseObject(analysisResultRate); // {"正常":0.97,"内圈2":0.01,"滚动体2":0.01,"外圈2":0.0}
        // 转换成{"seriesDate":[0.97,0.01,0.01,0.0],"axisData":["正常","内圈2","滚动体2","外圈2"]}
        JSONArray seriesData = new JSONArray();
        JSONArray axisData = new JSONArray();
        for (String key : jsonAnalysisResultRate.keySet()) {
            axisData.add(key);
            seriesData.add(jsonAnalysisResultRate.get(key));
        }
        JSONObject jsonData = new JSONObject();
        jsonData.put("seriesData", seriesData);
        jsonData.put("axisData", axisData);
        return jsonData;
    }

    public JSONArray getFaultTypeProportionByDeviceIdAndStatus(String deviceId, String varName){
        AnalysisResult analysisResult = analysisResultMapper.queryAnalysisResultRate(deviceId, varName);
        if(analysisResult.getAnalysisResultRate() == null){
            return null;
        }
        String analysisResultRate = analysisResult.getAnalysisResultRate();
        JSONObject jsonAnalysisResultRate = JSONObject.parseObject(analysisResultRate); // {"正常":0.97,"内圈2":0.01,"滚动体2":0.01,"外圈2":0.0}
        // 转换成[{"name":"正常","value":0.97},{"name":"内圈2","value":0.01},{"name":"滚动体2","value":0.01},{"name":"外圈2","value":0.0}]
        JSONArray jsonArray = new JSONArray();
        for (String key : jsonAnalysisResultRate.keySet()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", key);
            jsonObject.put("value", jsonAnalysisResultRate.get(key));
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    public JSONObject getSwitchDataByDeviceId(String deviceId, Integer switchNumber){
        int switchTypeNumber = analysisResultMapper.querySwitchTypeNumber(deviceId);

        List<AnalysisResult> analysisResultList = analysisResultMapper.querySwitchDataByDeviceId(deviceId, switchNumber * switchTypeNumber);
        if (analysisResultList == null || analysisResultList.isEmpty()) {
            return null;
        }
        Map<String, List<Integer>> map = new HashMap<>();
        for(AnalysisResult analysisResult: analysisResultList){
            map.computeIfAbsent(analysisResult.getVarName(),
                    k ->  new ArrayList<>()).add(Integer.parseInt(analysisResult.getData())
            );
        }
        // 查询出来采样点的个数：
        int n = analysisResultList.size() / switchTypeNumber;

        List<String> axisData = new ArrayList<>();
        for(int i = 0; i < n; i++){
            AnalysisResult analysisResult = analysisResultList.get(i);
//            long samplingTime = Long.parseLong(analysisResult.getSamplingtime());
//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String time = sdf.format(new Date(Long.parseLong(String.valueOf(samplingTime))));      // 时间戳转换成时间
//            axisData.add(time);

            axisData.add(analysisResult.getSamplingtime());
        }
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for(String key: map.keySet()){
            JSONObject json = new JSONObject();
            json.put("name", key);
            json.put("data", map.get(key));
            jsonArray.add(json);
        }
        jsonObject.put("seriesData", jsonArray);
        jsonObject.put("axisData", axisData);
        return jsonObject;
    }

    public JSONObject getPredictionResultByDeviceId(String deviceId, String varName, Integer predictiveNumber){
        List<AnalysisResult> analysisResultList = analysisResultMapper.queryPredictionResult(deviceId, varName, predictiveNumber);
        if (analysisResultList == null || analysisResultList.isEmpty()) {
            return null;
        }
        JSONArray seriesData = new JSONArray();
        JSONArray axisData = new JSONArray();
        JSONObject jsonPrediction = new JSONObject();
        for (AnalysisResult analysisResult : analysisResultList) {
            String predictResult = analysisResult.getPredictResult();
            seriesData.add(predictResult);
            // 時間錯轉換
//            long samplingTime = Long.parseLong(analysisResult.getSamplingtime());
//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String time = sdf.format(new Date(Long.parseLong(String.valueOf(samplingTime))));      // 时间戳转换成时间
//            axisData.add(time);

            axisData.add(analysisResult.getSamplingtime());
        }
        jsonPrediction.put("seriesData", seriesData);
        jsonPrediction.put("axisData", axisData);
        return jsonPrediction;
    }


//    public JSONArray getTemperatureByDeviceId(String deviceId) {
//        int temperatureNumber = analysisResultMapper.queryTemperatureNumber(deviceId);
//        List<AnalysisResult> analysisResultList = analysisResultMapper.queryTemperatureData(deviceId, temperatureNumber);
//        if (analysisResultList == null || analysisResultList.isEmpty()) {
//            return null;
//        }
//        JSONObject result = new JSONObject();
//        JSONArray jsonArray = new JSONArray();
//        for (AnalysisResult analysisResult : analysisResultList) {
//            String originData = analysisResult.getData();
//            JSONObject jsonData = JSONObject.parseObject(originData);
//            JSONArray seriesData = jsonData.getJSONArray("幅值(m/s2)");
//            if(seriesData == null) {
//                seriesData = jsonData.getJSONArray("幅值(A)");
//                jsonData.remove("幅值(A)");
//            }else{
//                jsonData.remove("幅值(m/s2)");
//            }
//            JSONArray axisData = jsonData.getJSONArray("时间(s)");
//            jsonData.remove("时间(s)");
//            jsonData.put("seriesData", seriesData);
//            jsonData.put("axisData", axisData);
//            jsonData.put("num", analysisResult.getVarName());
//            jsonArray.add(jsonData);
//        }
//        result.put("records", jsonArray);
//        return result;
//
//    }


    public JSONObject getTemperatureByDeviceId(String deviceId){
        int temperatureTypeNumber = analysisResultMapper.queryTemperatureTypeNumber(deviceId, "低频");
        List<AnalysisResult> analysisResultList = analysisResultMapper.queryTemperature(deviceId, temperatureTypeNumber);
        if (analysisResultList == null || analysisResultList.isEmpty()) {
            return null;
        }
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
       /* boolean toggle = true;
        for(AnalysisResult analysisResult: analysisResultList){
            String data = analysisResult.getData();
            JSONObject jsonData = JSONObject.parseObject(data);
            if (toggle){
                jsonData.put("value", jsonData.get("幅值(℃)"));
                jsonData.remove("幅值(℃)");
                jsonData.put("name", analysisResult.getVarName());
            }else {
                jsonData.put("value1",jsonData.get("幅值(℃)"));
                jsonData.remove("幅值(℃)");
                jsonData.put("name1", analysisResult.getVarName());
            }
            jsonArray.add(jsonData);
            toggle=!toggle;
        }*/

        for (int i = 0; i < analysisResultList.size(); i++) {
            AnalysisResult analysisResult = analysisResultList.get(i);
            String data = analysisResult.getData();
            JSONObject jsonData = JSONObject.parseObject(data);

            if (i%2 == 0){
                result.put("value", jsonData.get("幅值(℃)"));
                result.put("name", analysisResult.getVarName());
            }else {
                result.put("value1",jsonData.get("幅值(℃)"));
                result.put("name1", analysisResult.getVarName());
                jsonArray.add(result);
                result = new JSONObject();
            }
        }
        result.put("records", jsonArray);
        return result;
    }
}




