package com.muyu.parse.process;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.muyu.common.core.domain.Result;

import com.muyu.domain.req.MessageValueReq;
import com.muyu.domain.resp.MessageValueListResp;
import com.muyu.parse.uitl.DataParseUtil;
import com.muyu.remote.RemoteMessageValueService;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @Author xie ya ru
 * @Date 2024/9/28 21:14
 * @注释
 */
@Log4j2
public class ProcessData {

    @Resource
    private static RemoteMessageValueService remoteMessageValueService;

    @Resource
    private static RedisTemplate<String, Object> redisTemplate;

    public static JSONObject DataConversion(String jsonVin ) {
        String vin = DataParseUtil.dataParsing(jsonVin);

        Result<Long> byTemplateId = remoteMessageValueService.findByTemplateId(vin);

        Long templateId = byTemplateId.getData();
        List<MessageValueListResp> templateList;
        try{
        //从Redis中获取报文模版信息
        if (redisTemplate.hasKey("messageValue:" + templateId)) {
            List<Object> list = redisTemplate.opsForList().range("messageValue:" + templateId, 0, -1);
            templateList = list.stream()
                    .map(obj -> JSON.parseObject(obj.toString(), MessageValueListResp.class))
                    .toList();
            log.info("Redis缓存查询成功");
        } else {

            Result<List<MessageValueListResp>> byTemplate = remoteMessageValueService.findAll(MessageValueReq.builder().messageTemplateId(templateId).build());
            templateList = byTemplate.getData();
            templateList.forEach(
                    listResp ->
                            redisTemplate.opsForList().rightPush(
                                    "messageValue:" + templateId, JSON.toJSONString(listResp)
                            )
            );
        }
            log.info("数据库查询成功");
        } catch (Exception e) {
                throw new RuntimeException("获取报文模板失败");
            }
            //判断报文模板列表不为空
            if (templateList.isEmpty()) {
                throw new RuntimeException("报文模版为空");
            }
            //存储报文模版解析后的数据
            JSONObject jsonObject = new JSONObject();
            for (MessageValueListResp messageValue : templateList) {
                //起始位下标
                Integer startIndex = messageValue.getMessageStartIndex() - 1;
                //结束位下标
                Integer endIndex = messageValue.getMessageEndIndex();
                //根据报文模版截取数据
                String value = vin.substring(startIndex, endIndex);
                //存入数据
                System.out.println("标签"+messageValue.getMessageLabel()+"值"+value);
                jsonObject.put(messageValue.getMessageLabel(), value);
            }
            return jsonObject;


    }

}
