package com.muyu.parsing.controller;

import com.alibaba.fastjson2.JSONObject;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.poi.ExcelUtil;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.common.kafka.constants.KafkaConstants;
import com.muyu.common.security.annotation.RequiresPermissions;
import com.muyu.parsing.domain.KafKaData;
import com.muyu.parsing.domain.SysCarMessage;
import com.muyu.parsing.domain.resp.SysMessageResp;
import com.muyu.parsing.service.ISysCarMessageService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 车辆报文记录Controller
 *
 * @author muyu
 * @date 2024-09-18
 */
@Slf4j
@RestController
@RequestMapping("/messageInfo")
public class SysCarMessageController extends BaseController {
    @Resource
    private ISysCarMessageService sysCarMessageService;
    @Resource
    private KafkaProducer<String, String> kafkaProducer;
    static String TEST = "56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56 56";

//    @Autowired
//    private KafkaTemplate<String, Object> kafkaTemplate;


    /**
     * 查询车辆报文记录列表
     */
//    @RequiresPermissions("message:message:list")
    @Transactional
    @GetMapping("/list")
    public Result<List<SysCarMessage>> list(SysCarMessage sysCarMessage) throws ExecutionException, InterruptedException {

        List<SysCarMessage> list = sysCarMessageService.selectSysCarMessageList(sysCarMessage);
        if (list == null || list.isEmpty()) {
            return Result.error();  //为空返回错误信息
        }
        List<KafKaData> kafKaDataList = new ArrayList<>();
        String[] test = TEST.split(" ");
        String[] results = new String[list.size()];
//        HashMap<String, CompletableFuture<String>> futures = new HashMap<>();
        for (SysCarMessage carMessage : list) {
            int start = Integer.parseInt(carMessage.getMessageStartIndex()) - 1;
            int end = Integer.parseInt(carMessage.getMessageEndIndex());
            StringBuilder hexBuilder = new StringBuilder();
            for (int i = start; i < end; i++) {
                hexBuilder.append(test[i]);
            }
            String hex = hexBuilder.toString();
            char[] result = new char[hex.length() / 2];
            for (int x = 0; x < hex.length(); x += 2) {
                int high = Character.digit(hex.charAt(x), 16);
                int low = Character.digit(hex.charAt(x + 1), 16);
                result[x / 2] = (char) ((high << 4) + low);
            }
            String value = new String(result);
            kafKaDataList.add(KafKaData.builder()
                    .key(carMessage.getMessageTypeCode())
                    .label(carMessage.getMessageTypeCode())
                    .value(value)
                    .type("String")
                    .build());
        }

//        String jsonString = """
//                [{
//                    "key": "vin",
//                    "label": "VIN码",
//                    "type": "String",
//                    "value": "vin131413534474"
//                },{
//                    "key": "timestamp",
//                    "label": "时间戳",
//                    "type": "String",
//                    "value": "1727525252127"
//                },{
//                    "key": "latitude",
//                    "label": "纬度",
//                    "type": "String",
//                    "value": "66.898"
//                },{
//                    "key": "longitude",
//                    "label": "经度",
//                    "type": "String",
//                    "value": "99.124"
//                }]""";
        String jsonString = JSONObject.toJSONString(kafKaDataList);
        ProducerRecord<String, String> producerRecord = new ProducerRecord<>(KafkaConstants.KafkaTopic, jsonString);
        kafkaProducer.send(producerRecord);
        log.info("消息发送成功：{}", jsonString);
        return Result.success(list);
    }


    @RequiresPermissions("message:message:dobList")
    @GetMapping("/dobList")
    public Result<List<SysMessageResp>> dobList(SysMessageResp sysMessageResp) {
        List<SysMessageResp> list = sysCarMessageService.dobList(sysMessageResp);
        return Result.success(list);
    }


    /**
     * 导出车辆报文记录列表
     */
    @RequiresPermissions("message:message:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysCarMessage sysCarMessage) {
        List<SysCarMessage> list = sysCarMessageService.selectSysCarMessageList(sysCarMessage);
        ExcelUtil<SysCarMessage> util = new ExcelUtil<SysCarMessage>(SysCarMessage.class);
        util.exportExcel(response, list, "车辆报文记录数据");
    }

    /**
     * 获取车辆报文记录详细信息
     */
    @RequiresPermissions("message:message:query")
    @GetMapping(value = "/{id}")
    public Result<List<SysCarMessage>> getInfo(@PathVariable("id") Long id) {
        return success(sysCarMessageService.selectSysCarMessageById(id));
    }

    /**
     * 新增车辆报文记录
     */
    @RequiresPermissions("message:message:add")
    @PostMapping
    public Result<Integer> add(
            @Validated @RequestBody SysCarMessage sysCarMessage) {
        if (sysCarMessageService.checkIdUnique(sysCarMessage)) {
            return error("新增 车辆报文记录 '" + sysCarMessage + "'失败，车辆报文记录已存在");
        }
        return toAjax(sysCarMessageService.save(sysCarMessage));
    }

    /**
     * 修改车辆报文记录
     */
    @RequiresPermissions("message:message:edit")
    @PutMapping
    public Result<Integer> edit(
            @Validated @RequestBody SysCarMessage sysCarMessage) {
        if (!sysCarMessageService.checkIdUnique(sysCarMessage)) {
            return error("修改 车辆报文记录 '" + sysCarMessage + "'失败，车辆报文记录不存在");
        }
        return toAjax(sysCarMessageService.updateById(sysCarMessage));
    }

    /**
     * 删除车辆报文记录
     */
    @RequiresPermissions("message:message:remove")
    @DeleteMapping("/{ids}")
    public Result<Integer> remove(@PathVariable("ids") Long[] ids) {
        sysCarMessageService.removeBatchByIds(Arrays.asList(ids));
        return success();
    }

}
