package com.template.service.impl;
import com.alibaba.fastjson.JSONObject;
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 com.template.util.ToIoTDB;
import lombok.extern.log4j.Log4j2;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.session.SessionDataSet;
import org.apache.iotdb.session.util.Version;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * @Author：liuxinyue
 * @Package：com.template.service.impl
 * @Project：cloud-server-c
 * @name：TemplateServiceImp
 * @Date：2024/9/20 12:12
 */
@Log4j2
@Service
public class TemplateServiceImpl implements TemplateService{

    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private CarService carService;

    @Autowired
    private MessageTemplateTypeService messageTemplateTypeService;

    @Autowired
    private ToIoTDB toIoTDB;

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

    @Override
    public void messageParsing(String templateMessage) throws SQLException, IoTDBConnectionException, ClassNotFoundException, StatementExecutionException {
        //给一个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);
        log.info("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));
            }

            log.info("解析后的报文是:"+jsonObject);

        }
    }



    public void insertIoTDB(JSONObject jsonObject) throws SQLException, ClassNotFoundException, IoTDBConnectionException, StatementExecutionException {

        System.out.println("Hello IoTDB Java Example");
        //初始化与连接
        Session session = new Session.Builder()
                .host("47.116.173.119")
                .port(6667)
                .username("root")
                .password("root")
                .version(Version.V_0_12)
                .build();
        //开启Session RPC不压缩
        session.open(false);
        session.open(false);
        log.info("写入数据");
        //写入数据
        List<Object> values = new ArrayList<>();
        values.add(jsonObject);
        insertRecord(session, (List<Object>) jsonObject);
        //添加sql语句
        String sql="INSERT INTO template (vinCode, ' or timeStamp' or  longItude, latitude, speedVehicle, totalMileage, totalVoltage) VALUES(0, 0, 0, 0, 0, 0, 0)";
    }

    private static void insertRecord(Session session,List<Object> values) throws SQLException, ClassNotFoundException, IoTDBConnectionException, StatementExecutionException {

        List<String> strings = new ArrayList<>();

        List<TSDataType> objects = new ArrayList<>();

        strings.add("status");

        objects.add(TSDataType.INT32);

        session.insertRecord("root.test.test",System.currentTimeMillis(),strings,objects,values);

        System.out.println("----------------写入数据成功----------------");
    }

    private static void queryRecord(Session session) throws IoTDBConnectionException, StatementExecutionException {

        System.out.println("----------------查询数据开始----------------");

       try(SessionDataSet sessionDataSet = session.executeLastDataQuery(Collections.singletonList("select status from root.test.test"))){
           System.out.println(sessionDataSet.getColumnNames());
           sessionDataSet.setFetchSize(1024);
           while(sessionDataSet.hasNext()){
               System.out.println(sessionDataSet.hasNext());
           }
       }
        System.out.println("----------------查询数据结束----------------");

    }


}
