/*
 * 文 件 名:  MessageHandler
 * 版    权:  浩鲸云计算科技股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  lvwenbin
 * 修改时间:  2024/4/30
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.huashe.park.collect.handle;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.huashe.park.collect.config.TopicDataCfg;
import com.huashe.park.collect.core.TopicMsgEngine;
import com.huashe.park.collect.event.MachineRealtimeEventListener;
import com.huashe.park.common.ByteArrayUtil;
import com.huashe.park.common.DateTimeUtil;
import com.huashe.park.core.redis.RedisProxy;
import com.huashe.park.core.service.IMachineProcessResultService;
import com.huashe.park.core.service.IMachineProcessService;
import com.huashe.park.domain.entity.MachineProcess;
import com.huashe.park.domain.entity.MachineProcessResult;

/**
 * 消息处理handle <功能详细描述>
 *
 * @author lvwenbin
 * @version [版本号, 2024/4/30]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service("RootMsgHandler")
public class RootMsgHandler extends TopicMsgEngine {

    @Autowired
    private TopicDataCfg topicDataCfg;

    private final static String TOPIC_NAME = "topic";

    private static final String TOPIC_PAYLOAD = "payload";

    private static final Logger log = LoggerFactory.getLogger(RootMsgHandler.class);

    private final List<LinkedBlockingQueue<JSONObject>> messageQueueList = new ArrayList<>(2);

    @Autowired
    private IMachineProcessService machineProcessService;

    @Autowired
    private IMachineProcessResultService machineProcessResultService;

    @Autowired
    private MachineRealtimeEventListener machineRealtimeEventListener;

    @Autowired
    private RedisProxy redisProxy;

    @PostConstruct
    public void init() {
        super.init();
        this.setEngineName("终端机械指标");
        start();
    }

    @Override
    public List<LinkedBlockingQueue<JSONObject>> getQueue() {
        return messageQueueList;
    }

    @Override
    public void handle(String topic, byte[] payload) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(TOPIC_NAME, topic);
        if (topic.endsWith(topicDataCfg.getResultTopic().getName())) {
            JSONObject data = topicDataCfg.byteFormat(payload, topicDataCfg.getResultTopic().getProtocol());
            jsonObject.put("key", data.get("pileId"));
            jsonObject.put(TOPIC_PAYLOAD, data);
        }

        if (topic.endsWith(topicDataCfg.getProcessTopic().getName())) {
            JSONObject data = topicDataCfg.byteFormat(payload, topicDataCfg.getProcessTopic().getProtocol());
            jsonObject.put("key", data.get("pileId"));
            jsonObject.put(TOPIC_PAYLOAD, data);
        }
        push(jsonObject);
    }

    @Override
    public void messageBizHandle(JSONObject json) {
        String topic = json.getString(TOPIC_NAME);
        // 结果数据处理
        if (topic.endsWith(topicDataCfg.getResultTopic().getName())) {
            JSONObject jsonObject = json.getJSONObject(TOPIC_PAYLOAD);
            MachineProcessResult machineProcess = JSON.parseObject(jsonObject.toString(), MachineProcessResult.class);
            machineProcess.setRecordTime(DateTimeUtil.getDateFromMills(machineProcess.getDataTime()));
            machineProcess.setDt(
                DateTimeUtil.getDateFromMills(machineProcess.getDataTime(), DateTimeUtil.DateFormatter.yyyyMMdd));
            // 结合下行深度effectiveDown 以及 开始和结束时间 sendStartTime sendEndTime，计算平均下行速度
            machineProcess.setAvgSpeed(machineProcess.getEffectiveDown()
                / (machineProcess.getEndTime() - machineProcess.getStartTime()) * 1000);
            // 结合下行深度effectiveDown 以及 开始和结束时间 pullingStartTime pullingEndTime， 计算平均拔管速度。并且保留两位小数
            machineProcess.setAvgUpSpeed(machineProcess.getEffectiveDown()
                / (machineProcess.getPullingEndTime() - machineProcess.getPullingStartTime()) * 1000);
            machineProcessResultService.insertMachineProcessResult(machineProcess);
            machineRealtimeEventListener.handleConsResult(machineProcess);
            return;
        }
        if (topic.endsWith(topicDataCfg.getProcessTopic().getName())) {
            JSONObject jsonObject = json.getJSONObject(TOPIC_PAYLOAD);
            MachineProcess machineProcess = JSON.parseObject(jsonObject.toString(), MachineProcess.class);
            machineProcess.setRecordTime(DateTimeUtil.getDateFromMills(machineProcess.getDataTime()));
            machineProcess.setDt(
                DateTimeUtil.getDateFromMills(machineProcess.getDataTime(), DateTimeUtil.DateFormatter.yyyyMMdd));
            machineProcessService.insertMachineProcess(machineProcess);
            machineRealtimeEventListener.handleConsProcess(machineProcess);
        }
    }

    public static void main(String[] args) {
        byte[] bytes = ByteArrayUtil.hexString2ByteArray(
            "590200000001951C387150353061623664373875393537343066346D75656466653462FA7E6A04ACCE5041A8C64B37EA401C4163077186A3CE50410F490C00A6401C4163077186A3CE5041FE480C00A6401C41000000000000000000000000000000000000000000000000000001951C37D7CB000001951C38711A00000000643BDF4F8DD72C400000000000000000000000000000000000000000000000000000204100000000000000005902000000000000000000000000000075393537343066345F313130445339383339333230303030325F");
        // System.out.println(HexUtil.encodeHex(ByteArrayUtil.double2ByteArray_Big_Endian(4405936.0690)));
        System.out.println(ArrayUtils.subarray(bytes, bytes.length - 1, bytes.length));
    }
}