package com.template.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.muyu.common.core.domain.Result;
import com.template.domain.*;
import com.template.mapper.TemplateMapper;
import com.template.service.CarService;
import com.template.service.MessageTemplateTypeService;
import com.template.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.List;
/**
 * @Author：liuxinyue
 * @Package：com.template.service.impl
 * @Project：cloud-server-c
 * @name：TemplateServiceImp
 * @Date：2024/9/20 12:12
 */
@Service
public class TemplateServiceImpl implements TemplateService{

    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private CarService carService;

    @Autowired
    private MessageTemplateTypeService messageTemplateTypeService;

    @Override
    public List<Template> templateList() {
        return templateMapper.templateList();
    }

    @Override
    public void messageParsing(String templateMessage) {
        //给一个JSON对象
        JSONObject jsonObject = new JSONObject();
        //先截取出VIN码 然后根据VIN码查询这个车属于什么类型
        if(templateMessage.length()<18){
            throw new RuntimeException("The vehicle message is incorrect");
        }
        //将报文进行切割
        String[] hexArray = templateMessage.split(" ");
        StringBuilder result = new StringBuilder();
        for (String hex : hexArray) {
            int decimal = Integer.parseInt(hex, 16);
            result.append((char) decimal);
        }
        //取出VIN码
        String carVin = result.substring(0, 18-1);
        System.out.println("carVin码为:"+carVin);
        //根据VIN码获取车辆信息
        SysCar carByVin = carService.findCarByVin(carVin);
        if(carByVin==null){
            throw new RuntimeException("Check this car!!");
        }else{
            //根据车辆类型ID获取车辆类型名称
            CarType carTypeById = carService.findCarTypeById(carByVin.getCarTypeId());
            //查询报文模版
            Template templateDate=templateMapper.findTemplateByName(carTypeById.getTypeName());
            //根据报文模版的ID查询对应的模版
            List<MessageTemplateType> messageByTemplateName = messageTemplateTypeService.findMessageByTemplateName(templateDate.getTemplateId());
            //将模版里面有的配置进行循环
            for (MessageTemplateType messageTemplateType : messageByTemplateName) {
                //开始位置
                Integer startIndex = messageTemplateType.getStartIndex();
                //结束位置
                Integer endIndex = messageTemplateType.getEndIndex();
                //将每个解析后的字段都存入到JSON对象中
                jsonObject.put(messageTemplateType.getMessageField(), result.substring(startIndex, endIndex-1));
            }
            System.out.println("解析后的报文是:"+jsonObject);
        }
    }

    //连接IoTDB数据库并执行插入操作
    public void addIoTDBTemplate(MessageTemplate messageTemplate) throws ClassNotFoundException {
        // IoTDB 数据库的连接信息
        String url = "jdbc:iotdb://47.116.173.119:6667/";
        String user = "root";
        String password = "root";
        try {
            // 注册 JDBC 驱动
            Class.forName("org.apache.iotdb.jdbc.IoTDBDriver");
            System.out.println("JDBC Driver Registered!");
            // 数据库连接
            Connection connection = DriverManager.getConnection(url, user, password);
            System.out.println("Connected to IoTDB!");
            // 插入数据的 SQL 语句
            String insertSQL = "INSERT INTO root.four.message_template ( vin_code, time_stamp, long_itude, latitude, speed_vehicle, total_mileage, total_voltage, combined_current, insulation_resistance, " +
                    "gear_position, accelerator_pedal_travel_value, brake_pedal_travel_value, specific_fuel_consumption, motor_controller_temperature, motor_speed, motor_torque, motor_temperature, motor_voltage, motor_current, " +
                    "power_battery_remaining_soc, maximum_feedback_power, maximum_discharge_power, bms_self_check_counter, power_battery, total_voltage_load_side, maximum_voltage, minimum_voltage, maximum_temperature, minimum_temperature," +
                    " available_capacity, vehicle_status, charging_state, operational_status, soc, energy_storage_devices," +
                    " drive_motor_condition, whether_works, eas, ptc, eps, abs, mcu, heating_state, power_battery_status, state_battery_insulation, dcdc, chg, check_digit, cutoff_bit) VALUES ( ?, ?, ?, ?, ?, ?, ?, " +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ??, ?, ?, ?, ?, ?, ?, ?, ?, " +
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            // 使用 PreparedStatement 插入数据
            PreparedStatement preparedStatement = connection.prepareStatement(insertSQL);
            // 执行插入
            preparedStatement.execute();
            System.out.println("Data inserted successfully!");
            // 关闭连接
            preparedStatement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            System.err.println("JDBC Driver not found: " + e.getMessage());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
