package com.muyu.enterprise.service.impl.carImpl;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.enterprise.domain.car.MessageValue;
import com.muyu.enterprise.domain.req.car.MessageValueReq;
import com.muyu.enterprise.domain.resp.car.MessageValueListResp;
import com.muyu.enterprise.mapper.car.MessageValueMapper;
import com.muyu.enterprise.service.car.MessageValueService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

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

/**
 * @Author：李庆帅
 * @Package：com.muyu.car.service.impl
 * @Project：cloud-server
 * @name：MessageValueServiceImpl
 * @Date：2024/9/26 22:32
 * @Description: 报文数据业务层
 */
@Log4j2
@Service
public class MessageValueServiceImpl
extends ServiceImpl<MessageValueMapper,
        MessageValue> implements MessageValueService
{
    /**
     * 报文类型持久层
     */
    @Resource
    private  MessageValueMapper messageValueMapper;
    /**
     * Redis缓存
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    public MessageValueServiceImpl(MessageValueMapper messageValueMapper) {
        this.messageValueMapper = messageValueMapper;
    }
    /**
     * 报文数据列表查询
     * @param messageValueReq 请求对象
     * @return 返回结果
     */
    @Override
    public List<MessageValueListResp> findAll(MessageValueReq messageValueReq) {
        LambdaQueryWrapper<MessageValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(
                MessageValue::getTemplateId, messageValueReq.getMessageTemplateId()
        );
        queryWrapper.eq(
                MessageValue::getMessageType, messageValueReq.getMessageType()
        );
        List<MessageValue> list = this.list(queryWrapper);
        return list.stream()
                .map(messageValue -> MessageValueListResp.valueBuild(
                                messageValue
                        )
                )
                .toList();
    }
    /**
     * 报文转换测试
     * @param testStr 请求参数
     * @return 返回结果
     */
    @Override
    public JSONObject analysis(String testStr) {

        if (testStr.length() < 18) {
            throw new RuntimeException("报文格式不正确");
        }
        //根据空格切割数据
        String[] hexArray = testStr.split(" ");
        StringBuilder result = new StringBuilder();
        for (String hex : hexArray) {
            int decimal = Integer.parseInt(hex, 16);
            result.append((char) decimal);
        }
        log.info(result);
        //取出车辆VIN码
        String vehicleVin = result.substring(1, 18);
        log.info("车辆VIN:" + vehicleVin);
        //根据车辆VIN码, 查找到报文模版id
        Long templateId = messageValueMapper.getTemplateId(vehicleVin);
        log.info("模版id:" + templateId);
        //获取到报文模版的列表
        List<MessageValueListResp> templateList = null;
        if (redisTemplate.hasKey("messageTemplate" + templateId)) {
            List<Object> list = redisTemplate.opsForList().range("messageTemplate" + templateId, 0, -1);
            ArrayList<MessageValueListResp> arrayList = new ArrayList<>();
            for (Object o : list) {
                String obj = (String) o;
                MessageValueListResp messageValue = JSON.parseObject(obj, MessageValueListResp.class);
                arrayList.add(messageValue);
            }
            log.info("Redis查询成功");
            templateList = arrayList;
        } else {
            List<MessageValueListResp> list = messageValueMapper.getTemplateList(templateId);
            redisTemplate.opsForList().rightPushAll("messageTemplate" + templateId, list);
            log.info("数据库查询成功");
            templateList = list;
        }
        //判断报文模版列表不为空
        if (templateList == null){
            throw new RuntimeException("报文模板为空");
        }
        //存储报文模板解析后数据
        JSONObject jsonObject = new JSONObject();
        for (MessageValueListResp messageValue : templateList) {
            //起始位下标
            Integer startIndex = messageValue.getMessageStartIndex() - 1;
            //截止位下标
            Integer endIndex = messageValue.getMessageEndIndex();
            //根据报文模版截取数据
            String value = result.substring(startIndex, endIndex);
            //存入数据
            jsonObject.put(messageValue.getMessageLabel(), value);
        }
        for (Map.Entry<String, Object> stringObjectEntry : jsonObject) {
            log.info(stringObjectEntry.getKey() + ":" + stringObjectEntry.getValue());
        }
        return jsonObject;
    }

    @Override
    public List<MessageValueListResp> findByTemplateId(Long templateId) {
        LambdaQueryWrapper<MessageValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MessageValue::getTemplateId,templateId);
        List<MessageValue> list = this.list();
        return list.stream()
                .map(messageValue ->MessageValueListResp.valueBuild(
                        messageValue
                )
                ).toList();
    }


}
