package com.yeejoin.amos.boot.module.jxiop.biz.emqx;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jxiop.api.dto.BizMessage;
import com.yeejoin.amos.boot.module.jxiop.api.dto.TableContentVo;
import com.yeejoin.amos.boot.module.jxiop.api.feign.McbWarningFeign;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.component.emq.EmqxListener;

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

@Component
@Slf4j
public class JobRawDataUrlMessage extends EmqxListener {
    @Resource
    protected EmqKeeper emqKeeper;

    @Resource
    private McbWarningFeign mcbWarningFeign;


    // 江西电建接收红黄绿码主题
    private static final String UPDATE_RAWDATA_JOBURL = "update/rawData/jobUrl";

    @PostConstruct
    void init() throws Exception {
        emqKeeper.subscript(UPDATE_RAWDATA_JOBURL, 2, this);
    }

    @Override
    public void processMessage(String topic, MqttMessage message) {
        log.info("修改工单url数据{}", new String(message.getPayload()));
        JSONObject ja = JSON.parseObject(new String(message.getPayload()));
        jxIopUpdate(ja);
    }

    @Async("async")
    public void jxIopUpdate(JSONObject analysisResult) {
        FeignClientResult<String> sevenEntityMcb = null;
        try {
            sevenEntityMcb = mcbWarningFeign.getWarningInfoByTraceId(analysisResult.get("traceId").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sevenEntityMcb != null && 200 == sevenEntityMcb.getStatus() && CharSequenceUtil.isNotEmpty(sevenEntityMcb.getResult())) {
            String result = sevenEntityMcb.getResult();
            BizMessage alarmEvent = JSON.parseObject(result, BizMessage.class);
            List<Map<String, String>> list = new ArrayList<>();
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("key", "1");
            hashMap.put("name", "工单详情");
            hashMap.put("url", analysisResult.get("url").toString());
            list.add(hashMap);
            TableContentVo tableContentVo = new TableContentVo("10", "链接跳转", list, "jump");
            alarmEvent.getBizInfo().getDynamicDetails().get(0).getTabContent().add(tableContentVo);
            String rawData = JSON.toJSONString(alarmEvent);
            mcbWarningFeign.updateRawDataByTraceId(analysisResult.get("traceId").toString(), rawData);
            log.info("预警rawData字段修改完成,rawData数据:{}", rawData);
        }

    }
}
