package com.huatek.busi.service.impl;

import Cable_eval.Cable;
import GISmec.MEC;;
import assessnew.breaker;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;
import com.huatek.busi.common.BusiConstant;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.dao.AssessInputDataDao;
import com.huatek.busi.dao.BusiEqmWarningDao;
import com.huatek.busi.dao.BusiParamTransformerDao;
import com.huatek.busi.dto.CalculateBasicDataDto;
import com.huatek.busi.dto.SimulateResultDto;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.CalculateBasicDataMapper;
import com.huatek.busi.mapper.SimulateResultMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.vo.AssessInputDataVo;
import com.huatek.busi.vo.SimulateResultVo;
import com.huatek.busi.vo.TransformerInputDateVo;
import com.huatek.busi.where.SimulateResultSelectVo;
import com.huatek.frame.base.util.Constants;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.sql.dao.impl.BaseDao;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;
import com.mathworks.toolbox.javabuilder.*;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;
import lifeassess.ASSESS;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sim_oil_gas.DGA;
import switchtest.GUI;
import testc.TEST;

import javax.annotation.Resource;
import javax.enterprise.inject.New;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.Normalizer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Component
@Service(interfaceClass = ISimulateResultService.class)
@Transactional(rollbackFor = Exception.class)
public class SimulateResultServiceImpl extends BaseDao<SimulateResult, String> implements ISimulateResultService {

    @Reference(check = false)
    ISimulateInputDataItemService simulateInputDataItemService;

    @Reference(check = false)
    ITransformerOperateDataService transformerOperateDataService;

    @Reference(check = false)
    IOperateParamService operateParamService;

    @Resource
    private CalculateBasicDataMapper calculateBasicDataMapper;

    @Resource
    private SimulateResultMapper simulateResultMapper;

    @Autowired
    private BusiEqmWarningDao busiEqmWarningDao;

    @Autowired
    private BusiEqmWarningService busiEqmWarningService;

    @Autowired
    private AssessInputDataDao assessInputDataDao;

    @Override
    public Map<String, Object> list(SimulateResultSelectVo simulateResultSelectVo){
        PageHelper.startPage(simulateResultSelectVo.getPage(), simulateResultSelectVo.getLimit());
        Page<SimulateResultDto> page = simulateResultMapper.list(simulateResultSelectVo);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(), "BUSINESS.QUERY.SUCCESS", page.getResult());
    }

    @Override
    public Map<String, Object> resultData(SimulateResultSelectVo simulateResultSelectVo){
        PageHelper.startPage(simulateResultSelectVo.getPage(), simulateResultSelectVo.getLimit());
        Page<SimulateResultDto> page = simulateResultMapper.list(simulateResultSelectVo);
        for (SimulateResultDto simulateResultDto:page) {
            String resultJson = simulateResultDto.getSimulateResultJson();
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(resultJson);
            Set<String> keys = data.keySet();
            for (String key : keys){
                if ("key".equals(key)){
                    String number = data.getString("key");
                    simulateResultDto.setNumber(number);
                }
                if ("grade".equals(key)){
                    String number = data.getString("grade");
                    simulateResultDto.setNumber(number);
                }
                if ("assess".equals(key)){
                    JSONArray jsonArray = (JSONArray) data.get("assess");
                    for (int i = 0;i<jsonArray.size();i++){
                        net.sf.json.JSONObject assessObject = jsonArray.getJSONObject(i);
                        Set<String> assesses = assessObject.keySet();
                        for (String assess: assesses) {
                            if ("key2".equals(assess)){
                                String key2 = assessObject.getString("key2");
                                simulateResultDto.setAssess2(key2);
                            }
                            if ("key5".equals(assess)){
                                String key5 = assessObject.getString("key5");
                                simulateResultDto.setAssess5(key5);
                            }
                            if ("key8".equals(assess)){
                                String key8 = assessObject.getString("key8");
                                simulateResultDto.setAssess8(key8);
                            }
                            if ("key11".equals(assess)){
                                String key11 = assessObject.getString("key11");
                                simulateResultDto.setAssess11(key11);
                            }
                        }
                    }

                }
                if ("assess0".equals(key)){
                    String number = data.getString("assess0");
                    simulateResultDto.setAssess0(number);
                }
                if ("assess1".equals(key)){
                    String number = data.getString("assess1");
                    simulateResultDto.setAssess1(number);
                }
                if ("assess3".equals(key)){
                    String number = data.getString("assess3");
                    simulateResultDto.setAssess3(number);
                }
                if ("assess4".equals(key)){
                    String number = data.getString("assess4");
                    simulateResultDto.setAssess4(number);
                }
                if ("assess6".equals(key)){
                    String number = data.getString("assess6");
                    simulateResultDto.setAssess6(number);
                }
                if ("assess7".equals(key)){
                    String number = data.getString("assess7");
                    simulateResultDto.setAssess7(number);
                }
                if ("assess9".equals(key)){
                    String number = data.getString("assess9");
                    simulateResultDto.setAssess9(number);
                }
                if ("assess10".equals(key)){
                    String number = data.getString("assess10");
                    simulateResultDto.setAssess10(number);
                }
            }

        }
          return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(),"BUSINESS.QUERY.SUCCESS",page.getResult());
    }

    @Override
    public Map<String, Object> findOilList(SimulateResultSelectVo simulateResultSelectVo){
        PageHelper.startPage(simulateResultSelectVo.getPage(), simulateResultSelectVo.getLimit());
        simulateResultSelectVo.setEquipmentType("1");
        simulateResultSelectVo.setPId("OilChromatogram");
        Page<SimulateResultDto> page = simulateResultMapper.findOilList(simulateResultSelectVo);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(), "BUSINESS.QUERY.SUCCESS", page.getResult());
    }

    @Override
    public Map<String, Object> findAssessList(){
        List<AssessInputDataVo> data = simulateResultMapper.findAssessList();
        String count = simulateResultMapper.findMaxCount();
        String number = simulateResultMapper.findMaxNum();
        int total = Integer.parseInt(count);
        for (int i = 1; i < (total+1); i++) {
            List<AssessInputData> list = simulateResultMapper.findListByJudgment(String.valueOf(i),number);
            for (int j = 0; j < data.size(); j++) {
                if(Objects.equals(data.get(j).getNameId(),String.valueOf(i))){
                    data.get(j).setJudgment(list);
                }
            }
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", data);
    }

    @Override
    public Map<String, Object> findAssessAllList(){
        List<AssessInputData> data = simulateResultMapper.findAssessAllList();
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", data);
    }

    @Override
    public int updateAssessList(String token, List<AssessInputData> inputData){
        LocalUser user = UserUtil.getLocalUser(token);
        if (CollectionUtils.isEmpty(inputData)) {
            return 0;
        }
        int count = 0;
        for (AssessInputData assessInputData : inputData) {
            Integer number = assessInputData.getNum();
            assessInputData.setNum(number+1);
            LocalDateTime localDateTime= LocalDateTime.now();
            assessInputData.setId(Uuid.getUUID());
            assessInputData.setCreateUser(user.getUid());
            assessInputData.setCreateTime(localDateTime);
            count += assessInputDataDao.add(assessInputData);
        }
        return count;
    }

    @Override
    public Map<String, Object> findListByJudgment(String nameId, String num){
        List<AssessInputData> list = simulateResultMapper.findListByJudgment(nameId,num);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", list);
    }

    @Override
    public Map<String, Object> findCsvData(String token , SimulateResultVo simulateResultVo){
        String id = simulateResultVo.getId();
        String pid = simulateResultVo.getPId();
        String filePath = simulateResultMapper.findFilePath(id ,pid);
        int num1 = 3, num2 = 4, num3 = 6, num = 12, line = 26, num4 = 16, num5 = 10, line1 = 0;
        float[] f = new float[0], t = new float[0], h = new float[0];
        if(Objects.equals(pid, Constants.GISPD)){
            t = convertFloat(readFile(filePath, 0, 3), num5); //时间
            f = convertFloat(readFile(filePath, 0, 4), num); //电压值
            float[][] data = {f, t};
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", data);
        }else if(Objects.equals(pid, Constants.GISMEC)){
            f = convertFloat(readFile(filePath, line, 0), num1);
            t = convertFloat(readFile(filePath, line, 1), num2);
            h = convertFloat(readFile(filePath, line, 2), num3);
            float[][] data = {f, t, h};
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", data);
        }else if(Objects.equals(pid, Constants.SWITCH)){
            int columnIndex0 = 0;
            int columnIndex2 = 0;
            int columnIndex3 = 0;
            List<String> list = new ArrayList<>();
            list.addAll(Arrays.asList(filePath.split("/")));
            switch (Integer.parseInt(list.get(3))){
                case 0:
                    columnIndex2 = 2;
                    break;
                case 1:
                    columnIndex2 = 3;
                    columnIndex3 = 4;
                    break;
            }
            String filePathArr[] ={
                    Constants.PATH_NAME_7,
                    Constants.PATH_NAME_8,
                    Constants.PATH_NAME_9,
                    Constants.PATH_NAME_10,
                    Constants.PATH_NAME_11,
                    Constants.PATH_NAME_12
            };

            f = convertFloat(readFile(filePath, line1, columnIndex0), num4);
            if(ArrayUtils.contains(filePathArr, filePath)){
                t = convertFloat(readFile(filePath, line1, columnIndex3), num4);
            }else {
                t = convertFloat(readFile(filePath, line1, columnIndex2), num4);
            }
            float[][] result = {f, t};
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", result);
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", "");
    }

    @Override
    public List<SimulateResultDto> listSimulate(String equipmentType,String pId) {
        List<SimulateResultDto> listSimulate=  simulateResultMapper.listSimulate(equipmentType,pId);
        for (SimulateResultDto simulate:listSimulate){
            String dataItemJson = simulate.getDataItemJson();
            JSONArray jsonArray = JSONArray.fromObject(dataItemJson);
            for (int i=0;i<jsonArray.size();i++){
                net.sf.json.JSONObject insertObj = jsonArray.getJSONObject(i);
                Set<String> keys =  insertObj.keySet();
                for (String key : keys){
                    if ("a".equals(key)){
                        String first = key.replace("a","一级目录");
                        insertObj.put(first,insertObj.getString("a"));
                        insertObj.remove("a");
                    }
                    if ("label".equals(key)){
                        String first = key.replace("label","二级目录");
                        insertObj.put(first,insertObj.getString("label"));
                        insertObj.remove("label");
                    }
                   if ("childFileName".equals(key)){
                        String first = key.replace("childFileName","文件后缀");
                        insertObj.put(first,insertObj.getString("childFileName"));
                        insertObj.remove("childFileName");
                    }

                }
            }
            simulate.setDataItemJson(jsonArray.toString());
        }
        return listSimulate;
    }

    @Override
    public Map<String, Object> simulate(Map<String, Object> mainId) {
        return simulateResultMapper.simulate(mainId);
    }

    @Override
    public Map<String, Object> drivepipeList(SimulateResultSelectVo simulateResultSelectVo){
        PageHelper.startPage(simulateResultSelectVo.getPage(), simulateResultSelectVo.getLimit());
        Page<BusiDrivepipeEvaluationResults> page = simulateResultMapper.drivepipeList(simulateResultSelectVo);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, page.getTotal(), "BUSINESS.QUERY.SUCCESS", page.getResult());
    }

    @Override
    public SimulateResult findById(String id){
        return this.get(id);
    }

    @Override
    public Map<String, Object> calculateByInputItemDate(String token, SimulateResultVo simulateResultVo){

        String dataItemJson = simulateResultVo.getDataItemJson();
        String equipmentType = simulateResultVo.getEquipmentType();
        String pId = simulateResultVo.getPId();

        LocalUser user = UserUtil.getLocalUser(token);

        // 根据输入数据项条件查询
        SimulateInputDataItem simulateInputDataItem = simulateInputDataItemService.selectByDataItemJson(dataItemJson, user);

        // 输入数据项编号
        String dataItemId = simulateInputDataItem.getId();
        // jsonArray字符串转化为JSONArray
        JSONArray jsonArray = JSONArray.fromObject(simulateInputDataItem.getDataItemJson());

        SimulateResult simulateResult = new SimulateResult();
        simulateResult.setId(Uuid.getUUID());
        simulateResult.setEquipmentType(equipmentType);
        simulateResult.setPId(pId);
        simulateResult.setDataItemId(dataItemId);
        simulateResult.setCreateUser(user.getUid());
        simulateResult.setCreateTime(LocalDateTime.now());

        if(Objects.equals(pId, Constants.GISPD)){
            return testc(simulateResult, jsonArray);
        }else if(Objects.equals(pId, Constants.GISMEC)){
            return gISmec(jsonArray, simulateResult);
        }else if(Objects.equals(pId, Constants.ASSESS)){
            return assess(jsonArray, simulateResult);
        }else if(Objects.equals(pId, Constants.SWITCH)){
            return switchtest(jsonArray, simulateResult);
        }else if(Objects.equals(pId, Constants.GENERATOR)){
            return lifeassess(simulateResult, jsonArray);
        }else if(Objects.equals(pId, Constants.CABLE)){
            return cableEval(jsonArray, simulateResult);
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.SIMULATE.CALCULATE.SUCCESS", "");
    }

    @Override
    public String getFilePath(String filePath){
        return this.getClass().getResource(filePath).getPath();
    }

    @Override
    public Map<String, Object> calculatetransformerByInputItemDate(String token, TransformerInputDateVo transformerInputDateVo){

        String id = Uuid.getUUID();
        Integer dataPoint = transformerInputDateVo.getDataPoint();
        Integer totalDataPoint = transformerInputDateVo.getTotalDataPoint();
        LocalDateTime initDate = transformerInputDateVo.getInitDate();
        String jsonData = transformerInputDateVo.getJsonData();

        // 保存油色谱输入参数
        LocalUser user = UserUtil.getLocalUser(token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataPoint",dataPoint);
        jsonObject.put("totalDataPoint",totalDataPoint);
        jsonObject.put("initDate",initDate);
        jsonObject.put("jsonData",jsonData);
        String inputData = JSONObject.toJSONString(jsonObject);
        SimulateInputDataItem simulateInputDataItem = simulateInputDataItemService.selectByDataItemJson(inputData, user);
        // 输入数据项编号
        String dataItemId = simulateInputDataItem.getId();

        // 计算从公元0年【0000年1月0日】到给定日期之间所经历天数
        String startTime = "0000-01-00 00:00:00";
        String endTme = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(initDate);
        long dateNum = DateUtil.getTimeDiff(startTime, endTme);

        // 变压器运行数据
        TransformerOperateData transformerOperateData = new TransformerOperateData();
        transformerOperateData.setId(id);
        transformerOperateData.setInitDate(initDate);
        transformerOperateData.setDateNum(dateNum);
        transformerOperateData.setDataPoint(dataPoint);
        transformerOperateData.setTotalDataPoint(totalDataPoint);
        transformerOperateData.setCreateTime(LocalDateTime.now());

        // 运行参数
        List<String> tList = Lists.newArrayList();
        List<String> h2List = Lists.newArrayList();
        List<String> coList = Lists.newArrayList();
        List<String> co2List = Lists.newArrayList();
        List<String> h2oList = Lists.newArrayList();
        List<String> n2List = Lists.newArrayList();
        List<String> c2h2List = Lists.newArrayList();
        List<String> c2h4List = Lists.newArrayList();
        List<String> c2h6List = Lists.newArrayList();
        List<String> ch4List = Lists.newArrayList();
        List<String> o2List = Lists.newArrayList();
        List<OperateParam> list = Lists.newArrayList();
        JSONArray jsonArray = JSONArray.fromObject(jsonData);
        for (int i = 0; i < jsonArray.size(); i++){

            // 阈值
            String threshold = jsonArray.getJSONObject(i).getString("threshold");
            tList.add(threshold);

            // 初值
            String initValue = jsonArray.getJSONObject(i).getString("initValue");
            // 终值
            String finalValue = jsonArray.getJSONObject(i).getString("finalValue");

            // 绝对增长值
            String absoluteGrowth = jsonArray.getJSONObject(i).getString("absoluteGrowth");

            // 气体类型
            String gasType = jsonArray.getJSONObject(i).getString("gasType");

            OperateParam operateParam = new OperateParam();
            operateParam.setId(Uuid.getUUID());
            operateParam.setPId(id);
            operateParam.setThreshold(threshold);
            operateParam.setInitValue(initValue);
            operateParam.setFinalValue(finalValue);
            operateParam.setAbsoluteGrowth(absoluteGrowth);
            operateParam.setGasType(gasType);
            operateParam.setCreateTime(LocalDateTime.now());
            list.add(operateParam);
            if(gasType.equals("H2")){
                h2List.add(initValue);
                h2List.add(finalValue);
                h2List.add(absoluteGrowth);
            }
            if(gasType.equals("CO2")){
                co2List.add(initValue);
                co2List.add(finalValue);
                co2List.add(absoluteGrowth);
            }
            if(gasType.equals("CO")){
                coList.add(initValue);
                coList.add(finalValue);
                coList.add(absoluteGrowth);
            }
            if(gasType.equals("C2H2")){
                c2h2List.add(initValue);
                c2h2List.add(finalValue);
                c2h2List.add(absoluteGrowth);
            }
            if(gasType.equals("C2H4")){
                c2h4List.add(initValue);
                c2h4List.add(finalValue);
                c2h4List.add(absoluteGrowth);
            }
            if(gasType.equals("C2H6")){
                c2h6List.add(initValue);
                c2h6List.add(finalValue);
                c2h6List.add(absoluteGrowth);
            }
            if(gasType.equals("CH4")){
                ch4List.add(initValue);
                ch4List.add(finalValue);
                ch4List.add(absoluteGrowth);
            }
            if(gasType.equals("H2O")){
                h2oList.add(initValue);
                h2oList.add(finalValue);
                h2oList.add(absoluteGrowth);
            }
            if(gasType.equals("N2")){
                n2List.add(initValue);
                n2List.add(finalValue);
                n2List.add(absoluteGrowth);
            }
            if(gasType.equals("O2")){
                o2List.add(initValue);
                o2List.add(finalValue);
                o2List.add(absoluteGrowth);
            }
        }

        // 阈值
        String[] t = tList.toArray(new String[tList.size()]);
        float[] tFloat = convertFloat(t, 6);
        MWNumericArray signal = new MWNumericArray(tFloat, MWClassID.DOUBLE);

        // H2
        String[] h2 = h2List.toArray(new String[h2List.size()]);
        float[] h2Float = convertFloat(h2, 3);

        // O2
        String[] o2 = o2List.toArray(new String[o2List.size()]);
        float[] o2Float = convertFloat(o2, 3);

        // CH4
        String[] ch4 = ch4List.toArray(new String[ch4List.size()]);
        float[] ch4Float = convertFloat(ch4, 3);

        // C2H2
        String[] c2h2 = c2h2List.toArray(new String[c2h2List.size()]);
        float[] c2h2Float = convertFloat(c2h2, 3);

        // C2H4
        String[] c2h4 = c2h4List.toArray(new String[c2h4List.size()]);
        float[] c2h4Float = convertFloat(c2h4, 3);

        // C2H6
        String[] c2h6 = c2h6List.toArray(new String[c2h6List.size()]);
        float[] c2h6Float = convertFloat(c2h6, 3);

        // H2O
        String[] h2o = h2oList.toArray(new String[h2oList.size()]);
        float[] h2oFloat = convertFloat(h2o, 3);

        // N2
        String[] n2 = n2List.toArray(new String[n2List.size()]);
        float[] n2Float = convertFloat(n2, 3);

        // CO
        String[] co = coList.toArray(new String[coList.size()]);
        float[] coFloat = convertFloat(co, 3);

        // CO2
        String[] co2 = co2List.toArray(new String[co2List.size()]);
        float[] co2Float = convertFloat(co2, 3);

        float[][] gasPar = {h2Float, ch4Float, c2h6Float, c2h4Float, c2h2Float, coFloat, co2Float, n2Float, o2Float, h2oFloat};
        MWNumericArray signal1 = new MWNumericArray(gasPar, MWClassID.DOUBLE);
        try {
            DGA dga = new DGA();
            Object[] obj = dga.sim_oil_gas(2, dateNum, dataPoint, totalDataPoint, signal, signal1);

            // 返回代码
            String code = obj[1].toString();
            // 将matlab矩阵转换为二维数组
            MWCellArray mwCellArray = (MWCellArray) obj[0];
            Object time ;
            String a ;
            String b ;
            String c ;

            jsonObject.clear();
            if(Objects.equals(code, String.valueOf(Constants.PARAM_SIZE_ERROR))){
                jsonObject.put("code",Constants.PARAM_SIZE_ERROR);
                jsonObject.put("result",Constants.PARAM_SIZE_ERROR_MSG);
                return ResultUtil.put(Constants.PARAM_SIZE_ERROR, Constants.PARAM_SIZE_ERROR_MSG, "");
            }else if(Objects.equals(code, String.valueOf(Constants.PARAM_NULL))){
                jsonObject.put("code",Constants.PARAM_NULL);
                jsonObject.put("result",Constants.PARAM_NULL_MSG);
                return ResultUtil.put(Constants.PARAM_NULL, Constants.PARAM_NULL_MSG, "");
            }else if(Objects.equals(code, String.valueOf(Constants.NO_FAULT))){
                time = (mwCellArray.getCell(new int[]{1,1})).getData();
                jsonObject.put("code",Constants.NO_FAULT);
                jsonObject.put("result",Constants.NO_FAULT_MSG);
                jsonObject.put("time",time);
                return ResultUtil.put(Constants.NO_FAULT, Constants.NO_FAULT_MSG, "");
            }else if(Objects.equals(code, String.valueOf(Constants.PARAM_NOT_INTACT))){
                jsonObject.put("code",Constants.PARAM_NOT_INTACT);
                jsonObject.put("result",Constants.PARAM_NOT_INTACT_MSG);
                return ResultUtil.put(Constants.PARAM_NOT_INTACT, Constants.PARAM_NOT_INTACT_MSG, "");
            }else if(Objects.equals(code, String.valueOf(Constants.OVER_THRESHOLD))){
                time = (mwCellArray.getCell(new int[]{1,1})).getData();
                a = (mwCellArray.getCell(new int[]{1,2})).toString();
                a = a.replace("'","");
                b = (mwCellArray.getCell(new int[]{1,3})).toString();
                c = (mwCellArray.getCell(new int[]{1,4})).toString();
                jsonObject.put("code",Constants.OVER_THRESHOLD);
                jsonObject.put("result",Constants.OVER_THRESHOLD_MSG);
                jsonObject.put("time",time);
                jsonObject.put("threeRatioCode",a); //超阈值气体
                jsonObject.put("threeRatioMsg",b); //实际值
                jsonObject.put("threeRatioFault",c); //阈值
            }else if(Objects.equals(code, String.valueOf(Constants.THREE_RATIO))){
                time = (mwCellArray.getCell(new int[]{1,1})).getData();
                a = (mwCellArray.getCell(new int[]{1,2})).toString();
                b = (mwCellArray.getCell(new int[]{1,3})).toString();
                c = (mwCellArray.getCell(new int[]{1,4})).toString();
                jsonObject.put("code",Constants.THREE_RATIO);
                jsonObject.put("result",Constants.THREE_RATIO_MSG);
                jsonObject.put("time",time);
                jsonObject.put("threeRatioFault",a);
                jsonObject.put("threeRatioCode",b);
                jsonObject.put("threeRatioMsg",c);
            }else if(Objects.equals(code, String.valueOf(Constants.NINE_RATIO))){
                jsonObject.put("code",Constants.NINE_RATIO);
                jsonObject.put("result",Constants.NINE_RATIO_MSG);
                return ResultUtil.put(Constants.NINE_RATIO, Constants.NINE_RATIO_MSG, "");
            }

            // 新增变压器运行数据
            transformerOperateDataService.insert(transformerOperateData);

            // 批量新增运行参数
            Runnable runnable = () -> operateParamService.batchInsert(list);
            new Thread(runnable).start();

            String simulateResultJson = JSONObject.toJSONString(jsonObject);
            transformerOperateDataService.update(id, simulateResultJson);

            SimulateResult simulateResult = new SimulateResult();
            simulateResult.setEquipmentType("1");
            simulateResult.setPId("OilChromatogram");
            simulateResult.setDataItemId(dataItemId);
            simulateResult.setSimulateResultJson(simulateResultJson);
            simulateResult.setFilePath("-1");
            simulateResult.setFileName("-1");
            simulateResult.setId(Uuid.getUUID());
            simulateResult.setCreateUser(user.getUid());
            simulateResult.setCreateTime(LocalDateTime.now());
            this.add(simulateResult);
        }catch (Exception e){
            log.error("计算变压器运行数据异常:{}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.OPERATE.CALCULATE.SUCCESS", "");
    }

    /**
     * GIS局部放电诊断
     */
    private Map<String, Object> testc(SimulateResult simulateResult, JSONArray jsonArray){

        // 主文件夹名称
        String mainFileName = simulateResult.getPId();
        // 子文件夹名称
        int label = jsonArray.getJSONObject(0).getInt("label");
        // 文件名称
        String childFileName = jsonArray.getJSONObject(1).getString("childFileName");

        float[] f;
        int num = 12;
        String valueTwo = calculateBasicDataMapper.getTestc(mainFileName, label, childFileName);
        String filePath = "/gis/"+ mainFileName +"/"+ label +"/"+ childFileName +".csv";
        if(StrUtil.isNotEmpty(valueTwo)){
            f = convertFloat(valueTwo, num);
        }else {
            f = convertFloat(readFile(filePath, 0, 4), num);
        }

        TEST test;
        try {
            test = new TEST();
            MWNumericArray signal = new MWNumericArray(f, MWClassID.DOUBLE);
            Object[] obj = test.testc(1, signal);

            String value = null;
            String key = obj[0].toString();
            switch (key){
                case Constants.FLOAT_POTENTIAL_CODE:
                    value = Constants.FLOAT_POTENTIAL;
                    break;
                case Constants.METAL_PARTICL_CODE:
                    value = Constants.METAL_PARTICL;
                    break;
                case Constants.METAL_SPIK_CODE:
                    value = Constants.METAL_SPIK;
                    break;
                case Constants.NORMAL_CODE:
                    value = Constants.NORMAL_STATUS;
                    break;
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", key);
            jsonObject.put("value", value);
            String testc = JSONObject.toJSONString(jsonObject);

            if(key != Constants.NORMAL_CODE){
                // 保存告警
                this.saveBusiEqmWarning(simulateResult,value,testc);
            }
            simulateResult.setSimulateResultJson(testc);
            simulateResult.setFileName(childFileName +".csv");
            simulateResult.setFilePath(filePath);
            this.add(simulateResult);
        } catch (MWException e) {
            log.error("GIS局部放电诊断计算异常：{}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, Constants.CALCULATE_SUCCESS_MSG, "");
    }

    /**
     * GIS机械故障诊断
     * @param jsonArray
     */
    private Map<String, Object> gISmec(JSONArray jsonArray, SimulateResult simulateResult){

        // 主文件夹
        String mainFileName = simulateResult.getPId();
        // 0是分闸，1是合闸
        int a = jsonArray.getJSONObject(0).getInt("a");
        // 文件夹名称
        int label = jsonArray.getJSONObject(1).getInt("label");
        // 文件名称
        String childFileName = jsonArray.getJSONObject(2).getString("childFileName");

        int num1 = 3, num2 = 4, num3 = 6;
        float[] f = new float[0], t = new float[0], h = new float[0];
        String filePath = "/gis/"+ mainFileName +"/"+ a +"/"+ label +"/"+childFileName+".csv";
        CalculateBasicDataDto calculateBasicDataDto = calculateBasicDataMapper.getCalculateBasicData(mainFileName, a, label, childFileName);
        if(calculateBasicDataDto != null){
            String valueOne = calculateBasicDataDto.getValueOne();
            String valueTwo = calculateBasicDataDto.getValueTwo();
            String valueThree = calculateBasicDataDto.getValueThree();
            if(StrUtil.isNotEmpty(valueOne) && StrUtil.isNotEmpty(valueTwo) && StrUtil.isNotEmpty(valueThree)){
                f = convertFloat(valueOne, num1);
                t = convertFloat(valueTwo, num2);
                h = convertFloat(valueThree, num3);
            }
        }else {
            int line = 26;
            f = convertFloat(readFile(filePath, line, 0), num1);
            t = convertFloat(readFile(filePath, line, 1), num2);
            h = convertFloat(readFile(filePath, line, 2), num3);
        }

        float[][] data = {f, t, h};
        // 调用matlab的数据转换下
        MWNumericArray signal = new MWNumericArray(data, MWClassID.DOUBLE);
        try {
            MEC mec = new MEC();
            Object[] obj = mec.GISmec(1, a, signal);

            String key = obj[0].toString();
            String value = getGISmecValueByCode(key);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", key);
            jsonObject.put("value", value);
            String gISmec = JSONObject.toJSONString(jsonObject);

            if(key != "8" || key != "16"){
                // 保存告警
                this.saveBusiEqmWarning(simulateResult,value,gISmec);
            }
            simulateResult.setSimulateResultJson(gISmec);
            simulateResult.setFileName(childFileName +".csv");
            simulateResult.setFilePath(filePath);
            this.add(simulateResult);
        } catch (MWException e) {
            log.error("计算GIS机械故障诊断异常：{}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, Constants.CALCULATE_SUCCESS_MSG, "");
    }

    /**
     * 断路器状态评估
     * @param jsonArray
     */
    private Map<String, Object> assess(JSONArray jsonArray, SimulateResult simulateResult){

        // 断路器本体评价打分
        String body = jsonArray.getJSONObject(0).getString("body");
        int[] b = convertInt(body);

        // 弹簧机构评价打分
        String spr = jsonArray.getJSONObject(1).getString("spr");
        int[] s = convertInt(spr);

        // 液压弹簧机构评价打分
        String hyd = jsonArray.getJSONObject(2).getString("hyd");
        int[] h = convertInt(hyd);

        // 并联电容器评价打分
        String cap = jsonArray.getJSONObject(3).getString("cap");
        int[] c = convertInt(cap);

        // 合闸电阻评价打分
        String res = jsonArray.getJSONObject(4).getString("res");
        int[] r = convertInt(res);
        try {
            breaker as = new breaker();
            Object[] obj = as.assessnew(1, b, s, h, c, r);

            log.info("断路器状态评估计算结果为：{}", obj[0].toString());

            // 将matlab矩阵转换为二维数组
            MWNumericArray mwNumericArray = new MWNumericArray(obj[0], MWClassID.INT64);
            int[][] value = (int[][]) mwNumericArray.toIntArray();
            JSONArray jsonArray1 = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < value[0].length; i++){
                int v = value[0][i];
                JSONObject jsonObject1 = new JSONObject();
                if(i == 2 || i == 5 || i == 8 || i == 11){
                    if(v == Constants.NORMAL){
                        jsonObject1.put("value" + i, Constants.NORMAL_MSG);
                    }else if(v == Constants.TAKE_CARE){
                        jsonObject1.put("value" + i, Constants.TAKE_CARE_MSG);
                    }else if(v == Constants.ABNORMAL){
                        jsonObject1.put("value" + i, Constants.ABNORMAL_MSG);
                    }else if(v == Constants.SERIOUS){
                        jsonObject1.put("value" + i, Constants.SERIOUS_MSG);
                    }
                    jsonObject1.put("key" + i, v);
                    jsonArray1.add(jsonObject1);
                }else {
                    jsonObject.put("assess" + i, v);
                }
            }
            if(CollectionUtil.isNotEmpty(jsonArray1)){
                jsonObject.put("assess", jsonArray1);
            }
            String assess = JSONObject.toJSONString(jsonObject);

            if(value[0][2] != Constants.NORMAL || value[0][5] != Constants.NORMAL || value[0][8] != Constants.NORMAL || value[0][11] != Constants.NORMAL){
                this.saveBusiEqmWarning(simulateResult, "断路器状态诊断异常", assess);
            }

            simulateResult.setSimulateResultJson(assess);
            simulateResult.setFilePath("-1");
            simulateResult.setFileName("-1");
            this.add(simulateResult);
        } catch (MWException e) {
            log.error("计算断路器状态评估：{}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, Constants.CALCULATE_SUCCESS_MSG, "");
    }

    /**
     * 开关柜机械故障诊断
     * @param jsonArray
     */
    private Map<String, Object> switchtest(JSONArray jsonArray, SimulateResult simulateResult){

        // 主文件夹
        String mainFileName = simulateResult.getPId();
        // 分闸合闸
        int a = jsonArray.getJSONObject(0).getInt("a");
        // 故障标签文件夹名称
        int label = jsonArray.getJSONObject(1).getInt("label");
        // 文件名称
        String childFileName = jsonArray.getJSONObject(2).getString("childFileName");

        int num = 16;
        int columnIndex0 = 0;
        int columnIndex2 = 0;
        int columnIndex3 = 0;
        float[] f = new float[0], t = new float[0];
        switch (a){
            case 0:
                columnIndex2 = 2;
                break;
            case 1:
                columnIndex2 = 3;
                columnIndex3 = 4;
                break;
        }

        String filePath = "/gis/"+ mainFileName +"/"+ a +"/"+ label +"/"+ childFileName +".csv";
        CalculateBasicDataDto calculateBasicDataDto = calculateBasicDataMapper.getCalculateBasicData(mainFileName, a, label, childFileName);
        if(calculateBasicDataDto != null){
            String valueOne = calculateBasicDataDto.getValueOne();
            switch (a){
                case 0:
                    String valueThree = calculateBasicDataDto.getValueThree();
                    if(StrUtil.isNotEmpty(valueOne) && StrUtil.isNotEmpty(valueThree)){
                        f = convertFloat(valueOne, num);
                        t = convertFloat(valueThree, num);
                    }
                    break;
                case 1:
                    String value;
                    String valueFour = calculateBasicDataDto.getValueFour();
                    String valueFive = calculateBasicDataDto.getValueFive();
                    if(valueFive.contains(Constants.NO_DATA)){
                        value = valueFour;
                    }else {
                        value = valueFive;
                    }
                    if(StrUtil.isNotEmpty(valueOne) && StrUtil.isNotEmpty(value)){
                        f = convertFloat(valueOne, num);
                        t = convertFloat(value, num);
                    }
                    break;
            }
        }else {
            int line = 0;
            String filePathArr[] ={
                    Constants.PATH_NAME_7,
                    Constants.PATH_NAME_8,
                    Constants.PATH_NAME_9,
                    Constants.PATH_NAME_10,
                    Constants.PATH_NAME_11,
                    Constants.PATH_NAME_12
            };

            f = convertFloat(readFile(filePath, line, columnIndex0), num);
            if(ArrayUtils.contains(filePathArr, filePath)){
                t = convertFloat(readFile(filePath, line, columnIndex3), num);
            }else {
                t = convertFloat(readFile(filePath, line, columnIndex2), num);
            }
        }

        float[][] data = {f, t};
        // 调用matlab的数据转换下
         MWNumericArray signal = new MWNumericArray(data, MWClassID.DOUBLE);
        try {
            GUI gui = new GUI();
            Object[] obj = gui.switchtest(1, a, signal);

            String key = obj[0].toString();
            String value = getValueByCode(key);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", key);
            jsonObject.put("value", value);
            String switchTest = JSONObject.toJSONString(jsonObject);
            if(key != "0" || key != "7"){
                this.saveBusiEqmWarning(simulateResult, value, switchTest);
            }
            simulateResult.setSimulateResultJson(switchTest);
            simulateResult.setFileName(childFileName +".csv");
            simulateResult.setFilePath(filePath);
            this.add(simulateResult);
        } catch (MWException e) {
            log.error("计算开关柜机械故障诊断异常：{}",e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, Constants.CALCULATE_SUCCESS_MSG, "");
    }

    /**
     * 发电机定子绝缘状态诊断计算
     * @param simulateResult
     * @param jsonArray
     */
    private Map<String, Object> lifeassess(SimulateResult simulateResult, JSONArray jsonArray){
        try {
            // 电压等级
            Float v = Float.parseFloat(jsonArray.getJSONObject(0).getString("v"));
            // 常规运行温度
            Float t = Float.parseFloat(jsonArray.getJSONObject(1).getString("t"));
            // 主绝缘层厚度
            Float h = Float.parseFloat(jsonArray.getJSONObject(2).getString("h"));
            // 吸收比
            Float s = Float.parseFloat(jsonArray.getJSONObject(3).getString("s"));
            // 介质损耗
            Float j = Float.parseFloat(jsonArray.getJSONObject(4).getString("j"));
            // 介质增量
            Float z = Float.parseFloat(jsonArray.getJSONObject(5).getString("z"));
            // 放电量增加率
            Float f = Float.parseFloat(jsonArray.getJSONObject(6).getString("f"));

            ASSESS generator = new ASSESS();
            Object[] obj = generator.lifeassess(2,v,t,h,s,j,z,f);

            String grade = obj[1].toString();
            MWNumericArray B = new MWNumericArray(obj[0]);
            String suggest  = B.toString();
            String status;
            String opinion;
            if(suggest.equals(Constants.BEST)){
                status = Constants.BEST_STATUS;
                opinion = Constants.BEST_MSG;
            }else if(suggest.equals(Constants.GOOD)){
                status = Constants.GOOD_STATUS;
                opinion = Constants.GOOD_MSG;
            }else if(suggest.equals(Constants.MIDDLE)){
                status = Constants.MIDDLE_STATUS;
                opinion = Constants.MIDDLE_MSG;
            }else{
                status = Constants.BAD_STATUS;
                opinion = Constants.BAD_MSG;
            }

            log.info("检修意见：{},评分等级：{}, 运行状态：{}, suggest:{}", opinion, grade, status,suggest);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("opinion", opinion);
            jsonObject.put("grade", grade);
            jsonObject.put("status", status);
            String simulateResultJson = JSONObject.toJSONString(jsonObject);
            if(suggest != Constants.BEST){
                this.saveBusiEqmWarning(simulateResult, opinion, simulateResultJson);
            }
            simulateResult.setSimulateResultJson(simulateResultJson);
            simulateResult.setFileName("-1");
            simulateResult.setFilePath("-1");
            this.add(simulateResult);
        }catch (MWException e){
            log.error("发电机定子绝缘状态诊断计算异常: {}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, Constants.CALCULATE_SUCCESS_MSG, "");
    }

    /**
     * 电缆算法计算
     * @param jsonArray
     */
    public Map<String, Object> cableEval(JSONArray jsonArray, SimulateResult simulateResult){
        try {
            // 技术信息状态量
            String stateTech = jsonArray.getJSONObject(0).getString("stateTech");
            float[] t = convertFloat(stateTech, 6);

            // 经济信息状态量
            String stateEcon = jsonArray.getJSONObject(1).getString("stateEcon");
            float[] e = convertFloat(stateEcon, 6);

            // 策略信息状态量
            String stateStra = jsonArray.getJSONObject(2).getString("stateStra");
            float[] s = convertFloat(stateStra, 6);

            // 介损因数
            String factorDielDiss = jsonArray.getJSONObject(3).getString("factorDielDiss");
            float[] d = convertFloat(factorDielDiss, 6);

            // 局部放电
            String dischangPart = jsonArray.getJSONObject(4).getString("dischangPart");
            float[] p = convertFloat(dischangPart, 6);

            Cable cable = new Cable();
            Object[] obj = cable.Cable_eval(2, t, e, s, d, p);

            String v = obj[1].toString();
            if(Objects.equals(v, String.valueOf(Constants.PARAM_SIZE_ERROR))){
                return ResultUtil.put(Constants.PARAM_SIZE_ERROR, Constants.PARAM_SIZE_ERROR_MSG, "");
            }else if(Objects.equals(v, String.valueOf(Constants.PARAM_NULL))){
                return ResultUtil.put(Constants.PARAM_NULL, Constants.PARAM_NULL_MSG, "");
            }else if(Objects.equals(v, String.valueOf(Constants.PARAM_NOT_INTACT))){
                return ResultUtil.put(Constants.PARAM_NOT_INTACT, Constants.PARAM_NOT_INTACT_MSG, "");
            }else if(Objects.equals(v, String.valueOf(Constants.PROGRAM_EXCEPTION))){
                return ResultUtil.put(Constants.PROGRAM_EXCEPTION, Constants.PROGRAM_EXCEPTION_MSG, "");
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", v);
            jsonObject.put("value", obj[0].toString());
            String simulateResultJson = JSONObject.toJSONString(jsonObject);
            if(obj[0].toString().equals("该电缆评级为中，建议进一步检查") || obj[0].toString().equals("该电缆评级为差，需要立即检修，应及时进行更换")){
                this.saveBusiEqmWarning(simulateResult, obj[0].toString(), simulateResultJson);
            }
            simulateResult.setSimulateResultJson(simulateResultJson);
            simulateResult.setFileName("-1");
            simulateResult.setFilePath("-1");
            this.add(simulateResult);
        }catch (Exception e){
            log.error("电缆算法计算异常: {}", e.getMessage());
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.OPERATE.CALCULATE.FAIL", "");
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, Constants.CALCULATE_SUCCESS_MSG, "");
    }

    /**
     * 读取csv文件
     * @param pathName 全路径
     * @param line 行号索引
     * @throws IOException
     */
    @SneakyThrows
    private String readFile(String pathName, Integer line, Integer columnIndex) {
        String st = "";
        try {
            String basePath = this.getClass().getResource(pathName).getPath();
            InputStream inputStream = new FileInputStream(new File(basePath));
            DataInputStream in = new DataInputStream(inputStream);
            CSVReader csvReader = new CSVReader(new InputStreamReader(in, "GBK"), CSVParser.DEFAULT_SEPARATOR,
                    CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, line);
            String[] strs;
            while ((strs = csvReader.readNext()) != null) {
                st += strs[columnIndex].trim() + ",";
            }
            st = st.substring(0, st.length() - 1);
            csvReader.close();
            in.close();
        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            log.error("读取CSV文件异常:{}", ex.getMessage());
        }
        return st;
    }

    /**
     * 预测故障标签
     * 0-8是合闸状态
     * 0：合闸控制电压过低
     * 1：合闸弹簧过紧
     * 2：合闸弹簧过紧，同时控制电压过高
     * 3：合闸弹簧过松
     * 4：合闸弹簧过松，同时控制电压过低
     * 5：合闸控制电压过高
     * 6：合闸弹簧过紧
     * 7：合闸弹簧过松
     * 8：合闸正常
     * 9-16是分闸状态
     * 9：分闸控制电压过低
     * 10：分闸弹簧过紧，同时控制电压过高
     * 11：分闸弹簧过紧
     * 12：分闸弹簧过松，同时控制电压过低
     * 13：分闸弹簧过松
     * 14：分闸电磁铁卡涩
     * 15：分闸控制电压过高
     * 16：分闸正常
     * @param code
     * @return
     */
    private String getGISmecValueByCode(String code){
        String gISmec = "";
        switch (code){
            case "0":
                gISmec = "合闸控制电压过低";
                break;
            case "1":
                gISmec = "合闸弹簧过紧";
                break;
            case "2":
                gISmec = "合闸弹簧过紧，同时控制电压过高";
                break;
            case "3":
                gISmec = "合闸弹簧过松";
                break;
            case "4":
                gISmec = "合闸弹簧过松，同时控制电压过低";
                break;
            case "5":
                gISmec = "合闸控制电压过高";
                break;
            case "6":
                gISmec = "合闸弹簧过紧";
                break;
            case "7":
                gISmec = "合闸弹簧过松";
                break;
            case "8":
                gISmec = "合闸正常";
                break;
            case "9":
                gISmec = "分闸控制电压过低";
                break;
            case "10":
                gISmec = "分闸弹簧过紧，同时控制电压过高";
                break;
            case "11":
                gISmec = "分闸弹簧过紧";
                break;
            case "12":
                gISmec = "分闸弹簧过松，同时控制电压过低";
                break;
            case "13":
                gISmec = "分闸弹簧过松";
                break;
            case "14":
                gISmec = "分闸电磁铁卡涩";
                break;
            case "15":
                gISmec = "分闸控制电压过高";
                break;
            case "16":
                gISmec = "分闸正常";
                break;
        }
        return gISmec;
    }

    /**
     * 预测故障标签 (0-13)
     * 0-6属于分闸过程
     * 0：分闸正常
     * 1：分闸弹簧力减小
     * 2：分闸超程减小
     * 3：分闸超程增大
     * 4：分闸控制电压降低
     * 5：分闸控制电压提高
     * 6：分闸电磁体老化
     *  7-13属于合闸过程
     * 7：合闸正常
     * 8：合闸弹簧力减小
     * 9：合闸超程减小
     * 10：合闸超程增大
     * 11：合闸控制电压降低
     * 12：合闸控制电压提高
     * 13：合闸电磁体老化
     * @param code
     * @return
     */
    private String getValueByCode(String code){
        String switchTest;
        switch (code){
            case "0":
                switchTest = "分闸正常";
                break;
            case "1":
                switchTest = "分闸弹簧力减小";
                break;
            case "2":
                switchTest = "分闸超程减小";
                break;
            case "3":
                switchTest = "分闸超程增大";
                break;
            case "4":
                switchTest = "分闸控制电压降低";
                break;
            case "5":
                switchTest = "分闸控制电压提高";
                break;
            case "6":
                switchTest = "分闸电磁体老化";
                break;
            case "7":
                switchTest = "合闸正常";
                break;
            case "8":
                switchTest = "合闸弹簧力减小";
                break;
            case "9":
                switchTest = "合闸超程减小";
                break;
            case "10":
                switchTest = "合闸超程增大";
                break;
            case "11":
                switchTest = "合闸控制电压降低";
                break;
            case "12":
                switchTest = "合闸控制电压提高";
                break;
            case "13":
                switchTest = "合闸电磁体老化";
                break;
            default:
                throw new IllegalStateException("code value is null: " + code);
        }
        return switchTest;
    }

    /**
     * 字符串转int
     * @param value
     * @return
     */
    public int[] convertInt(String value){
        String[] v = value.split(",");
        List<Integer> list = Lists.newArrayList();
        for (int i = 0; i < v.length; i++){
            list.add(Integer.valueOf(v[i]));
        }
        int index = 0;
        int[] arr = new int[list.size()];
        for (Integer integer : list){
            arr[index++] = integer;
        }
        return arr;
    }

    /**
     * 字符串转float
     * @param value
     * @return
     */
    public static float[] convertFloat(String value, int num){
        String[] v = value.split(",");
        List<Float> list = Lists.newArrayList();
        for (int i = 0; i < v.length; i++){
            BigDecimal bigDecimal = new BigDecimal(v[i]).setScale(num, BigDecimal.ROUND_HALF_UP);
            float f = bigDecimal.floatValue();
            list.add(f);
        }
        int index = 0;
        float[] arr = new float[list.size()];
        for (Float f : list){
            arr[index++] = f;
        }
        return arr;
    }

    /**
     * 字符串数组转float
     * @param str
     * @param num
     * @return
     */
    private float[] convertFloat(String[] str, int num){
        String allName = "";
        for (String s :str){
            allName += s + ",";
        }
        allName = allName.substring(0, allName.length() -1);
        return convertFloat(allName, num);
    }

    /**
     * 将元胞数组（MWCellArray）转换为MWArray
     * @return
     */
    private String convertMWArray(Object o){
        MWCellArray mwCellArray = (MWCellArray) o;
        MWArray arr = mwCellArray.getCell(new int[]{1,1});
        return arr.toString();
    }

    /**
     * 获取字符串文本中的值
     * @param obj
     * @return
     */
    private Map<String, Object> getStrValue(Object obj){
        String str = obj.toString();
        str = str.replace(" ", ",");
        String[] s = str.split(",");
        String grade = s[0];
        String status = s[1];

        log.info(grade + "<<<<>>>>>" + status);

        grade = grade.substring(grade.indexOf("：") + 1);
        status = status.substring(status.indexOf("：") + 1);

        Map<String, Object> map = Maps.newHashMap();
        map.put("grade", grade);
        map.put("status", status);
        return map;
    }

    /**
     * list转换json字符串
     * @param o
     * @return
     */
    private String convertList(Object o, int num){
        MWNumericArray mwNumericArray = (MWNumericArray) o;
        double[][] uacc = (double[][]) mwNumericArray.toDoubleArray();
        List<BigDecimal> list = Lists.newArrayList();
        Arrays.stream(uacc).forEach(u -> list.add(new BigDecimal(u[0]).setScale(num, RoundingMode.UP)));
        return JSONArray.fromObject(list).toString();
    }

    private BusiEqmWarning saveBusiEqmWarning(SimulateResult simulateResult, String value, String json){
        BusiEqmWarning busiEqmWarning = new BusiEqmWarning();
        busiEqmWarning.setWarningCode("simulationWarning");
        busiEqmWarning.setSensorId(simulateResult.getPId());
        busiEqmWarning.setEqType(simulateResult.getEquipmentType());
        busiEqmWarning.setGzType(simulateResult.getPId());
        busiEqmWarning.setWarningTypeCode(simulateResult.getPId());
        busiEqmWarning.setWarningTime(LocalDateTime.now());
        busiEqmWarning.setCreateTime(simulateResult.getCreateTime());
        busiEqmWarning.setWarningFlag("1");
        busiEqmWarning.setWarningMsg(value);
        busiEqmWarning.setDelFlag(SiteConstants.Status.NORMAL.getValue());
        busiEqmWarning.setDealStatus("0");
        busiEqmWarning.setSubTreeId("/");
        busiEqmWarning.setSubEquipmentBrand("/");
        busiEqmWarning.setSubEquipmentId("/");
        busiEqmWarning.setSubEquipmentInstallLocation("/");
        busiEqmWarning.setSubEquipmentManufactor("/");
        busiEqmWarning.setSubEquipmentName("/");
        busiEqmWarning.setMainTreeId("/");
        busiEqmWarning.setMainEquipmentId("/");
        busiEqmWarning.setSensorBrand("/");
        busiEqmWarning.setSensorInstallLocation("/");
        busiEqmWarning.setSensorManufactor("/");
        busiEqmWarning.setSensorName("/");
        busiEqmWarning.setSiteId("/");
        busiEqmWarningDao.saveOrUpdate(busiEqmWarning);
        busiEqmWarningService.saveBusiEqmWarningInfo(busiEqmWarning, json);
        return busiEqmWarning;
    }
}
