package com.limap.controller.work;

import com.alibaba.fastjson.JSONObject;
import com.limap.core.basic.domain.AquDevice;
import com.limap.core.basic.service.IAquDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.net.URI;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Lenovo
 */
@Component
@SuppressWarnings("AlibabaThreadShouldSetName")
@Slf4j
public class EquipmentDataWork implements ApplicationRunner {

    private static final String consumerGroupId = "7F0WdwTYzdoUhss7zBDK000100";

    private static final String accessKey = "LTAI5tRnPowmTLjH181nSbsR";
    private static final String accessSecret = "Vh2LoAM1t3XuMUVy2wTWSACJ97kOUW";


    private static final String iotInstanceId = "";

    private static final String clientId = UUID.randomUUID().toString();

    private static final String host = clientId+ ".iot-amqp.cn-shanghai.aliyuncs.com";

    // 指定单个进程启动的连接数,最大64个连接
    private static final int connectionCount = 8;

    @Autowired
    private IAquDeviceService aquDeviceService;

    @Value("${ali.iot.amqpEnabled:true}")
    private boolean amqpEnabled;

    /**
     * 业务处理异步线程池，线程池参数可以根据您的业务特点调整，或者您也可以用其他异步方式处理接收到的消息。
     */
    private final static ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 4, 200, TimeUnit.SECONDS,
            new LinkedBlockingQueue(50000));


    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (!amqpEnabled) {
            log.info("AMQP 数据接收服务已关闭 [ali.iot.amqpEnabled=false]");
            return;
        }

        List<Connection> connections = new ArrayList<>();

        //参数说明，请参见AMQP客户端接入说明文档。
        for (int i = 0; i < connectionCount; i++) {
            long timeStamp = System.currentTimeMillis();
            //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
            String signMethod = "hmacsha1";

            //userName组装方法，请参见AMQP客户端接入说明文档。
            String userName = clientId + "-" + i + "|authMode=aksign"
                    + ",signMethod=" + signMethod
                    + ",timestamp=" + timeStamp
                    + ",authId=" + accessKey
                    + ",iotInstanceId=" + iotInstanceId
                    + ",consumerGroupId=" + consumerGroupId
                    + "|";
            //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
            String signContent = "authId=" + accessKey + "&timestamp=" + timeStamp;
            String password = doSign(signContent, accessSecret, signMethod);
            String connectionUrl = "failover:(amqps://" + host + ":5671?amqp.idleTimeout=80000)"
                    + "?failover.reconnectDelay=30";

            Hashtable<String, String> hashtable = new Hashtable<>();
            hashtable.put("connectionfactory.SBCF", connectionUrl);
            hashtable.put("queue.QUEUE", "default");
            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
            Context context = new InitialContext(hashtable);
            ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF");
            Destination queue = (Destination)context.lookup("QUEUE");
            // 创建连接。
            Connection connection = cf.createConnection(userName, password);
            connections.add(connection);

            ((JmsConnection)connection).addConnectionListener(myJmsConnectionListener);
            // 创建会话。
            // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。
            // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            connection.start();
            // 创建Receiver连接。
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(messageListener);
        }
    }

    private final MessageListener messageListener = message -> {
        try {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try{
                        processMessage(message);
                    }catch (Exception e){
                        log.error("processMessage occurs error ");
                    }

                }
            });
        } catch (Exception e) {
            log.error("submit task occurs exception ", e);
        }
    };

    /**
     * 在这里处理您收到消息后的具体业务逻辑。
     */
    private void processMessage(Message message) {
        try {
            byte[] body = message.getBody(byte[].class);
            String content = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
//            log.info("receive message"
//                    + ",\n topic = " + topic
//                    + ",\n messageId = " + messageId
//                    + ",\n content = " + content);

            dealDate(content);
        } catch (Exception e) {
            log.error("processMessage occurs error ", e);
        }
    }

    private static final JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        /**
         * 连接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            log.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 尝试过最大重试次数之后，最终连接失败。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            log.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 连接中断。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            log.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 连接中断后又自动重连上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            log.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {}

        @Override
        public void onSessionClosed(Session session, Throwable cause) {}

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {}

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {}
    };

    /**
     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
     */
    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }


    private void dealDate(String s) {
        if (!amqpEnabled) {
            return;
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(s);
            JSONObject items = jsonObject.getJSONObject("items");
            String iotId = jsonObject.getString("iotId");
            String deviceName = jsonObject.getString("deviceName");
            String status = jsonObject.getString("status");
            AquDevice aquDevice = aquDeviceService.getInfoByIotId(iotId);
            if(aquDevice != null){
                aquDeviceService.dealNowAndHistoryData(aquDevice,items);
            }
        }catch (Exception e){
            log.error("WOrk--dealDate error",e);
        }
    }
}
